Log strategy for script during zig build

Hello,

I was wondering if there is a way to log stuff in a zig build script. To be clearer, consider something along these lines :

const run_polytransmutate = b.addRunArtifact(polytransmutate_step);
run_polytransmutate.addFileArg(normal_source, .{});
const wonder_file = run_polytransmutate.captureStdOut(.{});

Now, obviously a poly transmutation is non trivial, and there is a bunch of edge cases that do not warrant for the script to panic, or to systematically write to stderr which will always appear. But maybe I still want to emit some info level log that I could toggle on/off if I run into issues later on.

My first instinct was : Can’t I just make it so that zig build --verbose reveal the logs of my polytransmutation tool ? But it’s a child process know nothing about the --verbose flag.

Anybody ran in similar situation ? Tips ?

I’m not sure I got your use case correctly, but you can log and print in build.zig using the usual std.log functions and std.debug.print.

std.log functions allow toggling of log level through std.Options.

Edit:
I tried std.log right now and it does print some trailing chars that have nothing to do with the message.

@compileLog straight up gives a compile error.

Maybe printing directly to stderr, or logging to a separate file.

Thanks for answering !

I didn’t meant from within the build.zig. The main build script compiles a helper script :

const polytransmutate_step = b.addExecutable( 
    ...
    b.path("polytransmutate.zig");
    ...
)

And the helper script itself, polytransmutate.zig:

pub fn main(init: std.process.Init) !void {
    ...
    const args = try init.minimal.args.toSlice(arena);
    const input_file = args[1]; 
    // Now transform file and output result to stdout

    // Ooops, I hit a hedge case...
    // But it's probably fine ...
    // Mmmh, can I log something that appears only in --verbose maybe
} 

Then you can use @compileLog, adding an option in the build.zig to toggle it, e.g.

// Build.zig
const logs = b.option(
        bool,
        "logs",
        "Enables comptime logs of intermediate build steps",
    ) orelse false;
const options = b.addOptions();
options.addOption(bool, "logs", logs);
polytransmute_step.root_module.addOptions("build_options", options);

// polytransmutate.zig
const opt = @import("build_options");
const some_comptime_value = 8;
if (opt.logs) @compileLog("Logging something " ++ some_comptime_value);

@compileLog expects comptime values passed to it, and will be executed at compile time.

If you also run polytransmutate.zig in your build.zig as part of the default build step (which I assume you do, since you said it’s an helper script) and you want to log at runtime during the execution by build.zig you can try with std.log, but I’m not sure if that works.

I don’t think that’s possible atm.

Best workaround I found is to write to a log file.
It would be cool if zig build had a flag to save the stdout of subprocesses