diff --git a/engine/lib/p2/src/structures/structured-logging.zig b/engine/lib/p2/src/structures/structured-logging.zig index b9abb8b..f4f0139 100644 --- a/engine/lib/p2/src/structures/structured-logging.zig +++ b/engine/lib/p2/src/structures/structured-logging.zig @@ -1,9 +1,5 @@ // experiment with a specialized logging infrastructure. // structured logging. -// -// It can log to an ultra tiny in-memory buffer directly, -// or it can log to a second writer thread. -// but the way it all works is it goes through this logger pub const ArgsDecoderOpKind = enum { boolean, @@ -11,9 +7,11 @@ pub const ArgsDecoderOpKind = enum { floating, string, // []u8 and []const u8 structure, + enumeration, }; pub const ArgsDecoderOp = struct { + type_name: []const u8 = "", kind: ArgsDecoderOpKind, bits: u16 = 0, signed: bool = false, @@ -41,6 +39,14 @@ pub const ArgsDecoder = struct { var op: ArgsDecoderOp = .{ .kind = ArgsSerializer.kindFor(T) }; switch (@typeInfo(T)) { .bool => op.bits = 8, + .@"enum" => |info| { + const int = @typeInfo(info.tag_type).int; + op.bits = int.bits; + op.signed = int.signedness == .signed; + const full_name = @typeName(T); + const name_start = if (std.mem.lastIndexOfScalar(u8, full_name, '.')) |index| index + 1 else 0; + op.type_name = full_name[name_start..]; + }, .comptime_int => op.bits = 32, .comptime_float => op.bits = 64, .int => |info| { @@ -86,6 +92,7 @@ pub const ArgsSerializer = struct { fn kindFor(comptime T: type) ArgsDecoderOpKind { return switch (@typeInfo(T)) { .bool => .boolean, + .@"enum" => .enumeration, .comptime_int, .int => .integer, .comptime_float, .float => .floating, .@"struct" => .structure, @@ -107,6 +114,7 @@ pub const ArgsSerializer = struct { const T = @TypeOf(value); switch (comptime kindFor(T)) { .boolean => try output.writeByte(@intFromBool(value)), + .enumeration => try writeValue(@backingInt(value), output), .integer => { if (T == comptime_int) { return output.writeInt(u32, std.math.cast(u32, value) orelse return error.IntegerOutOfRange, .little); @@ -168,7 +176,7 @@ pub const RenderOp = union(enum) { fn supports(self: Format, kind: ArgsDecoderOpKind) bool { return switch (kind) { .boolean => self == .any, - .integer => switch (self) { + .enumeration, .integer => switch (self) { .any, .decimal, .hex_lower, .hex_upper, .binary, .octal => true, else => false, }, @@ -274,6 +282,7 @@ pub const LoggerSystemInitOptions = struct { const PendingLog = struct { site: *const LogSite, logger: *const LoggerState, + verbosity: Verbosity, serialized_args: []const u8, }; @@ -299,19 +308,29 @@ pub const LoggerSystem = struct { logSites: std.ArrayList(LogSite) = .empty, entries: std.ArrayList(StructuredLog) = .empty, + outputWriters: std.ArrayList(*std.Io.Writer) = .empty, + pub const EnqueueError = ArgsSerializer.Error || std.mem.Allocator.Error || error{ QueueFull, Closed }; + pub fn addStdout(self: *@This()) !void { + try self.addWriter(self.stdout_writer); + } + + pub fn addWriter(self: *@This(), writer: *std.Io.Writer) !void { + try self.outputWriters.append(self.arena.allocator(), writer); + } + /// Encodes using argument types only. No registry access or shared writer. /// On success, ownership of the payload transfers to the queue. /// Site/logger descriptors must outlive all queued and retained events. - pub fn enqueue(self: *@This(), site: *const LogSite, logger: *const LoggerState, args: anytype) EnqueueError!void { + pub fn enqueue(self: *@This(), site: *const LogSite, logger: *const LoggerState, verbosity: Verbosity, args: anytype) EnqueueError!void { var writer: std.Io.Writer.Allocating = .init(self.payload_allocator); defer writer.deinit(); try ArgsSerializer.serialize(args, &writer.writer); const bytes = try writer.toOwnedSlice(); errdefer self.payload_allocator.free(bytes); - const pending: PendingLog = .{ .site = site, .logger = logger, .serialized_args = bytes }; + const pending: PendingLog = .{ .site = site, .logger = logger, .verbosity = verbosity, .serialized_args = bytes }; if (try self.queue.putUncancelable(self.io, &.{pending}, 0) == 0) { _ = self.dropped.fetchAdd(1, .monotonic); return error.QueueFull; @@ -342,6 +361,7 @@ pub const LoggerSystem = struct { try self.logSites.ensureUnusedCapacity(allocator, 1); const id = std.math.cast(u32, self.logSites.items.len) orelse return error.TooManySites; + // Site metadata is static; hot-reloaded modules remain loaded. self.logSites.appendAssumeCapacity(site.*); self.logMap.putAssumeCapacity(site, id); @@ -370,14 +390,23 @@ pub const LoggerSystem = struct { return err; }; self.entries.appendAssumeCapacity(log); - if (entry.logger.stdout) try log.render(self, self.stdout_writer); + for (self.outputWriters.items) |writer| { + std.debug.print("rendering\n", .{}); + try log.render(self, writer); + } } + + for (self.outputWriters.items) |writer| { + try writer.flush(); + } + return count; } fn accept(self: *@This(), pending: PendingLog) !StructuredLog { return .{ .serialized_args = pending.serialized_args, + .verbosity = pending.verbosity, .loggerId = try self.getOrRegisterLoggerState(pending.logger), .sourceId = try self.getOrRegisterSite(pending.site), }; @@ -498,6 +527,7 @@ pub const LoggerOptions = struct { pub const StructuredLog = struct { serialized_args: []const u8, // not a string + verbosity: Verbosity, loggerId: u32, sourceId: u32, @@ -518,10 +548,12 @@ pub const StructuredLog = struct { const site = logger.logSites.items[self.sourceId]; const ops = site.decoder.ops; var payload = Cursor{ .bytes = self.serialized_args }; - for (ops) |op| try skipValue(op, &payload, 0); + + for (ops) |op| try skipValue(op, &payload, 0); // todo remove. if (payload.bytes.len != 0) return error.InvalidPayload; - try writer.print("[{d}] [{d}] ", .{ self.loggerId, self.sourceId }); + const state = logger.loggerStatesById.items[self.loggerId]; + try writer.print("[{s}] [{s}:{d}] ", .{ state.name, site.source.file, site.source.line }); for (site.render_ops) |render_op| switch (render_op) { .literal => |text| try writer.writeAll(text), .argument => |arg| { @@ -570,7 +602,7 @@ pub const StructuredLog = struct { if (depth > 64) return error.InvalidSchema; switch (op.kind) { .boolean => _ = try cursor.boolean(), - .integer, .floating => { + .integer, .enumeration, .floating => { if (op.bits > 128) return error.InvalidSchema; if (op.kind == .floating) switch (op.bits) { 16, 32, 64, 80, 128 => {}, @@ -588,6 +620,20 @@ pub const StructuredLog = struct { if (!format.supports(op.kind)) return error.UnsupportedFormat; switch (op.kind) { .boolean => try writer.printValue("", options, try cursor.boolean(), std.fmt.default_max_depth), + .enumeration => { + var integer_op = op; + integer_op.kind = .integer; + + if (format == .any) { + try writer.writeAll(op.type_name); + try writer.writeByte('('); + } + + try renderValue(integer_op, cursor, format, options, writer, depth); + if (format == .any) { + try writer.writeByte(')'); + } + }, .integer => { const base: u8 = switch (format) { .any, .decimal => 10, @@ -675,7 +721,7 @@ pub fn DeclareLogger(comptime LoggerName: []const u8, comptime opts: LoggerOptio const FmtSite = struct { pub const site = LogSite.init(LogRef.fromSrcFmt(s, fmt), @TypeOf(args)); }; - try gLoggerSystem.enqueue(&FmtSite.site, &loggerState, args); + try gLoggerSystem.enqueue(&FmtSite.site, &loggerState, v, args); } /// Drop new events when full; callers needing retries can use tryAddLog. @@ -701,12 +747,14 @@ test "structured logging end to end" { try std.testing.expectEqual(before, gLoggerSystem.entries.items.len); try std.testing.expectEqual(@as(usize, 1), try drain()); const entry = gLoggerSystem.entries.items[before]; + try std.testing.expectEqual(Verbosity.log, entry.verbosity); var output: std.Io.Writer.Allocating = .init(std.testing.allocator); defer output.deinit(); try entry.render(&gLoggerSystem, &output.writer); var expected: std.Io.Writer.Allocating = .init(std.testing.allocator); defer expected.deinit(); - try expected.writer.print("[{d}] [{d}] ", .{ entry.loggerId, entry.sourceId }); + const source = gLoggerSystem.logSites.items[entry.sourceId].source; + try expected.writer.print("[normal] [{s}:{d}] ", .{ source.file, source.line }); try expected.writer.print(fmt ++ "\n", args); try std.testing.expectEqualStrings(expected.written(), output.written()); } @@ -804,6 +852,7 @@ test "concurrent logging with bounded queue and simultaneous main thread drain" const id: usize = @intCast(try cursor.integer(4)); try std.testing.expect(id < next.len); const seq: u32 = @intCast(try cursor.integer(4)); + try std.testing.expectEqual(if (seq % 2 == 0) Verbosity.log else Verbosity.warn, entry.verbosity); try std.testing.expectEqual(next[id], seq); next[id] += 1; const text: [4]u8 = @splat(@intCast('a' + id)); @@ -812,7 +861,9 @@ test "concurrent logging with bounded queue and simultaneous main thread drain" try entry.render(&gLoggerSystem, &output.writer); var expected: std.Io.Writer.Allocating = .init(std.testing.allocator); defer expected.deinit(); - try expected.writer.print("[{d}] [{d}] {s} {d}:{d} {s}\n", .{ entry.loggerId, entry.sourceId, if (seq % 2 == 0) "A" else "B", id, seq, text }); + const source = gLoggerSystem.logSites.items[entry.sourceId].source; + const name = if (seq % 2 == 0) "producer-A" else "producer-B"; + try expected.writer.print("[{s}] [{s}:{d}] {s} {d}:{d} {s}\n", .{ name, source.file, source.line, if (seq % 2 == 0) "A" else "B", id, seq, text }); try std.testing.expectEqualStrings(expected.written(), output.written()); } for (next) |n| try std.testing.expectEqual(@as(u32, 256), n); @@ -821,10 +872,26 @@ test "concurrent logging with bounded queue and simultaneous main thread drain" test "testing" { const xxd = @import("xxd.zig"); + const TestEnum = enum(u8) { + hello = 0, + world = 5, + ending, + }; + + const TestEnum2 = enum(u24) { + hello = 0, + world = 5, + ending, + }; + initialize(std.testing.io, std.testing.allocator); defer deinit(); const Logger = DeclareLogger("mylogger", .{ .verbosity = .verbose }); - Logger.addLog(@src(), .log, "who doesn't {} {s} 2 + 2 is {d}", .{ true, "dragons", 4 }); + Logger.addLog(@src(), .log, "{} {} who doesn't {} {s} 2 + 2 is {d}", .{ TestEnum.ending, TestEnum2.ending, true, "dragons", 4 }); + + var log = std.Io.Writer.Allocating.init(std.testing.allocator); + try gLoggerSystem.addWriter(&log.writer); + const drained = try gLoggerSystem.drain(); var writer = std.Io.Writer.Allocating.init(std.testing.allocator); @@ -837,6 +904,10 @@ test "testing" { var x = writer.toArrayList(); defer x.deinit(std.testing.allocator); - std.debug.print("{s}\n", .{x.items}); + std.debug.print("{s}\n {d} bytes serialized\n", .{ x.items, item.serialized_args.len }); } + + var y = log.toArrayList(); + defer y.deinit(std.testing.allocator); + std.debug.print("log>\n{s}\n", .{y.items}); }