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
init()create()Initialize formatter
deinit()destroy()Deinitialize 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.

setTheme(theme: Theme) void ​

Sets a custom color theme for the formatter.

getStats() FormatterStats ​

Returns formatter statistics.

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
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

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);

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

Methods ​

avgFormatSize() f64 ​

Calculate average format size in bytes.

errorRate() f64 ​

Calculate error rate (0.0 - 1.0).

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.