Created
August 23, 2024 18:24
-
-
Save dnut/4aa20d3acbd81a668a64878bfddf2d4c to your computer and use it in GitHub Desktop.
zig scoped logging poc using the type system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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