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;