Generate log scope from an enum

I am new to zig and try to use std.log for a terminal command.
One of my idea is to use a different log scope per subcommand.

const Command = enum {
  cmd1,
  cmd2,

  pub fn logger (self: Command) type {
    return switch(self) {
      .cmd1 => std.log.scoped(.cmd1),
      .cmd2 => std.log.scoped(.cmd2),
    }
  }
};

From the example, I need to generate the scope manually. I attempt to generate it using an inline else and inline for but zig does not allow conversion of enum member to type(enum_liternal).
Is there a better way to do this or suggestion on approach? :pray:

AFAIK enum literals can’t be created programmatically, so you’d have to generate this bit in build.zig

use a wrapper type like this

const std = @import("std");

const E = enum {
    a,
    b,
    c,
};

pub fn main() void {
    const scope = EnumLogger(E){ .e = .b };
    scope.info("hi {}", .{1});
}

fn EnumLogger(comptime T: type) type {
    return struct {
        e: T,

        pub fn info(el: @This(), comptime fmt: []const u8, args: anytype) void {
            std.options.logFn(.info, .default, "({s}) " ++ fmt, .{@tagName(el.e)} ++ args);
        }
    };
}

prints
info: (b) hi 1
it’s literally what std.log.scope does, with some minor changes to work with enums instead of enum literals

2 Likes