Skip to content

Color Control Example

This example demonstrates comprehensive control over ANSI color output at global and per-sink levels, including Windows support and custom colors.

Enable Colors on Windows

zig
const std = @import("std");
const logly = @import("logly");

pub fn main() !void {
    // IMPORTANT: Call this first on Windows for color support
    // This enables Virtual Terminal Processing
    // No-op on Linux/macOS
    _ = logly.Terminal.enableAnsiColors();

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    const logger = try logly.Logger.init(allocator);
    defer logger.deinit();

    // Colors now work on Windows!
    try logger.info("Colored output on all platforms");
    try logger.success("Green success message");
    try logger.warning("Yellow warning message");
    try logger.err("Red error message");
}

Global Color Control

zig
const logger = try logly.Logger.init(allocator);
defer logger.deinit();

var config = logly.Config.default();

// Master switch - disables colors everywhere
config.global_color_display = false;
logger.configure(config);

// All output will be plain text (no ANSI codes)
try logger.info("No colors here");
try logger.warning("Still no colors");

// Re-enable colors
config.global_color_display = true;
config.color = true;
logger.configure(config);

try logger.success("Colors are back!");

Per-Sink Color Control

zig
const logger = try logly.Logger.init(allocator);
defer logger.deinit();

var config = logly.Config.default();
config.auto_sink = false;  // Don't create default console sink
logger.configure(config);

// Console sink WITH colors (entire line colored)
_ = try logger.addSink(.{
    .name = "console",
    .color = true,
});

// File sink WITHOUT colors (no ANSI codes in file)
_ = try logger.addSink(.{
    .path = "logs/app.log",
    .color = false,
});

// JSON file sink (colors never apply to JSON)
_ = try logger.addSink(.{
    .path = "logs/app.json",
    .json = true,
    .color = false,
});

// Console shows colored output, files are plain text
try logger.info("Console: colored, File: plain text");
try logger.err("Error appears red on console only");

Sink-Specific Level Filtering

zig
// Console: all levels
_ = try logger.addSink(.{
    .color = true,
});

// Error file: only errors and above
_ = try logger.addSink(.{
    .path = "logs/errors.log",
    .level = .err,
    .color = false,
});

// Debug file: only debug and trace
_ = try logger.addSink(.{
    .path = "logs/debug.log",
    .level = .trace,
    .max_level = .debug,
    .color = false,
});

Custom Level Colors

zig
// Enable colors first
_ = logly.Terminal.enableAnsiColors();

const logger = try logly.Logger.init(allocator);
defer logger.deinit();

// Define custom levels with specific colors
// Format: (name, priority, color_code)
try logger.addCustomLevel("AUDIT", 35, "35");        // Magenta
try logger.addCustomLevel("NOTICE", 22, "36;1");    // Bold Cyan
try logger.addCustomLevel("ALERT", 48, "91;1");     // Bold Bright Red
try logger.addCustomLevel("SECURITY", 55, "31;4");  // Underline Red
try logger.addCustomLevel("HIGHLIGHT", 28, "33;7"); // Reverse Yellow

// Use custom levels - entire line gets the custom color
try logger.custom("AUDIT", "Security audit event");
try logger.custom("NOTICE", "Important notice");
try logger.custom("ALERT", "System alert!");
try logger.custom("SECURITY", "Unauthorized access attempt");
try logger.customf("HIGHLIGHT", "User {s} action", .{"admin"});

Color Code Reference

Basic Colors

ColorCodeDescription
Black30Dark text
Red31Errors
Green32Success
Yellow33Warnings
Blue34Debug
Magenta35Custom/Audit
Cyan36Trace
White37Info

Bright Colors

ColorCodeDescription
Bright Red91Critical
Bright Green92Highlight success
Bright Yellow93Important warning
Bright Blue94Highlight debug
Bright Magenta95Special
Bright Cyan96Highlight trace
Bright White97Emphasis

Modifiers

Combine with semicolons:

ModifierCodeExampleResult
Bold131;1Bold Red
Underline434;4Underline Blue
Reverse732;7Reverse Green

Built-in Level Colors

LevelColorCode
TRACECyan36
DEBUGBlue34
INFOWhite37
SUCCESSGreen32
WARNINGYellow33
ERRORRed31
FAILMagenta35
CRITICALBright Red91

JSON with Custom Levels

Custom level names appear in JSON output:

zig
var config = logly.Config.default();
config.json = true;
config.pretty_json = true;
logger.configure(config);

try logger.addCustomLevel("AUDIT", 35, "35");
try logger.custom("AUDIT", "Login event");

Output:

json
{
  "timestamp": "2024-01-15 10:30:45.000",
  "level": "AUDIT",
  "message": "Login event"
}

Complete Example

zig
const std = @import("std");
const logly = @import("logly");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // Enable Windows color support
    _ = logly.Terminal.enableAnsiColors();

    const logger = try logly.Logger.init(allocator);
    defer logger.deinit();

    // Add custom levels
    try logger.addCustomLevel("AUDIT", 35, "35;1");
    try logger.addCustomLevel("SECURITY", 55, "91;4");

    // Standard levels (whole line colored)
    try logger.trace("Cyan trace line");
    try logger.debug("Blue debug line");
    try logger.info("White info line");
    try logger.success("Green success line");
    try logger.warning("Yellow warning line");
    try logger.err("Red error line");
    try logger.critical("Bright red critical line");

    // Custom levels
    try logger.custom("AUDIT", "Bold magenta audit line");
    try logger.custom("SECURITY", "Underline bright red security line");

    // Disable colors for comparison
    var config = logly.Config.default();
    config.global_color_display = false;
    logger.configure(config);

    try logger.info("Plain text - no colors");

    std.debug.print("\nColor control example completed!\n", .{});
}
zig
const is_tty = std.io.getStdOut().isTty();
const force_no_color = std.process.getEnvVarOwned(allocator, "NO_COLOR") catch null;

var config = logly.Config.default();
config.color = is_tty and force_no_color == null;

Color Levels

LevelDefault Color
traceGray
debugBlue
infoGreen
successBright Green
warningYellow
errorRed
failBright Red
criticalRed on White

Custom Colors

See the Custom Colors example for changing level colors.

Best Practices

  1. Auto-detect for terminals - Use null for automatic TTY detection
  2. Disable for files - Unless using ANSI-capable viewers
  3. Never color JSON - Breaks parsing
  4. Respect NO_COLOR - Honor the NO_COLOR environment variable
  5. Test both modes - Ensure logs are readable with and without colors

Released under the MIT License.