This file contains a simple logging function. It is a modified version of the example logging function implementation provided in std.log.




(Level setting)

(Logging function)


// 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.


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.

const stderr = std.io.getStdErr().writer();
nosuspend stderr.print(msg, args) catch return;