Skip to content

Instantly share code, notes, and snippets.

@dnut
Created August 23, 2024 18:24
Show Gist options
  • Save dnut/4aa20d3acbd81a668a64878bfddf2d4c to your computer and use it in GitHub Desktop.
Save dnut/4aa20d3acbd81a668a64878bfddf2d4c to your computer and use it in GitHub Desktop.
zig scoped logging poc using the type system
const std = @import("std");
pub fn main() void {
const logger: Logger = .{};
logger.log("starting the app");
const stuff = Stuff.init(logger);
stuff.doStuff();
}
const Stuff = struct {
logger: ScopedLogger("stuff"),
pub fn init(logger: Logger) @This() {
return .{ .logger = logger.withScope("stuff") };
}
pub fn doStuff(self: @This()) void {
self.logger.log("doing stuff");
const child = StuffChild.init(self.logger.unscoped());
child.doStuffDetails();
}
};
const StuffChild = struct {
logger: ScopedLogger("stuff-child"),
pub fn init(logger: Logger) @This() {
return .{ .logger = logger.withScope("stuff-child") };
}
pub fn doStuffDetails(self: @This()) void {
self.logger.log("doing stuff details");
}
};
const Logger = ScopedLogger(null);
fn ScopedLogger(scope: ?[]const u8) type {
return struct {
fn unscoped(_: @This()) Logger {
return .{};
}
fn withScope(_: @This(), comptime new_scope: anytype) ScopedLogger(new_scope) {
return .{};
}
fn log(_: @This(), message: []const u8) void {
if (scope) |scope_str| {
std.debug.print("{s} - {s}\n", .{ scope_str, message });
} else {
std.debug.print("{s}\n", .{message});
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment