Is this idiomatic

I was learning WASM with Zig and needed a logger function, I made one, but I’m still wondering if this is idiomatic or not:

const std      = @import(“std”);
const myLogger = @import(“../main.zig”).logString;

pub const Logger = struct{
buf: [256]u8,
fs:  [*c]const u8, // fs → formatted string

pub fn log(self: *Logger, comptime logString: []const u8, value: anytype) void {
    const formatted_string = std.fmt.bufPrintZ(&self.buf, logString, .{value}) catch |err| {
        myLogger("Log Broken");
        @panic(@errorName(err));
    };
    myLogger(formatted_string);
}

};

std.log there is a default implementation, but it can be overriden (see linked docs for how).
It has the benefit that libraries can integrate with your custom log function, which is not the case for your current implementation.

1 Like

One thing to note about using std.log in wasm and embedded contexts is that it brings in a lot of Io.Writer.print, which can bloat binary size. It’s usually the right tool, but if size is critical, then it’s something to at least be aware of.

That is only the case if the log function uses writer.print (the default does), but yes it is compatible with it.

I will point out that their custom log API uses and is compatible with writer.print already, so this is likely not a problem, at least not yet.

2 Likes

Alright, I’ll try overriding the std.log function. Thanks a lot!