Timestamp Types¶
Choose a clock when creating a logger. TSC minimizes caller overhead, the system clock records wall time directly, and a custom clock can supply hardware, simulation or replay time.
Timestamp Recording¶
The caller timestamps each record just before publishing, after waiting for space, frontend formatting and copying the payload. Preemption between reading the clock and publishing can still delay a record.
BackendOptions::log_timestamp_ordering_grace_period(default 5 µs) lets earlier timestamps arrive from other threads. If a queue head stays ahead of the wall-clock cutoff, one grace period of steady time from its first observation makes it eligible even after a backward clock adjustment.The backend writes eligible records from other queues while waiting. If none are eligible, it waits the shorter of the grace period and
BackendOptions::sleep_duration. A zero sleep polls immediately.Backend::stop()drains without the grace period. User clocks returningTimestampType::EpochNanosecondsalso bypass it.
Timestamps in one queue should normally be non-decreasing. BackendOptions::ensure_monotonic_output_timestamps
corrects sink-visible times for regular log, metric and binary records if a clock moves backward.
Flushed backtraces keep their original capture times. A thread that logs through both a TSC and a system
clock logger reads two clocks, so its records can step back by tens to a few hundred nanoseconds; the same
option corrects those steps.
If a regular log, metric or binary timestamp predates one already selected for output, the backend can
suggest a larger grace period through BackendOptions::error_notifier.
Quill WARNING: A record is 571 us out of timestamp order. For delayed publishers, consider increasing BackendOptions::log_timestamp_ordering_grace_period to at least 600 us.
The suggested period adds the observed difference in whole microseconds to the current period, rounded up to one significant digit. The worker reports only increases over its last suggestion. More time helps a delayed producer, but cannot repair a clock running backward.
Zero grace or enabled monotonic correction disables the notification. The comparison excludes custom
EpochNanoseconds timelines. Monotonic correction orders those records among themselves, separately
from real-time loggers.
Timestamp Methods¶
The default frontend uses the same Logger* type for all three choices. One binary can select live or
simulation time at runtime.
TSC (
ClockSource::tsc(), the default). The caller reads raw__rdtscticks. The backend’sRdtscClocktakes about 10 ms to calibrate on first use on x86 (AArch64 reads the counter frequency), then converts ticks to wall time with a lock-free algorithm. It resynchronizes every 500 ms by default. Use an invariant TSC synchronized across cores. Drift is usually small, but captures from different cores can use different calibration points across a resync. Timestamps may then appear a few microseconds out of order.System (
ClockSource::system()).std::chrono::system_clock::now()costs more on the caller but gives wall time immediately, without TSC calibration or resync drift. Use it when wall-time accuracy or strict chronological order matters.User (
ClockSource::custom(clock)). The caller readsUserClockSource::now()virtually by default. The backend interprets the result using the optional virtualtimestamp_type() const noexcept.
Providing a Custom Timestamp¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
Frontend Clock Selection¶
FrontendOptions::clock_type defaults to quill::ClockSource, which holds any of the three runtime choices.
Options without clock_type also use runtime selection.
To make the read eligible for inlining, set clock_type to the UserClockSource subclass that implements
now() const noexcept. Pass ClockSource::custom(clock) directly to the factory so it can check the type.
The option selects dispatch, and the argument supplies the instance and state.
The selected class may be abstract if it implements
now()and the instance is derived. Virtual inheritance fromUserClockSourceprevents the frontend’sstatic_castand the first log call fails to compile.Direct dispatch bypasses further overrides of
now(). The backend still callstimestamp_type()virtually. Return aTimestampTypematching the selected implementation.
Custom timestamp representations
TimestampType::TscTicksreturns raw counter ticks. The backend converts them to epoch nanoseconds and applies the grace period as for the built-in TSC.TimestampType::WallClockNanosecondsreturns real Unix-epoch nanoseconds, for example from PTP, a NIC,CLOCK_REALTIMEor a custom TSC conversion. Ordering and grace match the system clock. Keep the clock aligned with system time. With a nonzero grace period, a clock that runs ahead can make each new queue head wait a full grace period from its first observation, allowing a backlog to build. A PTP hardware clock on TAI is 37 s ahead of UTC. Subtract the offset innow()or returnTimestampType::EpochNanoseconds.TimestampType::EpochNanosecondsis the default for compatibility with existing clocks. Use it for simulations or a replay of recorded data. Marking replay data as wall time can trigger reordering diagnostics or advance its timestamps to other loggers’ wall times under monotonic correction.
// A clock that follows real time, such as a PTP or NIC hardware clock on UTC: it has to agree with
// the system clock, which the backend compares its timestamps with. This sample reads
// std::chrono::system_clock in its place.
struct WallClock : quill::UserClockSource
{
uint64_t now() const noexcept override
{
return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
// The records wait for the grace period and are ordered with those of the other loggers
quill::TimestampType timestamp_type() const noexcept override
{
return quill::TimestampType::WallClockNanoseconds;
}
};
int main()
{
WallClock clock;
quill::Backend::start();
std::shared_ptr<quill::Sink> sink =
quill::Frontend::create_or_get_sink<quill::ConsoleSink>("custom_wall_clock_console");
quill::Logger* logger = quill::Frontend::create_or_get_logger(
"custom_wall_clock_logger", sink, quill::PatternFormatterOptions{}, quill::ClockSource::custom(clock));
LOG_INFO(logger, "Timestamp read from a wall clock");
logger->flush_log();
quill::Frontend::remove_logger_blocking(logger);
quill::Backend::stop();
}
ClockSource::custom(clock) borrows the clock by reference. Keep it alive through the logger’s lifetime and
pending records. Both methods must be thread-safe and the timestamp representation must stay constant.
Loggers may use different instances. Quill reads the clock once per enqueued record and skips it for dropped
records. Zero is a valid nanosecond timestamp.
Declare uint64_t now() const noexcept override. It must return normally and must never log through Quill,
even via another logger. Nested logging can overwrite the caller’s encoded but uncommitted record.
An exception can strand a deferred argument in it.
With a concrete clock type, the instance must have that type or derive from it. A different type, a built-in source or a missing clock argument fails at compile time. Use consistent Frontend Options across the application, shared libraries and typed signal handlers.
The same factory expression works with virtual or direct dispatch.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
If every logger uses TSC, this clock eliminates runtime selection. It uses the default TSC logger’s inline read and queue encoder and can save frontend instructions, depending on compiler and build options.
struct TscClock : quill::UserClockSource
{
uint64_t now() const noexcept override { return quill::detail::rdtsc(); }
quill::TimestampType timestamp_type() const noexcept override
{
return quill::TimestampType::TscTicks;
}
};
struct TscFrontendOptions : quill::FrontendOptions
{
using clock_type = TscClock;
};
using TscFrontend = quill::FrontendImpl<TscFrontendOptions>;
using TscLogger = TscFrontend::logger_t;
int main()
{
TscClock clock;
quill::Backend::start();
std::shared_ptr<quill::Sink> sink =
TscFrontend::create_or_get_sink<quill::ConsoleSink>("custom_tsc_clock_console");
TscLogger* logger = TscFrontend::create_or_get_logger(
"custom_tsc_clock_logger", sink, quill::PatternFormatterOptions{}, quill::ClockSource::custom(clock));
LOG_INFO(logger, "Timestamp captured as raw TSC ticks");
logger->flush_log();
TscFrontend::remove_logger_blocking(logger);
quill::Backend::stop();
}
Updating Existing Logger Creation Calls¶
Replace the old enum/pointer pair with one clock selection. Omitting the argument still selects TSC.
// Previous: ..., pattern_options, ClockSourceType::User, &clock
// Current:
Frontend::create_or_get_logger("app", sink, pattern_options, ClockSource::custom(clock));
For an explicit built-in selection use ClockSource::tsc() or ClockSource::system().
Getting a Synchronized Timestamp with the Backend Thread TSC Clock¶
Use BackendTscClock to obtain a timestamp synchronized with the backend’s TSC log timestamps.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | |