diff options
author | eudoxia <uplink@distress.network> | 2022-03-31 10:19:21 -0400 |
---|---|---|
committer | eudoxia <uplink@distress.network> | 2022-03-31 10:19:21 -0400 |
commit | 27f4773b122a2758cfaf88537c9e1a8ad5df7e69 (patch) | |
tree | f6a31476fee7208d1ceb49186b243b106b09a5bd /log.lp |
initial
Diffstat (limited to 'log.lp')
-rw-r--r-- | log.lp | 63 |
1 files changed, 63 insertions, 0 deletions
@@ -0,0 +1,63 @@ +# log.zig + +This file contains a simple logging function. It is a modified version of the example logging function implementation provided in `std.log`. + +@: * +@= Imports + +@= Level setting + +@= Logging function +@. + +We first import the standard library, and the `Level` type which is an enum representing the possible log levels. + +@: Imports +const std = @import("std"); +const Level = std.log.Level; +@. + +The logging function is structured such that only log messages equal to or above a certain severity threshold will be printed to the console. This threshold can then be globally modified during development. The threshold constant is defined below. + +@: Level setting +pub const log_level: Level = .warn; +@. + +We then define the logging function itself, which accepts a `Level` value and the format string and argument struct to be passed to the inner print function. + +@: Logging function +pub fn log( + comptime level: Level, + comptime format: []const u8, + args: anytype, +) void { + @= Compare with level threshold + + @= Define message string + + @= Print to console +} +@. + +First the comparison against the severity threshold is made. (A lower integer value signifies a higher severity.) If the severity is lower than the threshold, the function immediately exits. + +@: Compare with level threshold +if (@enumToInt(level) > @enumToInt(log_level)) return; +@. + +Next the message string is created. The unformatted content of this string is evaluated at compile-time, before being formatted by the print function at runtime. The "info" and "error" log levels use custom names, whereas all other levels use their default display names. + +@: Define message string +const msg = "[" ++ switch (level) { + .info => "ok", + .err => "err", + else => level.asText(), +} ++ "]\t" ++ format ++ "\n"; +@. + +Finally, the message is printed to the console. If an error is returned by the `print()` call, the logging function silently exits. + +@: Print to console +const stderr = std.io.getStdErr().writer(); +nosuspend stderr.print(msg, args) catch return; +@. |