1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
This file contains a simple logging function. It is a modified version of the example logging function implementation provided in `std.log`.
@: *
@= License
@= Imports
@= Level setting
@= Logging function
@.
@: License
// Copyright 2022 DistressNetwork° <uplink@distress.network>
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
@.
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;
@.
|