Locking && logging stdout

I want my program to log to stdout. However I cannot find a way to do it using std.log && global mutex, since logFn signature does not pass std.Io (for use in std.Io.Mutex.lock to lock stdout):

pub fn logFn(
    comptime message_level: std.log.Level,
    comptime scope: @EnumLiteral(),
    comptime format: []const u8,
    args: anytype,
) void;

I also don’t want to depend on libc for std.c.pthread_mutex_t. Is there any way to implement it without writing spinlock? Please, don’t mention std.debug.lockStderr, or that logging to stdout is a bad practice.

Thank you.

Maybe I can send std.Io as first arg in args var.

You have to use global variable to pass something to logFn. The default log function just uses std.debug.print which uses global debug IO instance fyi, https://codeberg.org/ziglang/zig/src/commit/eb23216dd90ef2e031498c65824858720f78082c/lib/std/log.zig#L96-L109

I came up with this solution:

const std = @import("std");

var stdoutMutex: std.Io.Mutex = .init;

// For locking `std.Io.Mutex`. Expected to be set first thing in
// main using init(io: *const std.Io)` fn before any call to `logFn`
// is received.
var logIo: *const std.Io = undefined;

/// Supply Io for multi-threaded logging.
pub fn init(io: *const std.Io) void {
    logIo = io;
}

pub fn logFn(
    comptime message_level: std.log.Level,
    comptime scope: @EnumLiteral(),
    comptime format: []const u8,
    args: anytype,
) void {
    stdoutMutex.lockUncancelable(logIo.*);
    defer stdoutMutex.unlock(logIo.*);
...

Not very strict, but should be ok.

You might want to store and pass Io as a value, not pointer.