diff --git a/src/root.zig b/src/root.zig index 8927df0..2cb4dc0 100644 --- a/src/root.zig +++ b/src/root.zig @@ -25,47 +25,53 @@ pub const Options = struct { disabled_in_test: bool = true, }; -/// Used to create a logger from. +pub const empty_logger = Logger{ .base_tags = &.{} }; + +/// A Logger. Examples: /// -/// Examples: /// ```zig -/// const logger = Logger(&.{.my_module}); -/// const foo_bar_logger = Logger(&.{.foo, .bar}); -/// const foo_bar_log = foo_bar_logger.log; +/// pub const module_log = Logger{ .base_tags = &.{.module} }; +/// module_log.log(.debug, "Hello {s}!", .{"World"}); /// +/// pub const sub_module_log = module_log.scope(.bar); +/// sub_module_log.log(.perf, "Operation took {} ns", .{time_ns}); /// ``` -pub fn Logger(comptime base_tags: []const @Type(.enum_literal)) type { - return struct { - /// Creates a new logger with an extended tag prefix. - pub fn scope(comptime tag: @Type(.enum_literal)) type { - return Logger(base_tags ++ [_]@Type(.enum_literal){tag}); - } +pub const Logger = @This(); - /// Log with one `tag`. Checks whether the log is enabled. - pub fn log( - comptime tag: @Type(.enum_literal), - comptime format: []const u8, - args: anytype, - ) void { - logTags(&.{tag}, format, args); - } +base_tags: []const @Type(.enum_literal), - /// Log with multiple `tags`. Checks whether the log is enabled. - pub fn logTags( - comptime tags: []const @Type(.enum_literal), - comptime format: []const u8, - args: anytype, - ) void { - if (builtin.is_test and options.disabled_in_test) return; - - const all_tags = comptime base_tags ++ tags; - if (!options.enabled(all_tags)) return; - - options.function(all_tags, format, args); - } +/// Creates a new logger with an extended tag prefix. +pub fn scope(comptime logger: Logger, comptime tag: @TypeOf(.enum_literal)) Logger { + return .{ + .base_tags = logger.base_tags ++ [_]@Type(.enum_literal){tag}, }; } +/// Log with one `tag`. Checks whether the log is enabled. +pub fn log( + comptime logger: Logger, + comptime tag: @Type(.enum_literal), + comptime format: []const u8, + args: anytype, +) void { + logger.logTags(&.{tag}, format, args); +} + +/// Log with multiple `tags`. Checks whether the log is enabled. +pub fn logTags( + comptime logger: Logger, + comptime tags: []const @Type(.enum_literal), + comptime format: []const u8, + args: anytype, +) void { + if (builtin.is_test and options.disabled_in_test) return; + + const all_tags = comptime logger.base_tags ++ tags; + if (!options.enabled(all_tags)) return; + + options.function(all_tags, format, args); +} + /// Return `false` if `as` and `bs` have no common member. Else return `true`. fn intersect(comptime as: []const @Type(.enum_literal), comptime bs: []const @Type(.enum_literal)) bool { for (as) |a| {