Skip to content

Rotation API ​

The Rotation module provides enterprise-grade log rotation capabilities, including time-based and size-based rotation, retention policies, compression, and flexible naming strategies.

Quick Reference: Method Aliases ​

Full MethodAlias(es)Description
init()create()Initialize rotation
deinit()destroy()Deinitialize rotation

Rotation Struct ​

The core struct managing rotation logic.

zig
const Rotation = @import("logly").Rotation;

Initialization ​

zig
pub fn init(
    allocator: std.mem.Allocator,
    path: []const u8,
    interval_str: ?[]const u8, // "daily", "hourly", etc.
    size_limit: ?u64,          // Bytes
    retention: ?usize          // Max files to keep
) !Rotation

Configuration Methods ​

withCompression ​

Enables automatic compression of rotated files.

zig
pub fn withCompression(self: *Rotation, config: CompressionConfig) !void

Example:

zig
try rot.withCompression(.{ .algorithm = .deflate });

withNaming ​

Sets the naming strategy for rotated files.

zig
pub fn withNaming(self: *Rotation, strategy: NamingStrategy) void

Example:

zig
rot.withNaming(.iso_datetime);

withNamingFormat ​

Sets a custom format string for rotated files. Automatically sets strategy to .custom.

zig
pub fn withNamingFormat(self: *Rotation, format: []const u8) !void

Example:

zig
try rot.withNamingFormat("{base}-{date}{ext}");

withMaxAge ​

Sets a maximum age (in seconds) for retaining log files.

zig
pub fn withMaxAge(self: *Rotation, seconds: i64) void

Example:

zig
rot.withMaxAge(86400 * 7); // 7 days

withArchiveDir ​

Sets a specific directory to move rotated files into.

zig
pub fn withArchiveDir(self: *Rotation, dir: []const u8) !void

Example:

zig
try rot.withArchiveDir("logs/archive");

withKeepOriginal ​

Set whether to keep original files after compression.

zig
pub fn withKeepOriginal(self: *Rotation, keep: bool) void

Example:

zig
rot.withKeepOriginal(true); // Keep both original and compressed files

withCompressOnRetention ​

Enable compression during retention cleanup instead of deletion.

zig
pub fn withCompressOnRetention(self: *Rotation, enable: bool) void

Example:

zig
rot.withCompressOnRetention(true); // Compress old files instead of deleting

withDeleteAfterRetentionCompress ​

Set whether to delete original files after retention compression.

zig
pub fn withDeleteAfterRetentionCompress(self: *Rotation, delete: bool) void

Example:

zig
rot.withDeleteAfterRetentionCompress(false); // Keep originals after compression

applyConfig ​

Applies global configuration settings to the rotation instance.

zig
pub fn applyConfig(self: *Rotation, config: RotationConfig) !void

Example:

zig
try rot.applyConfig(global_config.rotation);

Configuration Structs ​

RotationConfig ​

Global configuration struct for rotation defaults.

zig
pub const RotationConfig = struct {
    enabled: bool = false,
    interval: ?[]const u8 = null,
    size_limit: ?u64 = null,
    size_limit_str: ?[]const u8 = null,
    retention_count: ?usize = null,
    max_age_seconds: ?i64 = null,
    naming_strategy: NamingStrategy = .timestamp,
    naming_format: ?[]const u8 = null,
    archive_dir: ?[]const u8 = null,
    clean_empty_dirs: bool = false,
    async_cleanup: bool = false,
    keep_original: bool = false,                    // Keep original after compression
    compress_on_retention: bool = false,            // Compress instead of delete during retention
    delete_after_retention_compress: bool = true,   // Delete originals after retention compression
    archive_root_dir: ?[]const u8 = null,           // Root directory for all archives
    create_date_subdirs: bool = false,              // Create YYYY/MM/DD subdirectories
    file_prefix: ?[]const u8 = null,                // Custom prefix for rotated files
    file_suffix: ?[]const u8 = null,                // Custom suffix for rotated files
    compression_algorithm: CompressionAlgorithm = .gzip,
    compression_level: CompressionLevel = .default,
};

RotationConfig Field Reference ​

FieldTypeDefaultDescription
enabledboolfalseEnable rotation
interval?[]const u8nullTime-based interval (e.g., "daily")
size_limit?u64nullSize-based rotation threshold (bytes)
retention_count?usizenullMax files to retain
max_age_seconds?i64nullMax age for rotated files
naming_strategyNamingStrategy.timestampFile naming strategy
archive_dir?[]const u8nullDirectory for rotated files
archive_root_dir?[]const u8nullCentralized archive root
create_date_subdirsboolfalseCreate YYYY/MM/DD subdirs
file_prefix?[]const u8nullPrefix for rotated file names
file_suffix?[]const u8nullSuffix for rotated file names
compression_algorithmCompressionAlgorithm.gzipAlgorithm for compression
compression_levelCompressionLevel.defaultCompression level
keep_originalboolfalseKeep original after compression
compress_on_retentionboolfalseCompress instead of delete
delete_after_retention_compressbooltrueDelete after retention compression
clean_empty_dirsboolfalseRemove empty directories

Enums ​

RotationInterval ​

Defines the time interval for rotation.

ValueDescription
.minutelyRotate every minute.
.hourlyRotate every hour.
.dailyRotate every day (24 hours).
.weeklyRotate every week.
.monthlyRotate every 30 days.
.yearlyRotate every 365 days.

NamingStrategy ​

Defines how rotated files are named.

ValueExample (app.log)Notes
.timestampapp.log.167882233Default for size/hourly rotation.
.dateapp.log.2023-01-01Default for daily/weekly/monthly.
.iso_datetimeapp.log.2023-01-01T12-00-00High precision.
.indexapp.log.1, app.log.2Rolling log style.
.customapp-2023-01-01.logUses naming_format.

Custom Format Placeholders ​

When using .custom (or setting naming_format), you can use:

PlaceholderDescription
{base}Filename without extension
{ext}Extension (including dot)
{date}YYYY-MM-DD
{time}HH-mm-ss
{timestamp}Unix timestamp
{iso}ISO 8601 Datetime

Flexible Date/Time Placeholders: You can also use {YYYY}, {YY}, {MM}, {M}, {DD}, {D}, {HH}, {H}, {mm}, {m}, {ss}, {s} and any separators. Example: app-{YYYY}/{M}/{D}.log -> app-2023/10/5.log

Statistics ​

The RotationStats struct provides insights into the rotation process.

FieldTypeDescription
total_rotationsAtomicUnsignedTotal number of rotations performed.
files_archivedAtomicUnsignedNumber of files successfully compressed.
files_deletedAtomicUnsignedNumber of files deleted due to retention policy.
last_rotation_time_msAtomicUnsignedDuration of the last rotation operation.
rotation_errorsAtomicUnsignedCount of rotation failures.
compression_errorsAtomicUnsignedCount of compression failures.

Presets ​

The RotationPresets struct offers common configurations.

zig
// Daily rotation, keep 7 days
const rot = try RotationPresets.daily7Days(allocator, path);

// Size based (10MB), keep 5 files
const rot = try RotationPresets.size10MB(allocator, path);

Example Usage ​

zig
var rotation = try Rotation.init(allocator, "app.log", "daily", null, 30);

// Enable compression
try rotation.withCompression(.{ .algorithm = .deflate });

// Logic ensures checks are fast
try rotation.checkAndRotate(&file);

Released under the MIT License.