### Quick Start with Logly.zig Project Starter Template Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/README.md This section provides instructions to quickly start a new project using Logly.zig. It involves downloading a pre-configured starter template, which includes a setup `build.zig` and `build.zig.zon`, example code, and sink configurations. The process includes downloading, extracting, and building the example project. ```bash # Download and extract the starter template curl -L https://github.com/muhammad-fiaz/logly.zig/releases/latest/download/project-starter-example.zip -o logly-starter.zip unzip logly-starter.zip cd project-starter-example # Build and run zig build run ``` -------------------------------- ### Production Setup Example for Logly Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/thread-pool.md A comprehensive example demonstrating a production-ready setup for Logly. This includes initializing a thread pool with work stealing and priorities, configuring a parallel sink writer with retry mechanisms, starting the pool, and checking final statistics. It uses `GeneralPurposeAllocator` for memory management. ```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(); // Production thread pool config const cpu_count = std.Thread.getCpuCount() catch 4; var pool = try logly.ThreadPool.init(allocator, .{ .thread_count = cpu_count, .queue_size = 2048, .work_stealing = true, .enable_priorities = true, .shutdown_timeout_ms = 10000, }); defer pool.deinit(); // Parallel sink writer var writer = try logly.ParallelSinkWriter.init(allocator, .{ .max_concurrent = 4, .retry_on_failure = true, .max_retries = 3, }); defer writer.deinit(); try pool.start(); defer pool.stop(); // Application runs... // Check final stats const stats = pool.getStats(); std.debug.print("Total processed: {d}\n", .{ stats.tasks_completed.load(.monotonic), }); } ``` -------------------------------- ### Install Logly.zig using Zig Fetch Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/getting-started.md This method uses the `zig fetch` command to download and save the Logly.zig package. It automatically handles downloading, hash calculation, and updating your `build.zig.zon` file, making it the recommended installation approach. ```bash zig fetch --save https://github.com/muhammad-fiaz/logly.zig/archive/refs/tags/v0.0.4.tar.gz ``` -------------------------------- ### Basic Logly.zig Usage Example Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/getting-started.md This Zig code demonstrates a basic integration of Logly.zig. It initializes the logger, enables ANSI colors for Windows, and logs messages at different severity levels (info, success, warning). ```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 ANSI colors on Windows (no-op on Linux/macOS) _ = logly.Terminal.enableAnsiColors(); const logger = try logly.Logger.init(allocator); defer logger.deinit(); // Entire log lines are colored by level! try logger.info("Logly-Zig is working!"); // White line try logger.success("Installation complete!"); // Green line try logger.warning("Ready for production!"); // Yellow line } ``` -------------------------------- ### Fetch Hash for Manual Installation Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/getting-started.md This command is used to manually retrieve the hash for a given URL, which is required when adding Logly.zig as a dependency in your `build.zig.zon` file. ```bash zig fetch https://github.com/muhammad-fiaz/logly.zig/archive/refs/tags/v0.0.4.tar.gz ``` -------------------------------- ### Production Logging Setup with Compression in Zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/compression.md A complete example of setting up a production logger with Logly.zig, including initialization, configuration with compression, direct compression/decompression usage, and verification of the compression ratio. This demonstrates a practical application of the library's features. ```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(); // Production config with compression enabled var config = logly.Config.production(); // Includes compression // Or customize compression settings var custom_config = logly.Config.default().withCompression(.{ .algorithm = .lz77_rle, .level = 6, .window_size = 32768, .enable_checksums = true, }); var logger = try logly.Logger.initWithConfig(allocator, config); defer logger.deinit(); // Direct compression usage var compression = logly.Compression.init(allocator, .{}); defer compression.deinit(); const data = "Application log data..." ** 100; const compressed = try compression.compress(data); defer allocator.free(compressed); // Verify integrity const decompressed = try compression.decompress(compressed); defer allocator.free(decompressed); const ratio = @as(f64, @floatFromInt(compressed.len)) / @as(f64, @floatFromInt(data.len)) * 100; std.debug.print("Compression ratio: {d:.1}%\n", .{ratio}); std.debug.print("Data verified: {}\n", .{std.mem.eql(u8, data, decompressed)}); } ``` -------------------------------- ### Build and Run Zig Project Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/getting-started.md These commands are used to compile your Zig project and then execute the built application. `zig build` compiles the project, and `zig build run` executes the application. ```bash # Build the project zig build # Run the application zig build run ``` -------------------------------- ### Initialize and Start Logly Scheduler in Zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/scheduler.md Demonstrates the quick start process for Logly's scheduler. This involves initializing the scheduler, adding a cleanup task with a daily schedule, and then starting the scheduler. It includes necessary imports and memory management. ```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(); // Create scheduler var scheduler = try logly.Scheduler.init(allocator); defer scheduler.deinit(); // Add a cleanup task _ = try scheduler.addTask(.{ .name = "daily_cleanup", .task_type = .cleanup, .schedule = .{ .daily = .{ .hour = 2, .minute = 0 } }, .config = .{ .path = "logs", .max_age_seconds = 30 * 24 * 60 * 60, // 30 days }, }); // Start scheduler try scheduler.start(); defer scheduler.stop(); } ``` -------------------------------- ### Production Setup for Logly Scheduler in Zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/scheduler.md This code illustrates a comprehensive production setup for the Logly scheduler in Zig. It initializes the scheduler with specific configurations for intervals, timezones, and concurrency, and adds various scheduled tasks for daily cleanup, hourly compression, and weekly deep cleaning. It also shows how to start and gracefully stop the scheduler. ```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(); // Production scheduler config var scheduler = try logly.Scheduler.init(allocator, .{ .check_interval_ms = 60000, .timezone_offset = -5, // EST .max_concurrent_tasks = 2, .retry_failed = true, .max_retries = 3, }); defer scheduler.deinit(); // Daily cleanup at 2 AM - remove logs older than 30 days _ = try scheduler.addTask(.{ .name = "daily_cleanup", .task_type = .cleanup, .schedule = logly.Schedule.daily(2, 0), .config = .{ .cleanup = .{ .path = "logs", .max_age_days = 30, .min_files_to_keep = 10, }}, }); // Hourly compression - compress logs older than 1 day _ = try scheduler.addTask(.{ .name = "hourly_compression", .task_type = .compression, .schedule = logly.Schedule.everyHours(1), .config = .{ .compression = .{ .path = "logs", .min_age_days = 1, }}, }); // Weekly deep clean on Sunday _ = try scheduler.addTask(.{ .name = "weekly_deep_clean", .task_type = .cleanup, .schedule = logly.Schedule.weekly(0, 3, 0), .config = .{ .cleanup = .{ .path = "logs", .max_age_days = 7, .include_compressed = true, }}, }); // Start scheduler try scheduler.start(); // ... application runs ... // Graceful shutdown scheduler.stop(); } ``` -------------------------------- ### Run Example Formatted Logging in Logly Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/CONTRIBUTING.md Builds and runs the formatted logging example for the Logly project using the Zig build system. This command verifies that the examples function correctly after making changes. Ensure Zig version 0.15.x or later is installed. ```bash zig build example-formatted_logging ``` -------------------------------- ### Initialize and Start Logly Thread Pool Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/thread-pool.md Demonstrates the basic setup for a Logly thread pool. It involves initializing the thread pool with an allocator and configuration, starting the worker threads, and ensuring proper deinitialization upon completion. Tasks can then be submitted to this pool. ```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(); // Create thread pool with default settings var pool = try logly.ThreadPool.init(allocator, .{ .thread_count = 4, .work_stealing = true, }); defer pool.deinit(); // Start workers try pool.start(); defer pool.stop(); // Submit tasks // pool.submit(...); } ``` -------------------------------- ### Logly.zig Usage Example in Zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/api/scheduler.md Example demonstrating how to initialize Logly.zig, add tasks (daily cleanup and hourly compression), start the scheduler, and check its statistics. It uses `std.heap.GeneralPurposeAllocator` for memory management. ```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(); // Create scheduler var scheduler = try logly.Scheduler.init(allocator, .{ .check_interval_ms = 60000, .auto_start = false, }); defer scheduler.deinit(); // Add daily cleanup task _ = try scheduler.addTask(.{ .name = "log_cleanup", .task_type = .cleanup, .schedule = logly.Schedule.daily(2, 30), .config =Анатолий.{ .cleanup = { .path = "logs", .max_age_days = 30, .pattern = "*.log", }}, }); // Add hourly compression _ = try scheduler.addTask(.{ .name = "log_compression", .task_type = .compression, .schedule = logly.Schedule.everyHours(1), .config =Анатолий.{ .compression = { .path = "logs", .min_age_days = 1, }}, }); // Start scheduler try scheduler.start(); defer scheduler.stop(); // Check stats periodically const stats = scheduler.getStats(); std.debug.print("Tasks executed: {d} ", .{ stats.tasks_executed.load(.monotonic), }); } ``` -------------------------------- ### Integrate Prebuilt Logly.zig Library in build.zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/getting-started.md This code demonstrates how to link a prebuilt Logly.zig static library into your project. It involves adding the library's path and linking it as a system library within your `build.zig` file. ```zig // Assuming you downloaded the library to `libs/` exe.addLibraryPath(b.path("libs")); exe.linkSystemLibrary("logly"); ``` -------------------------------- ### Logly.zig Usage Example Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/api/async.md A complete Zig example demonstrating how to initialize and use the Logly.zig asynchronous logger. It covers creating the logger with a specific preset, starting the background worker, logging messages, and retrieving statistics. ```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(); // Create async logger with high throughput config var async_logger = try logly.AsyncLogger.init( allocator, logly.AsyncPresets.highThroughput(), ); defer async_logger.deinit(); // Start the background worker try async_logger.start(); defer async_logger.stop(); // Log messages (non-blocking) for (0..1000) |i| { _ = i; // async_logger.log(&record); } // Check statistics const stats = async_logger.getStats(); std.debug.print("Queued: {d}, Written: {d}, Dropped: {d}\\n", .{ stats.records_queued.load(.monotonic), stats.records_written.load(.monotonic), stats.records_dropped.load(.monotonic), }); std.debug.print("Drop rate: {d:.2}%\\n", .{stats.dropRate() * 100}); } ``` -------------------------------- ### Configure build.zig for Logly.zig Dependency Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/getting-started.md This is a standard Zig `build.zig` file configuration that includes adding Logly.zig as a dependency and importing its module. It sets up the target, optimization, and creates an executable, along with a run step. ```zig const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "my-app", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); // Add logly dependency const logly_dep = b.dependency("logly", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("logly", logly_dep.module("logly")); b.installArtifact(exe); // Add run step const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); const run_step = b.step("run", "Run the application"); run_step.dependOn(&run_cmd.step); } ``` -------------------------------- ### Import Logly Module in build.zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/getting-started.md Illustrates how to correctly import the Logly module into your Zig project's build configuration, ensuring that the logger library is available for use. ```zig exe.root_module.addImport("logly", logly_dep.module("logly")); ``` -------------------------------- ### Zig Async Logging Example with Logly Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/examples/async-logging.md This code example demonstrates a complete asynchronous logging setup using the logly library in Zig. It initializes a logger, configures it with async settings, adds file and console sinks, logs multiple messages, and ensures logs are flushed before the program exits. It requires the 'logly' and 'std' libraries. Input is standard allocator and log messages. Output includes console messages and a file log. ```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 colors on Windows _ = logly.Terminal.enableAnsiColors(); const logger = try logly.Logger.init(allocator); defer logger.deinit(); // Configure logger with async settings var config = logly.Config.default(); config.auto_sink = false; config.async_config = logly.AsyncConfig{ .buffer_size = 8192, .flush_interval_ms = 100, }; logger.configure(config); // Add a file sink with async writing enabled (default) // Using add() alias (same as addSink()) _ = try logger.add(.{ .path = "logs/async.log", .async_write = true, .buffer_size = 4096, // 4KB buffer }); // Add a console sink _ = try logger.add(.{}); try logger.info("Starting async logging test...", @src()); // Log many messages quickly for (0..1000) |i| { try logger.infof("Async log message #d", .{i}, @src()); } try logger.info("Finished logging 1000 messages", @src()); // Flush is important for async sinks before exit try logger.flush(); std.debug.print("Async logging example completed!\n", .{} ); } ``` -------------------------------- ### Global Logging Controls Configuration (Zig) Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/quick-start.md Configures global settings that control log output behavior. This example enables console display, file storage, and color display globally for the logger. ```zig var config = logly.Config.default(); config.global_console_display = true; // Enable console config.global_file_storage = true; // Enable file storage config.global_color_display = true; // Enable colors logger.configure(config); ``` -------------------------------- ### Helper Methods for Logly Configuration in Zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/configuration.md Demonstrates using helper methods to enable specific configurations like async logging, compression, thread pools, and schedulers with default settings. These methods simplify the initial setup. ```zig // Enable async logging var config = logly.Config.default().withAsync(); // Enable compression var config2 = logly.Config.default().withCompression(); // Enable thread pool with specific thread count var config3 = logly.Config.default().withThreadPool(4); // Enable scheduler var config4 = logly.Config.default().withScheduler(); ``` -------------------------------- ### Basic Console Logging with Log Levels (Zig) Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/quick-start.md Demonstrates basic console logging using Logly.zig, showcasing different log levels (info, success, warning, err) which automatically color the entire log line based on the level. It also shows how to include source location information for clickable file:line output. ```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 ANSI colors on Windows _ = logly.Terminal.enableAnsiColors(); const logger = try logly.Logger.init(allocator); defer logger.deinit(); // Entire line is colored based on level! // Pass @src() for clickable file:line output, or null for no source location try logger.info("Hello, Logly!", @src()); // White line try logger.success("Operation done!", @src()); // Green line try logger.warning("Be careful!", @src()); // Yellow line try logger.err("Something went wrong!", @src()); // Red line } ``` -------------------------------- ### Manually Add Logly.zig Dependency to build.zig.zon Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/getting-started.md This snippet shows how to manually add Logly.zig as a dependency in your `build.zig.zon` file. You need to provide the URL and fetch the corresponding hash using the `zig fetch` command. ```zig .{ .name = "my-project", .version = "0.1.0", .dependencies = .{ .logly = .{ .url = "https://github.com/muhammad-fiaz/logly.zig/archive/refs/tags/v0.0.4.tar.gz", .hash = "1220...", // Run: zig fetch to get this hash }, }, } ``` -------------------------------- ### Initialize and Schedule Log Maintenance Tasks Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/examples/scheduler.md Demonstrates initializing the Logly scheduler and adding tasks for daily log cleanup and hourly compression. It includes scheduling specific times and intervals, configuring task parameters, and starting the scheduler. ```zig //! Scheduler Example //! //! Demonstrates scheduled log maintenance tasks. const std = @import("std"); const logly = @import("logly"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); // Create scheduler with centralized config var scheduler = try logly.Scheduler.init(allocator, .{ .check_interval_ms = 60000, .auto_start = false, }); defer scheduler.deinit(); // Add daily cleanup task _ = try scheduler.addTask(.{ .name = "log_cleanup", .task_type = .cleanup, .schedule = logly.Schedule.daily(2, 30), // 2:30 AM .config = .{ .cleanup = .{ .path = "logs", .max_age_days = 30, .pattern = "*.log" } }, }); // Add hourly compression task _ = try scheduler.addTask(.{ .name = "log_compression", .task_type = .compression, .schedule = logly.Schedule.everyHours(1), .config = .{ .compression = .{ .path = "logs", .min_age_days = 1 } }, }); // Start scheduler try scheduler.start(); defer scheduler.stop(); // List tasks const tasks = scheduler.listTasks(); for (tasks, 0..) |task, i| { std.debug.print("Task {d}: {s} ({s})\n", .{ i, task.name, @tagName(task.task_type), }); } } ``` -------------------------------- ### Zig: Basic Trace Context Setup and Logging Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/examples/tracing.md Sets up a basic trace context and correlation ID, then logs messages that will automatically include this trace information. It also shows how to clear the trace context after use. Requires the 'logly' and 'std' Zig libraries. ```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 colors on Windows _ = logly.Terminal.enableAnsiColors(); const logger = try logly.Logger.init(allocator); defer logger.deinit(); // Set trace context for distributed tracing try logger.setTraceContext("trace-abc123", "span-001"); try logger.setCorrelationId("request-789"); // All logs will now include trace info try logger.info("Processing request", @src()); try logger.debug("Validating input", @src()); try logger.info("Request completed", @src()); // Clear trace context logger.clearTraceContext(); } ``` -------------------------------- ### Add and Use Custom Log Levels with ANSI Colors in Zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/getting-started.md Demonstrates how to define custom log levels with specific ANSI color codes and how to subsequently use these custom levels for logging messages. This allows for enhanced log message differentiation. ```zig try logger.addCustomLevel("NOTICE", 35, "36;1"); try logger.custom("NOTICE", "Custom notice message"); ``` -------------------------------- ### Log All Levels and Formatted Output (Zig) Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/quick-start.md Illustrates logging across all available levels in Logly.zig, including trace, debug, info, success, warning, err, fail, and critical, each with distinct colors and priorities. It also demonstrates formatted logging using `printf`-style methods like `infof`, `debugf`, and `errf`. ```zig // Each level colors the ENTIRE log line (timestamp, level, message) // All logging methods accept an optional source location as the last parameter try logger.trace("Detailed trace", @src()); // Priority 5 - Cyan try logger.debug("Debug info", @src()); // Priority 10 - Blue try logger.info("Information", @src()); // Priority 20 - White try logger.success("Success!", @src()); // Priority 25 - Green try logger.warning("Warning", @src()); // Priority 30 - Yellow try logger.err("Error occurred", @src()); // Priority 40 - Red try logger.fail("Operation failed", @src()); // Priority 45 - Magenta try logger.critical("Critical!", @src()); // Priority 50 - Bright Red // Without source location (no clickable file:line) try logger.info("Simple message", null); try logger.infof("User {s} logged in from {s}", .{"Alice", "127.0.0.1"}, @src()); try logger.debugf("Processing item {d} of {d}", .{5, 10}, @src()); try logger.errf("Connection failed: {s}", .{"Timeout"}, @src()); ``` -------------------------------- ### Quick Start: Compress Data in Zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/compression.md Demonstrates how to initialize the compression module and compress data using default settings. It allocates memory, compresses a string, and prints the original and compressed sizes. This snippet showcases the core functionality of data compression within the Logly library. ```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(); // Create compression with default settings var compression = logly.Compression.init(allocator); defer compression.deinit(); // Compress some data const data = "Hello, World! " ** 100; const compressed = try compression.compress(data); defer allocator.free(compressed); std.debug.print("Original: {d} bytes\n", .{data.len}); std.debug.print("Compressed: {d} bytes\n", .{compressed.len}); } ``` -------------------------------- ### Manual Installation of Logly.zig Dependency Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/README.md This demonstrates how to manually add Logly.zig as a dependency in your Zig project. It involves updating the `build.zig.zon` file with the dependency's URL and hash, and then importing the module into your `build.zig` file. The example shows how to reference the dependency and add it to the root module. ```zig const logly = b.dependency("logly", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("logly", logly.module("logly")); ``` -------------------------------- ### Use Compression Presets in Zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/compression.md Illustrates how to use pre-defined presets for compression to quickly configure compression settings. It uses `logly.CompressionPresets` to select common scenarios, such as fast, balanced (default), and maximum compression. This simplifies compression setup with pre-optimized configurations. ```zig // Fast compression, minimal CPU const fast = logly.CompressionPresets.fast(); // Balanced (default) const balanced = logly.CompressionPresets.balanced(); // Maximum compression const maximum = logly.CompressionPresets.maximum(); ``` -------------------------------- ### Adding Custom Log Levels (Zig) Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/quick-start.md Demonstrates how to define and use custom log levels in Logly.zig. This allows for more granular control over log message severity and categorization by defining new levels with specific names, priorities, and colors. ```zig try logger.addCustomLevel("NOTICE", 35, "96"); try logger.custom("NOTICE", "Custom level message", @src()); ``` -------------------------------- ### Zig: Initialize and Configure Logly Logger Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/quick-start.md This snippet shows how to initialize a Logly logger in Zig, configure its level, color, and source location display, and add console and file-based sinks. It also demonstrates binding contextual data and logging messages with source location information. ```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(); // Create logger const logger = try logly.Logger.init(allocator); defer logger.deinit(); // Configure with source location display var config = logly.Config.default(); config.level = .debug; config.color = true; config.show_filename = true; // Enable clickable file:line config.show_lineno = true; config.enable_callbacks = true; logger.configure(config); // Add sinks _ = try logger.addSink(.{}); // Console _ = try logger.addSink(.{ .path = "logs/app.log", .rotation = "daily", .retention = 7, }); // Bind context try logger.bind("app", .{ .string = "myapp" }); try logger.bind("version", .{ .string = "1.0.0" }); // Log messages with source location (clickable in terminals) try logger.info("Application started", @src()); try logger.success("Initialization complete", @src()); // Simulate work for (0..10) |i| { try logger.debugf("Processing item {d}", .{i}, @src()); } try logger.success("All items processed", @src()); } ``` -------------------------------- ### Logly Sink Examples Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/api/sink.md Code examples demonstrating various sink configurations. ```APIDOC ## Examples ### Console Sink (Default) ```zig // Using add() alias (same as addSink()) _ = try logger.add(SinkConfig.default()); ``` ### File Sink with Rotation ```zig _ = try logger.add(.{ .path = "logs/app.log", .rotation = "daily", .retention = 7, .size_limit_str = "100MB", }); ``` ### JSON Sink for Structured Logging ```zig _ = try logger.add(.{ .path = "logs/app.json", .json = true, .pretty_json = true, .include_trace_id = true, }); ``` ### Error-Only File Sink ```zig _ = try logger.add(.{ .path = "logs/errors.log", .level = .err, // Minimum: error .max_level = .critical, // Maximum: critical .color = false, }); ``` ### Console with Color Control ```zig // Disable colors for console output _ = try logger.add(.{ .color = false, // Override auto-detect }); // Or use global setting var config = Config.default(); config.global_color_display = false; logger.configure(config); ``` ### High-Throughput Async Sink ```zig _ = try logger.add(.{ .path = "logs/high-volume.log", .async_write = true, .buffer_size = 65536, // 64KB buffer }); ``` ### Multiple Sinks with Different Levels ```zig // Console: info and above _ = try logger.addSink(.{ .level = .info, }); // File: all levels _ = try logger.addSink(.{ .path = "logs/debug.log", .level = .trace, }); // Errors file: errors only _ = try logger.addSink(.{ .path = "logs/errors.log", .level = .err, }); ``` ## Color Auto-Detection When `color` is `null` (default), the sink auto-detects: - **Console sinks**: Colors enabled if terminal supports ANSI - **File sinks**: Colors disabled Override with explicit `true` or `false`: ```zig // Force colors off for console _ = try logger.addSink(.{ .color = false }); // Force colors on for file (e.g., for viewing with `less -R`) _ = try logger.addSink(.{ .path = "logs/colored.log", .color = true, }); ``` ``` -------------------------------- ### Complete Logging Example with Custom Levels and Colors in Zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/examples/color-control.md A comprehensive example demonstrating the full capabilities of logly.zig. It initializes the logger, enables terminal color support, adds custom log levels ('AUDIT', 'SECURITY'), logs messages using both standard and custom levels with various colors, and shows how to disable colors globally. ```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", .{}); } ``` -------------------------------- ### Logly Custom Production Configuration with File Sink Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/examples/production-config.md Demonstrates creating a custom production configuration by starting with the production preset and then modifying specific fields like log level, hostname inclusion, PID, thread ID, and time format. It also adds a file sink for daily rotated logs with 30-day retention. ```zig const Config = logly.Config; // Start with production preset and customize var config = Config.production(); config.level = .info; // Allow info logs config.include_hostname = true; // Include server hostname config.include_pid = true; // Include process ID config.show_thread_id = true; // Include thread ID config.time_format = "iso8601"; // ISO timestamps logger.configure(config); // Add file sink _ = try logger.addSink(.{ .path = "logs/production.log", .json = true, .rotation = "daily", .retention = 30, // Keep 30 rotated files }); ``` -------------------------------- ### Manage Logly Scheduler Tasks Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/examples/scheduler.md Provides examples of how to manage scheduled tasks, including disabling, enabling, running immediately, and removing tasks by their index. ```zig // Disable a task scheduler.disableTask(0); // Enable a task scheduler.enableTask(0); // Run immediately try scheduler.runTaskNow(0); // Remove a task try scheduler.removeTask(0); ``` -------------------------------- ### Build and Run Logly.zig Benchmark (Zig) Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/README.md This snippet demonstrates how to build and run the benchmark executable for Logly.zig. It first builds the benchmark using `zig build bench` and then executes it. The notes explain that the benchmark uses a null output device to avoid I/O bottlenecks and that results may vary. ```bash # Build and run the benchmark (default build output in `zig-out`) zig build bench # Or build then run the built executable directly (useful if you pass extra flags to build): zig build -p zig-out ./zig-out/bin/benchmark # POSIX .\zig-out\bin\benchmark.exe # Windows PowerShell ``` -------------------------------- ### Build Logly.zig Examples (Zig) Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/README.md This section lists the build commands for various examples provided by the Logly.zig library. These commands cover basic usage, file logging, rotation, JSON logging, callbacks, context, advanced configuration, module levels, sink formats, and formatted logging, as well as enterprise and advanced features like filtering, sampling, redaction, metrics, tracing, compression, thread pools, schedulers, and async operations. ```bash # Run tests zig build test # Build examples zig build example-basic zig build example-file_logging zig build example-rotation zig build example-json_logging zig build example-callbacks zig build example-context zig build example-advanced_config zig build example-module_levels zig build example-sink_formats zig build example-formatted_logging # Enterprise feature examples zig build example-filtering zig build example-sampling zig build example-redaction zig build example-metrics zig build example-tracing zig build example-color_options zig build example-production_config # Advanced feature examples zig build example-compression zig build example-thread_pool zig build example-scheduler zig build example-async_advanced # Run an example ./zig-out/bin/basic ``` -------------------------------- ### Configure Production Logging Settings Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/README.md Provides examples of how to configure the logger for production environments. It shows how to use predefined production configuration presets and how to customize production settings, such as log level and including hostname information. This ensures appropriate logging behavior in live systems. ```zig // Use preset configurations const config = logly.ConfigPresets.production(); logger.configure(config); // Or customize var config = logly.Config.production(); config.level = .info; config.include_hostname = true; logger.configure(config); ``` -------------------------------- ### Disable Colors Globally and Per Sink in Logly.zig Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/getting-started.md Shows how to disable color output for all logs globally by modifying the logger configuration and how to disable colors specifically for individual log sinks, such as file outputs. ```zig var config = logly.Config.default(); config.global_color_display = false; logger.configure(config); _ = try logger.addSink(.{ .path = "logs/app.log", .color = false, // No colors in file }); ``` -------------------------------- ### Zig Quick Example: Initialize and Log Messages Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/index.md Demonstrates how to initialize the Logly.Zig logger, enable ANSI colors on Windows, and log messages at different levels (info, success, warn, error). It shows the use of @src() for including file and line number information in logs. ```zig const std = @import("std"); const logly = @import("logly"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); // Enable ANSI colors on Windows (no-op on Linux/macOS) _ = logly.Terminal.enableAnsiColors(); const logger = try logly.Logger.init(gpa.allocator()); defer logger.deinit(); // Each level colors the ENTIRE line (timestamp, level, message) // @src() is optional - enables file:line display when show_filename/show_lineno are true try logger.info(@src(), "Application started", .{}); // White line try logger.success(@src(), "Operation completed!", .{}); // Green line try logger.warn(@src(), "Low memory", .{}); // Yellow line (alias for warning) try logger.err(@src(), "Connection failed", .{}); // Red line } ``` -------------------------------- ### File Rotation and Retention Configuration (Zig) Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/quick-start.md Sets up file logging with rotation and retention policies. This example configures a sink to write logs to 'logs/app.log', rotating the log file daily and retaining logs for 7 days. ```zig _ = try logger.addSink(.{ .path = "logs/app.log", .rotation = "daily", .retention = 7, // Keep 7 days }); ``` -------------------------------- ### Configuring Multiple Log Sinks (Zig) Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/quick-start.md Adds multiple destinations for log output. This example configures a standard console sink, a file sink for all messages ('app.log'), and a separate file sink specifically for error messages ('errors.log'). ```zig // Console sink _ = try logger.addSink(.{}); // File sink _ = try logger.addSink(.{ .path = "app.log", }); // Error-only file _ = try logger.addSink(.{ .path = "errors.log", .level = .err, }); ``` -------------------------------- ### Basic Logly-Zig Tracing Setup Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/tracing.md Demonstrates the basic initialization of the Logly logger and setting trace context for subsequent log entries. This involves initializing the logger, setting trace and span IDs, logging messages, and finally clearing the context. ```zig const logly = @import("logly"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var logger = try logly.Logger.init(allocator); defer logger.deinit(); // Set trace context (e.g., from incoming request) try logger.setTraceContext("trace-abc-123", "span-parent-456"); // All subsequent logs include the trace context try logger.info("Processing request"); try logger.debug("Validating input"); try logger.info("Request completed"); // Clear context when done logger.clearTraceContext(); } ``` -------------------------------- ### Implement Log Sampling Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/README.md Details how to configure log sampling for high-throughput scenarios. This example shows initializing a sampler with a specific probability (e.g., 50%) and then setting it on the logger. Sampling is useful for reducing the amount of log data generated in performance-critical applications. ```zig // Sample 50% of logs for high-throughput scenarios var sampler = logly.Sampler.init(allocator, .{ .probability = 0.5 }); defer sampler.deinit(); logger.setSampler(&sampler); ``` -------------------------------- ### Configure Logly Scheduler Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/examples/scheduler.md Sets up the scheduler's configuration, including parameters like maximum tasks, timer resolution, thread pool size, and persistence options. It shows both direct configuration and using a helper method. ```zig const logly = @import("logly"); var config = logly.Config.default(); config.scheduler = logly.SchedulerConfig{ .max_tasks = 512, .timer_resolution_ms = 10, .thread_pool_size = 4, .enable_persistence = true, .persistence_path = "scheduler.state", }; // Or use helper method var config2 = logly.Config.default().withScheduler(.{ .max_tasks = 256, .timer_resolution_ms = 50, }); ``` -------------------------------- ### Schedule Task for Non-Peak Hours Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/scheduler.md Example of scheduling a task, such as cleanup, during off-peak hours (3 AM daily) to minimize impact on system performance. ```zig // Run cleanup during low-traffic hours .schedule = logly.Schedule.daily(3, 0), // 3 AM ``` -------------------------------- ### Get Secure Configuration (Zig) Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/api/config.md Provides a security-focused configuration for Logly. This setup enables redaction, structured logging, and prevents the exposure of hostname and PID. ```zig const config = logly.Config.secure(); ``` -------------------------------- ### Enable and Use Logger Metrics Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/README.md Explains how to enable metrics collection within the logger and retrieve a snapshot of collected metrics. This example shows initializing the logger, enabling metrics, logging some messages, and then accessing the metrics snapshot to print the total number of logs and errors recorded. Metrics provide insights into logging activity. ```zig const logger = try logly.Logger.init(allocator); defer logger.deinit(); // Enable metrics collection logger.enableMetrics(); // Log some messages try logger.info("Request processed", @src()); try logger.err("Database error", @src()); // Get metrics snapshot if (logger.getMetrics()) |snapshot| { std.debug.print("Total logs: {}\n", .{snapshot.total_records}); std.debug.print("Errors: {}\n", .{snapshot.error_count}); } ``` -------------------------------- ### Get Default Configuration (Zig) Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/api/config.md Retrieves the default configuration object for Logly. This method is useful for starting with a baseline configuration and then applying specific modifications. ```zig const config = logly.Config.default(); ``` -------------------------------- ### Configure Timezone Offset for Scheduler Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/scheduler.md Illustrates how to set the timezone offset for the scheduler. This affects how scheduled times are interpreted. Examples are provided for UTC, EST, CET, and PST. ```zig // UTC .timezone_offset = 0 // Eastern Time (EST) .timezone_offset = -5 // Central European Time (CET) .timezone_offset = 1 // Pacific Time (PST) .timezone_offset = -8 ``` -------------------------------- ### Get Scheduler Statistics Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/scheduler.md Retrieves performance statistics from the scheduler, including the number of tasks executed, tasks failed, files cleaned, and bytes freed. These statistics are loaded atomically. ```zig const stats = scheduler.getStats(); std.debug.print("Tasks executed: {d}\n", .{ stats.tasks_executed.load(.monotonic), }); std.debug.print("Tasks failed: {d}\n", .{ stats.tasks_failed.load(.monotonic), }); std.debug.print("Files cleaned: {d}\n", .{ stats.files_cleaned.load(.monotonic), }); std.debug.print("Bytes freed: {d}\n", .{ stats.bytes_freed.load(.monotonic), }); ``` -------------------------------- ### High Throughput Thread Pool Preset Usage Source: https://github.com/muhammad-fiaz/logly.zig/blob/main/docs/guide/thread-pool.md Example of initializing a thread pool using the `highThroughput` preset for scenarios demanding maximum performance in log processing. ```zig // Use high throughput preset var pool = try logly.ThreadPool.init( allocator, logly.ThreadPoolPresets.highThroughput(), ); ```