Skip to content

Formatter API ​

The Formatter struct handles the conversion of log records into string output. It supports custom formats, JSON output, and color themes.

Quick Reference: Method Aliases ​

Full MethodAlias(es)Description
getTotalFormatted()totalFormatted(), count()Get total formatted records
getJsonFormats()jsonCount(), jsonFormats()Get JSON format count
getCustomFormats()customCount(), customFormats()Get custom format count
getFormatErrors()errors(), errorCount()Get format error count
getTotalBytesFormatted()bytes(), totalBytes()Get total bytes formatted
getPlainFormats()plainCount(), plainFormats()Get plain format count
hasFormatted()hasRecords(), isActive()Check if records have been formatted
hasJsonFormats()hasJson(), usesJson()Check if JSON formats used
hasCustomFormats()hasCustom(), usesCustom()Check if custom formats used
hasErrors()hasFailed(), hasFailures()Check if there are errors
jsonUsageRate()jsonRate(), jsonUsage()Get JSON usage rate
customUsageRate()customRate(), customUsage()Get custom usage rate
avgFormatSize()avgSize(), averageSize()Get average format size
errorRate()failureRate()Get error rate
successRate()success()Get success rate
throughputBytesPerSecond()throughput(), bytesPerSecond()Get throughput
reset()clear(), zero()Reset statistics
getColor()colorFor(), getLevelColor()Get color for level
bright()brightTheme(), vivid()Create bright theme
dim()dimTheme(), subtle()Create dim theme
minimal()minimalTheme(), basic()Create minimal theme
neon()neonTheme(), vibrant()Create neon theme
pastel()pastelTheme(), soft()Create pastel theme
dark()darkTheme(), night()Create dark theme
light()lightTheme(), day()Create light theme
fromRgb()custom(), rgb()Create custom theme
init()create()Initialize formatter
deinit()destroy()Deinitialize formatter
format()render(), output()Format record to string
formatToWriter()renderToWriter(), writeFormatted()Format record to writer
formatJson()json(), toJson()Format record to JSON
formatJsonToWriter()jsonToWriter(), writeJson()Format record to JSON writer
formatTimestamp()timestamp(), formatTime()Format timestamp only
formatTimestampWithAllocator()timestampWithAllocator(), formatTimeWithAllocator()Format timestamp with custom allocator
getStats()statistics()Get formatter statistics
setFormatCompleteCallback()onFormatComplete(), setOnFormatComplete()Set format complete callback
setJsonFormatCallback()onJsonFormat(), setOnJsonFormat()Set JSON format callback
setCustomFormatCallback()onCustomFormat(), setOnCustomFormat()Set custom format callback
setErrorCallback()onError(), setOnError()Set error callback
formatWithAllocator()renderWithAllocator(), outputWithAllocator()Format with custom allocator
formatJsonWithAllocator()jsonWithAllocator(), toJsonWithAllocator()Format JSON with custom allocator
hasTheme()hasColorTheme(), isThemed()Check if theme is set
resetStats()clearStats(), resetStatistics()Reset statistics
plain()noColor(), monochrome(), colorless()Create plain formatter
dark()darkMode(), nightMode()Create dark formatter
light()lightMode(), dayMode()Create light formatter

Formatter ​

The Formatter is typically managed internally by sinks, but can be customized via callbacks and themes.

Methods ​

init(allocator: std.mem.Allocator) Formatter ​

Initializes a new Formatter and pre-fetches system metadata (hostname, PID).

format(record: *const Record, config: anytype) ![]u8 ​

Formats a log record into a string. The config can be Config or SinkConfig. Uses the internal allocator for string building.

formatWithAllocator(record: *const Record, config: anytype, scratch_allocator: ?std.mem.Allocator) ![]u8 ​

Formats a log record using an optional scratch allocator. If provided, temporary allocations use this allocator. If null, falls back to the internal allocator.

Example:

zig
const formatted = try formatter.formatWithAllocator(record, config, logger.scratchAllocator());

formatJson(record: *const Record, config: anytype) ![]u8 ​

Formats a log record into a JSON string. Automatically includes cached hostname and PID if enabled in config. Uses the internal allocator.

formatJsonWithAllocator(record: *const Record, config: anytype, scratch_allocator: ?std.mem.Allocator) ![]u8 ​

Formats a log record as JSON using an optional scratch allocator.

Example:

zig
const json = try formatter.formatJsonWithAllocator(record, config, logger.scratchAllocator());

formatJsonToWriter(writer: anytype, record: *const Record, config: anytype) !void ​

Writes a log record as JSON directly to a writer without intermediate allocation.

formatTimestamp(timestamp_ms: i64, config: anytype) ![]u8 ​

Formats a standalone timestamp string using the same logic as record formatting.

  • Honors Config.time_format and timezone behavior.
  • Useful when callers need consistent timestamp serialization outside full record formatting.

formatTimestampWithAllocator(timestamp_ms: i64, config: anytype, scratch_allocator: ?std.mem.Allocator) ![]u8 ​

Allocator-aware variant of formatTimestamp(...).

  • Uses scratch_allocator when provided.
  • Falls back to formatter allocator when null.

Timestamp Timezone Behavior ​

Timestamp formatting behavior depends on Config.timezone:

  • .utc: ISO8601 emits Z, and RFC3339 emits +00:00.
  • .local: uses process/system local timezone when available and emits +/-HH:MM for ISO8601 and RFC3339.

For custom time_format patterns, timezone tokens are also available:

  • ZZZ => +HH:MM
  • ZZ => +HHMM

time_format = "default" resolves to the canonical default pattern (YYYY-MM-DD HH:mm:ss.SSS).

unix and unix_ms formats remain numeric and timezone-agnostic, including JSON output.

Why ZZZ and ZZ are needed:

  • Custom date/time layouts are often required by legacy parsers and SIEM pipelines.
  • Including explicit offsets prevents ambiguous timestamps when logs are aggregated across timezones.

setTheme(theme: Theme) void ​

Sets a custom color theme for the formatter.

getStats() FormatterStats ​

Returns formatter statistics.

FormatterStats ​

Statistics for formatter performance.

Getter Methods ​

MethodReturnDescription
getTotalFormatted()u64Get total records formatted
getJsonFormats()u64Get total JSON formats
getCustomFormats()u64Get total custom formats
getFormatErrors()u64Get total format errors
getTotalBytesFormatted()u64Get total bytes formatted
getPlainFormats()u64Get plain text formats (total - json - custom)

Boolean Checks ​

MethodReturnDescription
hasFormatted()boolCheck if any records have been formatted
hasJsonFormats()boolCheck if any JSON formats have been used
hasCustomFormats()boolCheck if any custom formats have been used
hasErrors()boolCheck if any format errors have occurred

Rate Calculations ​

MethodReturnDescription
jsonUsageRate()f64Calculate JSON format usage rate (0.0 - 1.0)
customUsageRate()f64Calculate custom format usage rate (0.0 - 1.0)
avgFormatSize()f64Calculate average format size
errorRate()f64Calculate error rate (0.0 - 1.0)
successRate()f64Calculate success rate (0.0 - 1.0)
throughputBytesPerSecond(elapsed_seconds)f64Calculate throughput (bytes per second)

Precise Byte Tracking

As of v0.1.5, total_bytes_formatted captures the exact length of each formatted message, replacing previous estimations.

Reset ​

MethodDescription
reset()Reset all statistics to initial state

System Metadata ​

The Formatter caches system metadata during initialization to improve performance:

  • Hostname: Retrieved via GetComputerNameW (Windows) or gethostname (POSIX).
  • PID: Retrieved via GetCurrentProcessId (Windows) or getpid (POSIX).

These values are automatically included in JSON output when include_hostname or include_pid are enabled in the configuration.

Callbacks ​

setFormatCompleteCallback(callback: *const fn (u32, u64) void) void ​

Sets the callback for format completion.

  • Parameters: format_type (u32), output_size (u64)

setJsonFormatCallback(callback: *const fn (*const Record, u64) void) void ​

Sets the callback for JSON formatting.

  • Parameters: record (*const Record), output_size (u64)

setCustomFormatCallback(callback: *const fn ([]const u8, u64) void) void ​

Sets the callback for custom formatting.

  • Parameters: format_string ([]const u8), output_size (u64)

setErrorCallback(callback: *const fn ([]const u8) void) void ​

Sets the callback for format errors.

  • Parameters: error_msg ([]const u8)

Theme ​

The Theme struct defines custom ANSI color codes for each log level.

Fields ​

FieldTypeDefaultDescription
trace[]const u8"36" (Cyan)Color for TRACE level
debug[]const u8"34" (Blue)Color for DEBUG level
info[]const u8"37" (White)Color for INFO level
notice[]const u8"96" (Bright Cyan)Color for NOTICE level (v0.1.5)
success[]const u8"32" (Green)Color for SUCCESS level
warning[]const u8"33" (Yellow)Color for WARNING level
err[]const u8"31" (Red)Color for ERROR level
fail[]const u8"35" (Magenta)Color for FAIL level
critical[]const u8"91" (Bright Red)Color for CRITICAL level
fatal[]const u8"91;1" (Bright Red Bold)Color for FATAL level (v0.1.5)

Basic Usage ​

zig
var theme = logly.Formatter.Theme{};
theme.info = "32"; // Change INFO to Green
theme.err = "1;31"; // Change ERROR to Bold Red

// Apply to a sink
logger.sinks.items[0].formatter.setTheme(theme);

Theme Presets (v0.1.5) ​

zig
const Theme = logly.Formatter.Theme;

// Built-in theme presets
const default_theme = Theme{};              // Standard colors
const bright = Theme.bright();              // Bold/bright colors
const dim = Theme.dim();                    // Dim colors
const underlined = Theme.underlined();      // Underlined colors (v0.1.5)
const minimal = Theme.minimal();            // Subtle grays
const neon = Theme.neon();                  // Vivid 256-colors
const pastel = Theme.pastel();              // Soft colors
const dark = Theme.dark();                  // Dark terminal optimized
const light = Theme.light();                // Light terminal optimized

// Apply preset to formatter
var formatter = logly.Formatter.init(allocator);
formatter.setTheme(Theme.neon());

Theme Preset Details ​

PresetTraceDebugInfoSuccessWarningErrorCritical
default36343732333191
bright()96;194;197;192;193;191;191;1;4
dim()36;234;237;232;233;231;291;2
underlined()36;434;437;432;433;431;491;4
minimal()90903732333191
neon()38;5;5138;5;3338;5;25238;5;4638;5;22638;5;19638;5;196;1
pastel()38;5;15238;5;11138;5;25338;5;15738;5;22838;5;21038;5;203
dark()38;5;3738;5;3338;5;24538;5;3438;5;21438;5;16038;5;196
light()38;5;3038;5;2738;5;23838;5;2838;5;17238;5;12438;5;160

Custom RGB Theme (v0.1.5) ​

zig
// Create a theme from RGB values
const custom = Theme.fromRgb(
    .{ 0, 255, 255 },    // trace (cyan)
    .{ 0, 128, 255 },    // debug (blue)
    .{ 240, 240, 240 },  // info (white)
    .{ 0, 255, 128 },    // success (green)
    .{ 255, 200, 0 },    // warning (orange)
    .{ 255, 64, 64 },    // error (red)
    .{ 255, 0, 0 },      // critical (bright red)
);

ColorStyle (v0.1.5) ​

The ColorStyle enum controls which color variant to use:

zig
pub const ColorStyle = enum {
    default,     // Standard ANSI colors (30-37, 90-97)
    bright,      // Bold/bright variants
    dim,         // Dim variants
    color256,    // 256-color palette
    minimal,     // Minimal styling
    neon,        // Vivid neon colors
    pastel,      // Soft pastel colors
    dark,        // Optimized for dark terminals
    light,       // Optimized for light terminals
};

FormatterStats ​

Statistics for the formatter.

FieldTypeDescription
total_records_formattedatomic.Value(u64)Total records formatted
json_formatsatomic.Value(u64)Number of JSON formats
custom_formatsatomic.Value(u64)Number of custom formats
format_errorsatomic.Value(u64)Number of format errors
total_bytes_formattedatomic.Value(u64)Total bytes formatted

Getter Methods ​

MethodReturnDescription
getTotalFormatted()u64Get total records formatted
getJsonFormats()u64Get total JSON formats
getCustomFormats()u64Get total custom formats
getFormatErrors()u64Get total format errors
getTotalBytesFormatted()u64Get total bytes formatted
getPlainFormats()u64Get plain text formats (total - json - custom)

Boolean Checks ​

MethodReturnDescription
hasFormatted()boolCheck if any records have been formatted
hasJsonFormats()boolCheck if any JSON formats have been used
hasCustomFormats()boolCheck if any custom formats have been used
hasErrors()boolCheck if any format errors have occurred

Rate Calculations ​

MethodReturnDescription
jsonUsageRate()f64Calculate JSON format usage rate (0.0 - 1.0)
customUsageRate()f64Calculate custom format usage rate (0.0 - 1.0)
avgFormatSize()f64Calculate average format size in bytes
errorRate()f64Calculate error rate (0.0 - 1.0)
successRate()f64Calculate success rate (0.0 - 1.0)
throughputBytesPerSecond(elapsed_seconds)f64Calculate bytes per second throughput

Reset ​

MethodDescription
reset()Reset all statistics to initial state

Aliases ​

The Formatter module provides convenience aliases:

AliasMethod
renderformat
outputformat
renderToWriterformatToWriter
writeFormattedformatToWriter
jsonformatJson
toJsonformatJson
jsonToWriterformatJsonToWriter
writeJsonformatJsonToWriter
statisticsgetStats
colorssetTheme

Additional Methods ​

  • hasTheme() bool - Returns true if a custom theme is set
  • resetStats() void - Resets all formatter statistics

FormatterPresets ​

Pre-configured formatter options:

zig
pub const FormatterPresets = struct {
    /// Plain formatter (no colors).
    pub fn plain() FormatterConfig {
        return .{ .color = false };
    }
    
    /// Dark theme formatter.
    pub fn dark() FormatterConfig {
        return .{
            .color = true,
            .theme = .dark,
        };
    }
    
    /// Light theme formatter.
    pub fn light() FormatterConfig {
        return .{
            .color = true,
            .theme = .light,
        };
    }
};

See Also ​

Released under the MIT License.