Utils API
The Utils module provides consolidated utility functions for size parsing, duration parsing, time manipulation, and date formatting.
Overview
const logly = @import("logly");
const Utils = logly.Utils;
// Parse size strings
const bytes = Utils.parseSize("10MB"); // 10485760
// Parse duration strings
const ms = Utils.parseDuration("5m"); // 300000
// Time utilities
const tc = Utils.nowComponents();
std.debug.print("Year: {d}\n", .{tc.year});
// Date formatting
var buf: [32]u8 = undefined;
const date = try Utils.formatIsoDate(&buf, tc);Quick Reference: Method Aliases
| Full Method | Alias(es) | Description |
|---|---|---|
formatDatePattern() | format() | Format date with pattern |
formatDateToBuf() | formatToBuf() | Format date to buffer |
Size Parsing
parseSize
Parses a size string into bytes.
pub fn parseSize(s: []const u8) ?u64Supported units (case insensitive):
B- BytesK,KB- Kilobytes (×1024)M,MB- Megabytes (×1024²)G,GB- Gigabytes (×1024³)T,TB- Terabytes (×1024⁴)
Examples:
Utils.parseSize("1024") // 1024
Utils.parseSize("10KB") // 10240
Utils.parseSize("5 MB") // 5242880 (whitespace allowed)
Utils.parseSize("1GB") // 1073741824formatSize
Formats a byte size into a human-readable string.
pub fn formatSize(allocator: std.mem.Allocator, bytes: u64) ![]u8Example:
const str = try Utils.formatSize(allocator, 5242880);
defer allocator.free(str);
// str = "5.00 MB"Duration Parsing
parseDuration
Parses a duration string into milliseconds.
pub fn parseDuration(s: []const u8) ?i64Supported units (case insensitive):
ms- Millisecondss- Seconds (×1000)m- Minutes (×60000)h- Hours (×3600000)d- Days (×86400000)
Examples:
Utils.parseDuration("1000ms") // 1000
Utils.parseDuration("30s") // 30000
Utils.parseDuration("5m") // 300000
Utils.parseDuration("2h") // 7200000
Utils.parseDuration("1d") // 86400000formatDuration
Formats milliseconds into a human-readable string.
pub fn formatDuration(allocator: std.mem.Allocator, ms: i64) ![]u8Time Utilities
TimeComponents
Structure containing extracted time components.
pub const TimeComponents = struct {
year: i32,
month: u8, // 1-12
day: u8, // 1-31
hour: u64, // 0-23
minute: u64, // 0-59
second: u64, // 0-59
};fromEpochSeconds
Extracts time components from a Unix timestamp (seconds).
pub fn fromEpochSeconds(timestamp: i64) TimeComponentsfromMilliTimestamp
Extracts time components from a millisecond timestamp.
pub fn fromMilliTimestamp(timestamp: i64) TimeComponentsfromMilliTimestampLocal
Extracts local-time components from a millisecond timestamp.
pub fn fromMilliTimestampLocal(timestamp: i64) TimeComponentslocalUtcOffsetMinutes
Returns local UTC offset (in minutes) for a millisecond timestamp. The result is bounded to Constants.TimeConstants.min_utc_offset_minutes through Constants.TimeConstants.max_utc_offset_minutes.
pub fn localUtcOffsetMinutes(timestamp: i64) i16writeUtcOffset
Writes a UTC offset in +HH:MM/-HH:MM form.
pub fn writeUtcOffset(writer: anytype, offset_minutes: i16) !voidwriteUtcOffsetCompact
Writes a compact UTC offset in +HHMM/-HHMM form.
pub fn writeUtcOffsetCompact(writer: anytype, offset_minutes: i16) !voidnowComponents
Gets current time components.
pub fn nowComponents() TimeComponentscurrentSeconds
Returns current Unix timestamp in seconds.
pub fn currentSeconds() i64currentMillis
Returns current timestamp in milliseconds.
pub fn currentMillis() i64currentNanos
Returns current timestamp in nanoseconds.
pub fn currentNanos() i128isSameDay
Checks if two timestamps are on the same day.
pub fn isSameDay(ts1: i64, ts2: i64) boolisSameHour
Checks if two timestamps are in the same hour.
pub fn isSameHour(ts1: i64, ts2: i64) boolstartOfDay
Returns the start of the day (midnight) as epoch seconds.
pub fn startOfDay(timestamp: i64) i64startOfHour
Returns the start of the hour as epoch seconds.
pub fn startOfHour(timestamp: i64) i64elapsedMs
Calculates elapsed time in milliseconds since start_time.
pub fn elapsedMs(start_time: i64) u64elapsedSeconds
Calculates elapsed time in seconds since start_time.
pub fn elapsedSeconds(start_time: i64) u64durationSinceNs
Calculates duration in nanoseconds since a start time.
pub fn durationSinceNs(start_time: i128) u64Math & Rate Utilities
calculateRate
Calculates a rate (0.0 to 1.0) given a numerator and denominator.
pub fn calculateRate(numerator: u64, denominator: u64) f64calculateErrorRate
Calculates error rate (0.0 to 1.0) given error count and total count.
pub fn calculateErrorRate(errors: u64, total: u64) f64calculateAverage
Calculates average value given a sum and count.
pub fn calculateAverage(sum: u64, count: u64) f64calculateThroughput
Calculates throughput (items/sec) given a count and duration in nanoseconds.
pub fn calculateThroughput(count: u64, elapsed_ns: u64) f64calculateBytesPerSecond
Calculates bytes per second given bytes and duration in milliseconds.
pub fn calculateBytesPerSecond(bytes: u64, elapsed_ms: i64) f64calculateCRC32
Calculates CRC32 checksum of data.
pub fn calculateCRC32(data: []const u8) u32lzmaHash
Calculates LZMA hash for match finding.
pub fn lzmaHash(data: []const u8, len: usize) u14getCompressionExtension
Returns the canonical file extension for a given compression algorithm. Useful when generating archive or compressed file names consistently across rotation, scheduler, and compression utilities.
pub fn getCompressionExtension(algo: anytype) []const u8Example:
const ext = Utils.getCompressionExtension(CompressionAlgorithm.zstd); // ".zst"Note: Returns an empty string for .none.
Trace Context Utilities
TraceparentContext
Parsed W3C trace context fields returned by parseTraceparentHeader.
pub const TraceparentContext = struct {
version: []const u8,
trace_id: []const u8,
span_id: []const u8,
flags: []const u8,
sampled: bool,
};TraceparentError
Errors returned by formatTraceparentHeader validation.
pub const TraceparentError = error{
InvalidTraceId,
InvalidSpanId,
};parseTraceparentHeader
Parses a W3C traceparent header.
Expected format: 00-<32_hex_trace_id>-<16_hex_span_id>-<2_hex_flags>.
pub fn parseTraceparentHeader(header: []const u8) ?TraceparentContextReturns null for malformed headers, invalid hex values, or all-zero trace/span IDs.
formatTraceparentHeader
Formats a W3C traceparent header string from validated IDs.
pub fn formatTraceparentHeader(
allocator: std.mem.Allocator,
trace_id: []const u8,
span_id: []const u8,
sampled: bool
) ![]u8Returns:
TraceparentError.InvalidTraceIdwhentrace_idis invalid.TraceparentError.InvalidSpanIdwhenspan_idis invalid.
Example:
const traceparent = try Utils.formatTraceparentHeader(
allocator,
"4bf92f3577b34da6a3ce929d0e0e4736",
"00f067aa0ba902b7",
true,
);
defer allocator.free(traceparent);Date Formatting
formatDatePattern
Formats a date/time using a custom pattern.
pub fn formatDatePattern(
writer: anytype,
fmt: []const u8,
year: i32,
month: u8,
day: u8,
hour: u64,
minute: u64,
second: u64,
millis: u64
) !voidformatDatePatternWithOffset
Formats a date/time pattern and enables timezone tokens (ZZZ, ZZ).
pub fn formatDatePatternWithOffset(
writer: anytype,
fmt: []const u8,
year: i32,
month: u8,
day: u8,
hour: u64,
minute: u64,
second: u64,
millis: u64,
timezone_offset_minutes: i16
) !voidSupported tokens:
| Token | Description |
|---|---|
YYYY | 4-digit year |
YY | 2-digit year |
ZZZ | Timezone offset (+HH:MM) |
MM | 2-digit month (01-12) |
DD | 2-digit day (01-31) |
HH | 2-digit hour (00-23) |
mm | 2-digit minute (00-59) |
ss | 2-digit second (00-59) |
ZZ | Timezone offset (+HHMM) |
M | 1-2 digit month |
D | 1-2 digit day |
H | 1-2 digit hour |
formatDateToBuf
Formats a date/time to a buffer.
pub fn formatDateToBuf(buf: []u8, fmt: []const u8, year: i32, month: u8, day: u8, hour: u64, minute: u64, second: u64, millis: u64) ![]u8formatDateToBufWithOffset
Formats a date/time pattern to a buffer with timezone token support.
pub fn formatDateToBufWithOffset(buf: []u8, fmt: []const u8, year: i32, month: u8, day: u8, hour: u64, minute: u64, second: u64, millis: u64, timezone_offset_minutes: i16) ![]u8formatIsoDate
Formats an ISO 8601 date (YYYY-MM-DD).
pub fn formatIsoDate(buf: []u8, tc: TimeComponents) ![]u8formatIsoTime
Formats an ISO 8601 time (HH:MM:SS).
pub fn formatIsoTime(buf: []u8, tc: TimeComponents) ![]u8formatIsoDateTime
Formats an ISO 8601 datetime (YYYY-MM-DDTHH:MM:SS).
pub fn formatIsoDateTime(buf: []u8, tc: TimeComponents) ![]u8formatFilenameSafe
Formats a filename-safe datetime (YYYY-MM-DD_HH-MM-SS).
pub fn formatFilenameSafe(buf: []u8, tc: TimeComponents) ![]u8Pattern Matching
matchRegexPattern
Anchored regex-like matching starting from the beginning of the string.
pub fn matchRegexPattern(input: []const u8, pattern: []const u8) ?usizeSupported Syntax:
.- Any character*- Zero or more of previous token+- One or more of previous token?- Zero or one of previous token\d,\D- Digit / Non-digit\w,\W- Alphanumeric +_/ Non-alphanumeric\s,\S- Whitespace / Non-whitespace
findRegexPattern
Searches for the first occurrence of a regex pattern anywhere in the string.
pub fn findRegexPattern(input: []const u8, pattern: []const u8) ?[]const u8Example:
if (Utils.findRegexPattern("error at line 42", "\\d+")) |match| {
// match = "42"
}String & Redaction Utilities
replaceString
Replaces all occurrences of a substring with a replacement string. Allocates a new string for the result.
pub fn replaceString(allocator: std.mem.Allocator, input: []const u8, needle: []const u8, replacement: []const u8) ![]u8maskString
Masks a string for redaction purposes. Supports full masking, partial start/end, and middle masking.
pub fn maskString(
allocator: std.mem.Allocator,
value: []const u8,
mask_char: u8,
start_reveal: usize,
end_reveal: usize,
mode: enum { full, partial_start, partial_end, mask_middle }
) ![]u8Modes:
full: Masks the entire string (result length = input length).partial_start: Shows the beginning of the string, masks the rest.partial_end: Shows the end of the string, masks the beginning.mask_middle: Shows start and end, masks the middle (e.g., credit cards).
computeRedactionHash
Computes a short SHA256 hash (first 8 bytes) formatted as hex for consistent redaction replacement.
pub fn computeRedactionHash(allocator: std.mem.Allocator, value: []const u8) ![]u8Format: [HASH:<16_char_hex>]
General Utilities
clamp
Clamps a value between min and max bounds.
pub fn clamp(comptime T: type, value: T, min_val: T, max_val: T) TsafeToUnsigned
Safely converts a signed integer to unsigned (returns 0 for negatives).
pub fn safeToUnsigned(comptime T: type, value: anytype) Tmin / max
Returns the minimum or maximum of two values.
pub fn min(comptime T: type, a: T, b: T) T
pub fn max(comptime T: type, a: T, b: T) TUsage Example
const std = @import("std");
const logly = @import("logly");
pub fn main() !void {
// Parse configuration sizes
const max_size = logly.Utils.parseSize("10MB") orelse 10485760;
const timeout = logly.Utils.parseDuration("30s") orelse 30000;
// Get current time
const now = logly.Utils.nowComponents();
// Format for display
var buf: [32]u8 = undefined;
const date_str = try logly.Utils.formatIsoDate(&buf, now);
std.debug.print("Today: {s}\n", .{date_str});
// Calculate elapsed time
const start = logly.Utils.currentMillis();
// ... do work ...
const elapsed = logly.Utils.elapsedMs(start);
std.debug.print("Elapsed: {d}ms\n", .{elapsed});
}See Also
- Config API - Configuration options
- Rotation Guide - Log rotation
