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 returning TimestampType::EpochNanoseconds also 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 __rdtsc ticks. The backend’s RdtscClock takes 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 reads UserClockSource::now() virtually by default. The backend interprets the result using the optional virtual timestamp_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
#include "quill/Backend.h"
#include "quill/Frontend.h"
#include "quill/LogMacros.h"
#include "quill/Logger.h"
#include "quill/UserClockSource.h"
#include "quill/sinks/ConsoleSink.h"

#include <atomic>
#include <chrono>
#include <cstdint>
#include <utility>

/**
 * Example demonstrating custom clock usage for logging. This is particularly useful
 * when simulating events from a specific time period, allowing logs to align with
 * the simulated time.
 */

/**
 * This class needs to be thread-safe, unless only a single thread in the application calling
 * LOG_ macros from the same logger
 */
class SimulatedClock : public quill::UserClockSource
{
public:
  SimulatedClock() = default;

  /**
   * Required by TimestampClock
   * @return current time now, in nanoseconds since epoch
   */
  uint64_t now() const noexcept override { return _timestamp_ns.load(std::memory_order_relaxed); }

  /**
   * set custom timestamp
   * @param time_since_epoch timestamp
   */
  void set_timestamp(std::chrono::seconds time_since_epoch)
  {
    // always convert to nanos
    _timestamp_ns.store(static_cast<uint64_t>(std::chrono::nanoseconds{time_since_epoch}.count()),
                        std::memory_order_relaxed);
  }

private:
  std::atomic<uint64_t> _timestamp_ns{0}; // time since epoch - must always be in nanoseconds
};

int main()
{
  // Start the backend thread
  quill::BackendOptions backend_options;
  quill::Backend::start(backend_options);

  // Create a simulated timestamp class. Quill takes a pointer to this class,
  // and the user is responsible for its lifetime.
  // Ensure that the instance of this class remains alive for as long as the logger
  // object exists, until the logger is removed.
  SimulatedClock simulated_clock;

  // Get the console sink and also create a logger using the simulated clock
  auto console_sink = quill::Frontend::create_or_get_sink<quill::ConsoleSink>("sink_id_1");

  quill::Logger* logger = quill::Frontend::create_or_get_logger(
    "root", std::move(console_sink),
    quill::PatternFormatterOptions{
      "%(time) %(short_source_location:<28) LOG_%(log_level:<9) %(logger:<12) %(message)",
      "%D %H:%M:%S.%Qns", quill::Timezone::LocalTime, false},
    quill::ClockSource::custom(simulated_clock));

  // Change the LogLevel to print everything
  logger->set_log_level(quill::LogLevel::TraceL3);

  // Set our timestamp to Sunday 12 June 2022
  simulated_clock.set_timestamp(std::chrono::seconds{1655007309});
  LOG_TRACE_L3(logger, "This is a log trace l3 example {}", 1);
  LOG_TRACE_L2(logger, "This is a log trace l2 example {} {}", 2, 2.3);

  // update our timestamp
  simulated_clock.set_timestamp(std::chrono::seconds{1655039000});
  LOG_INFO(logger, "This is a log info {} example", "string");
  LOG_DEBUG(logger, "This is a log debug example {}", 4);
  logger->flush_log();
  quill::Frontend::remove_logger_blocking(logger);
  quill::Backend::stop();
}

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 from UserClockSource prevents the frontend’s static_cast and the first log call fails to compile.

  • Direct dispatch bypasses further overrides of now(). The backend still calls timestamp_type() virtually. Return a TimestampType matching the selected implementation.

Custom timestamp representations

  • TimestampType::TscTicks returns raw counter ticks. The backend converts them to epoch nanoseconds and applies the grace period as for the built-in TSC.

  • TimestampType::WallClockNanoseconds returns real Unix-epoch nanoseconds, for example from PTP, a NIC, CLOCK_REALTIME or 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 in now() or return TimestampType::EpochNanoseconds.

  • TimestampType::EpochNanoseconds is 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
#include "quill/Backend.h"
#include "quill/Frontend.h"
#include "quill/LogMacros.h"
#include "quill/sinks/ConsoleSink.h"

#include <atomic>
#include <cstdint>
#include <memory>

// Application-controlled epoch nanoseconds. A real application can supply its own clock read.
struct AppClock : quill::UserClockSource
{
  uint64_t now() const noexcept override { return timestamp_ns.load(std::memory_order_relaxed); }

  // Optional: epoch nanoseconds are also the base class default.
  quill::TimestampType timestamp_type() const noexcept override
  {
    return quill::TimestampType::EpochNanoseconds;
  }

  std::atomic<uint64_t> timestamp_ns{1655007309000000000ULL};
};

struct AppFrontendOptions : quill::FrontendOptions
{
  using clock_type = AppClock;
};

using AppFrontend = quill::FrontendImpl<AppFrontendOptions>;
using AppLogger = AppFrontend::logger_t;

int main()
{
  AppClock clock;
  quill::Backend::start();
  std::shared_ptr<quill::Sink> sink =
    AppFrontend::create_or_get_sink<quill::ConsoleSink>("custom_clock_console");
  AppLogger* logger = AppFrontend::create_or_get_logger(
    "custom_clock_logger", sink, quill::PatternFormatterOptions{}, quill::ClockSource::custom(clock));

  LOG_INFO(logger, "Application clock timestamp");
  clock.timestamp_ns.fetch_add(1000000000ULL, std::memory_order_relaxed);
  LOG_INFO(logger, "One second later");

  logger->flush_log();
  AppFrontend::remove_logger_blocking(logger);
  quill::Backend::stop();
}

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
#include "quill/Backend.h"
#include "quill/BackendTscClock.h"
#include "quill/Frontend.h"
#include "quill/LogMacros.h"
#include "quill/Logger.h"
#include "quill/sinks/ConsoleSink.h"

#include <iostream>
#include <utility>

int main()
{
  quill::Backend::start();

  auto console_sink = quill::Frontend::create_or_get_sink<quill::ConsoleSink>("sink_id_1");

  // Ensure at least one logger with quill::ClockSource::tsc() is created for BackendTscClock to function
  quill::Logger* logger = quill::Frontend::create_or_get_logger(
    "root", std::move(console_sink),
    quill::PatternFormatterOptions{
      "%(time) [%(thread_id)] %(short_source_location:<28) LOG_%(log_level:<9) %(logger:<12) "
      "%(message)",
      "%H:%M:%S.%Qns", quill::Timezone::LocalTime},
    quill::ClockSource::tsc());

  // Log an informational message which will also init the backend RdtscClock
  LOG_INFO(logger, "This is a log info example with number {}", 123);

  // The function `quill::detail::BackendManager::instance().convert_rdtsc_to_epoch_time(quill::detail::rdtsc())`
  // will return a valid timestamp only after the backend worker has started and processed
  // at least one log with `ClockSource::tsc()`.
  // This is because the Rdtsc clock is lazily initialized by the backend worker on the first log message.
  // To ensure at least one log message is processed, we call flush_log here.
  logger->flush_log();

  // Get a timestamp synchronized with the backend's clock
  uint64_t const backend_timestamp =
    static_cast<uint64_t>(quill::BackendTscClock::now().time_since_epoch().count());
  std::cout << "Synchronized timestamp with the backend: " << backend_timestamp << std::endl;

  return 0;
}