spdlog Format Flags: Complete Reference for Pattern Formatting

spdlog provides 40+ built-in format flags that allow you to customize log output through pattern strings, including timestamps, log levels, thread IDs, source locations, and color codes.

The spdlog library (available at gabime/spdlog) formats log messages using a pattern formatter that parses format strings and replaces each %-prefixed flag with corresponding runtime values. The complete flag implementation resides in include/spdlog/pattern_formatter.h and include/spdlog/pattern_formatter-inl.h, specifically within the handle_flag_ switch statement that maps characters to their respective formatter classes.

Date and Time Format Flags

spdlog supports extensive date-time formatting compatible with strftime-style patterns:

  • %Y — Four-digit year (e.g., 2023)
  • %C — Two-digit year (e.g., 23)
  • %m — Month number 01-12
  • %d — Day of month 01-31
  • %b / %h — Abbreviated month name (e.g., Sep)
  • %B — Full month name (e.g., September)
  • %a — Abbreviated weekday name (e.g., Tue)
  • %A — Full weekday name (e.g., Tuesday)

Time components include:

  • %H — Hour (24-hour clock) 00-23
  • %I — Hour (12-hour clock) 01-12
  • %M — Minute 00-59
  • %S — Second 00-59
  • %p — AM/PM designation
  • %r — 12-hour clock time with AM/PM (e.g., 01:42:01 pm)
  • %R — 24-hour clock time without seconds (HH:MM)
  • %T / %X — ISO-8601 time format (HH:MM:SS)
  • %c — Standard date-time string (e.g., Thu Aug 23 15:35:46 2014)
  • %D / %x — Date in MM/DD/YY format

Sub-second Precision

For high-resolution timestamps:

  • %e — Milliseconds (3 digits)
  • %f — Microseconds (6 digits)
  • %F — Nanoseconds (9 digits)
  • %E — Seconds since epoch

Log Metadata and Context Flags

Track execution context with these identifiers:

  • %n — Logger name
  • %l — Log level name (info, error, debug, etc.)
  • %L — Short log level (single letter: I, E, D, etc.)
  • %t — Thread ID
  • %P — Process ID
  • %v — The actual log message text

Source Location Flags

When logging with source location support (compile-time enabled):

  • %@ — Full source location (filename:line)
  • %s — Short source filename (basename only)
  • %g — Full source filename with path
  • %# — Source line number
  • %! — Source function name

Color and Special Formatting Flags

Control terminal output appearance:

  • %^ — Begin color range (requires color sink)
  • %$ — End color range
  • % — Literal percent character

Elapsed Time Flags

Measure intervals between log messages:

  • %u — Elapsed time since previous log (nanoseconds)
  • %i — Elapsed time since previous log (microseconds)
  • %o — Elapsed time since previous log (milliseconds)
  • %O — Elapsed time since previous log (seconds)

Utility and Timezone Flags

  • %z — UTC offset (e.g., +02:00); respects SPDLOG_NO_TZ_OFFSET compile flag
  • %+ — Full default formatter equivalent to [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] [%s:%#] %v
  • %& — Mapped Diagnostic Context (MDC); requires TLS support (SPDLOG_NO_TLS not defined)

How to Configure Format Patterns

Set custom patterns using set_pattern() on any logger instance. The pattern formatter in include/spdlog/pattern_formatter.h processes these strings at runtime.

#include <spdlog/spdlog.h>

int main()
{
    auto logger = spdlog::stdout_color_mt("example");
    
    // Default full format
    logger->set_pattern("%+");
    logger->info("Using default format");
    
    // Custom timestamp with thread ID
    logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [thread %t] %v");
    logger->info("Processing item");
    
    // Include source location and function name
    logger->set_pattern("[%l] %s:%# (%!) - %v");

    logger->info("Debug message with location");
    
    // Colored log levels
    logger->set_pattern("%^[%l]%$ %v");
    logger->error("This appears in red");
}

Pattern Modifiers

Apply width and alignment modifiers using standard printf-style syntax:

  • %5l — Right-align level to 5 characters
  • %-5! — Left-align function name to 5 characters
  • %.10v — Truncate message to 10 characters

Custom Format Flags

The pattern_formatter class allows runtime registration of custom flags through the add_flag<char, MyFormatter>() template method. Custom flags follow the same %<char> syntax but require explicit registration before use:

#include <spdlog/pattern_formatter.h>

// Define custom formatter class inheriting from flag_formatter
class CustomFlag : public spdlog::custom_flag_formatter {
    void format(const spdlog::details::log_msg& msg, const std::tm&, spdlog::memory_buf_t& dest) override {
        dest.append("CUSTOM");
    }
};

// Register with the formatter
auto formatter = std::make_unique<spdlog::pattern_formatter>();
formatter->add_flag<CustomFlag>('x');
logger->set_formatter(std::move(formatter));
// Now %x produces "CUSTOM" in log output

Summary

  • spdlog supports 40+ built-in format flags defined in include/spdlog/pattern_formatter-inl.h via the handle_flag_ dispatcher.
  • Date-time flags (%Y, %m, %d, %H, %M, %S) support standard strftime formatting with millisecond/microsecond/nanosecond extensions (%e, %f, %F).
  • Context flags include thread ID (%t), process ID (%P), logger name (%n), and log level (%l or %L).
  • Source location requires compiler support but provides filename (%s), line number (%#), and function name (%!) when enabled.
  • Color ranges (%^ and %$) work with color sinks to apply terminal colors to specific log segments.
  • Custom flags can extend functionality through the add_flag API without modifying core library code.

Frequently Asked Questions

How do I display milliseconds in spdlog timestamps?

Use the %e flag in your pattern string: logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e] %v");. This outputs milliseconds as three digits (e.g., .123). For microseconds use %f and for nanoseconds use %F.

Why are my source location flags showing question marks or empty values?

Source location flags (%@, %s, %#, %!) require that SPDLOG_ACTIVE_LEVEL is set to a level that enables the macro and that you're using the SPDLOG_LOGGER_* macros or SPDLOG_SOURCE_LOC compile-time support. By default, release builds may disable source location tracking for performance.

Can I use spdlog format flags without including the entire library?

Yes, the pattern formatting system is modular. Include spdlog/pattern_formatter.h directly if you only need formatting capabilities without sinks. The handle_flag_ implementation in pattern_formatter-inl.h contains the complete flag dispatch table that processes individual format specifiers.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →