//! Log lines on stdout, for following what the interactive server does. //! //! `main` installs `logFn` as std.log's, so the rest of the tree logs through //! `std.log.scoped(...)` and needs nothing passed to it. std.log filters by a //! level fixed at compile time; that one is set to debug, and the level chosen //! at startup is applied here instead. const std = @import("std"); const epoch = std.time.epoch; const Writer = std.Io.Writer; /// The most detailed level still written. Read on every log call, which is /// why it is global rather than handed around. var threshold: std.log.Level = .info; // zlinter-disable-current-line no_global_vars /// What is being served right now. The server sets it; every line logged /// meanwhile, from whichever module, carries it. var context: Context = .{}; // zlinter-disable-current-line no_global_vars /// Sets the level from the CSV2JOURNAL_LOG environment variable: info when /// unset, otherwise exactly `info` or `debug`. A misspelt value is refused /// rather than ignored, so asking for debug output never silently yields none. pub fn configure(value: ?[]const u8) error{InvalidLogLevel}!void { const text = value orelse "info"; threshold = if (std.mem.eql(u8, text, "info")) .info else if (std.mem.eql(u8, text, "debug")) .debug else return error.InvalidLogLevel; } pub fn enabled(level: std.log.Level) bool { return @backingInt(level) <= @backingInt(threshold); } pub fn logFn( comptime level: std.log.Level, comptime scope: @EnumLiteral(), comptime format: []const u8, args: anytype, ) void { if (!enabled(level)) return; var buffer: [1024]u8 = undefined; // Streaming, not positional: a positional writer on redirected stdout // starts at offset zero and would overwrite the previous line. var file_writer = std.Io.File.stdout().writerStreaming(std.Options.debug_io, &buffer); const writer = &file_writer.interface; // zlinter-disable-next-line no_swallow_error - a log line that cannot be written has nowhere to report that write(writer, .now(level, scope), context, format, args) catch return; // zlinter-disable-next-line no_swallow_error - as above writer.flush() catch return; } fn write( writer: *Writer, stamp: Stamp, about: Context, comptime format: []const u8, args: anytype, ) Writer.Error!void { try writer.print("{f}{f}" ++ format ++ "\n", .{ stamp, about } ++ args); } /// The server's connection, and the request on it, that lines are about. /// Both are numbered from one as they arrive, requests across connections, /// so "c3#42" names one request however many share its path. pub const Context = struct { connection: ?u32 = null, request: ?Request = null, pub const Request = struct { method: std.http.Method, number: u32, /// Without the query, which only the request's first line repeats. path: []const u8, }; pub fn format(self: Context, writer: *Writer) Writer.Error!void { const connection = self.connection orelse return; try writer.print("c{d}", .{connection}); const request = self.request orelse return writer.writeAll(" "); try writer.print("#{d} {t} {s}: ", .{ request.number, request.method, request.path }); } }; pub fn setConnection(connection: ?u32) void { context = .{ .connection = connection }; } /// The request's path must outlive it being set; clear it before freeing. pub fn setRequest(request: ?Context.Request) void { context.request = request; } /// What every line starts with: when, how severe, and where from. pub const Stamp = struct { level: std.log.Level, scope: ?[]const u8, time: std.Io.Timestamp, /// Reads only the real-time clock, so a signal handler may call it too. pub fn now(level: std.log.Level, comptime scope: @EnumLiteral()) Stamp { return .{ .level = level, .scope = if (scope == .default) null else @tagName(scope), .time = .now(std.Options.debug_io, .real), }; } pub fn format(self: Stamp, writer: *Writer) Writer.Error!void { const millis: u64 = @intCast(@max(0, self.time.toMilliseconds())); const seconds: epoch.EpochSeconds = .{ .secs = millis / std.time.ms_per_s }; const year_day = seconds.getEpochDay().calculateYearDay(); const month_day = year_day.calculateMonthDay(); const day_seconds = seconds.getDaySeconds(); try writer.print("{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}Z {s: <5} ", .{ year_day.year, month_day.month.numeric(), month_day.day_index + 1, day_seconds.getHoursIntoDay(), day_seconds.getMinutesIntoHour(), day_seconds.getSecondsIntoMinute(), millis % std.time.ms_per_s, levelText(self.level), }); if (self.scope) |scope| try writer.print("({s}) ", .{scope}); } fn levelText(level: std.log.Level) []const u8 { return switch (level) { .err => "ERROR", .warn => "WARN", .info => "INFO", .debug => "DEBUG", }; } }; // -- tests ------------------------------------------------------------------- const expect = std.testing.expect; const expectError = std.testing.expectError; const expectFmt = std.testing.expectFmt; fn at(seconds: i96, millis: i96) std.Io.Timestamp { return .fromNanoseconds(seconds * std.time.ns_per_s + millis * std.time.ns_per_ms); } test "a log line starts with the UTC time to the millisecond, the level and the scope" { try expectFmt( "2026-10-03T14:05:09.123Z INFO (server) ", "{f}", .{Stamp{ .level = .info, .scope = "server", .time = at(1791036309, 123) }}, ); try expectFmt( "2024-02-29T23:59:59.007Z DEBUG (session) ", "{f}", .{Stamp{ .level = .debug, .scope = "session", .time = at(1709251199, 7) }}, ); } test "a log line from the default scope names no scope" { try expectFmt( "1970-01-01T00:00:00.000Z ERROR ", "{f}", .{Stamp{ .level = .err, .scope = null, .time = at(0, 0) }}, ); } test "CSV2JOURNAL_LOG chooses info or debug, and info when unset" { defer configure(null) catch unreachable; try configure(null); try expect(enabled(.info)); try expect(!enabled(.debug)); try configure("debug"); try expect(enabled(.debug)); try configure("info"); try expect(enabled(.warn)); try expect(!enabled(.debug)); } test "CSV2JOURNAL_LOG refuses any other value and keeps the level" { defer configure(null) catch unreachable; try configure("debug"); for ([_][]const u8{ "", "DEBUG", "verbose", "warn" }) |value| { try expectError(error.InvalidLogLevel, configure(value)); } try expect(enabled(.debug)); } test "a stamp taken now carries the level, the scope and the current time" { const io = std.testing.io; const before: std.Io.Timestamp = .now(io, .real); const stamp: Stamp = .now(.warn, .server); const after: std.Io.Timestamp = .now(io, .real); try expect(stamp.level == .warn); try std.testing.expectEqualStrings("server", stamp.scope.?); try expect(before.nanoseconds <= stamp.time.nanoseconds); try expect(stamp.time.nanoseconds <= after.nanoseconds); const unscoped: Stamp = .now(.info, .default); try expect(unscoped.scope == null); } test "a line names the connection and request it belongs to, if any" { const stamp: Stamp = .{ .level = .debug, .scope = "server", .time = at(1791036309, 123) }; var buffer: [256]u8 = undefined; var outside: Writer = .fixed(&buffer); try write(&outside, stamp, .{}, "listening on {s}", .{"http://127.0.0.1:8080/"}); try std.testing.expectEqualStrings( "2026-10-03T14:05:09.123Z DEBUG (server) listening on http://127.0.0.1:8080/\n", outside.buffered(), ); var between: Writer = .fixed(&buffer); try write(&between, stamp, .{ .connection = 3 }, "accepted", .{}); try std.testing.expectEqualStrings( "2026-10-03T14:05:09.123Z DEBUG (server) c3 accepted\n", between.buffered(), ); var during: Writer = .fixed(&buffer); const request: Context.Request = .{ .method = .PUT, .number = 42, .path = "/api/rules" }; try write(&during, stamp, .{ .connection = 3, .request = request }, "decoded {d} rules", .{37}); try std.testing.expectEqualStrings( "2026-10-03T14:05:09.123Z DEBUG (server) c3#42 PUT /api/rules: decoded 37 rules\n", during.buffered(), ); }