Debian Codegraph @

debian/rust-vendor/codspeed/instrument-hooks/src/logger.zig

raw
1 const std = @import("std");
2
3 // We have to use c_char here, otherwise we redeclare it and cast u8 to char which results in
4 // additional warnings (-Wbuiltin-declaration-mismatch and -Wpointer-sign).
5 extern "c" fn printf(format: [*c]const c_char, ...) c_int;
6
7 pub const LogLevel = enum(u8) {
8 Debug = 0,
9 Info = 1,
10 Warn = 2,
11 Error = 3,
12 };
13
14 var max_level: LogLevel = LogLevel.Debug;
15
16 fn logWithPrefix(comptime level: LogLevel, comptime fmt: []const u8, args: anytype) void {
17 if (@intFromEnum(level) < @intFromEnum(max_level)) {
18 return;
19 }
20
21 // Format the message using Zig's formatting
22 var buffer: [512]u8 = undefined;
23 const prefix_fmt = comptime switch (level) {
24 .Debug => "[DEBUG] " ++ fmt,
25 .Info => "[INFO] " ++ fmt,
26 .Warn => "[WARN] " ++ fmt,
27 .Error => "[ERROR] " ++ fmt,
28 };
29
30 const msg = std.fmt.bufPrint(buffer[0 .. buffer.len - 1], prefix_fmt, args) catch {
31 _ = printf(@as([*c]const c_char, @ptrCast("[ERROR] logger formatting failed\n")));
32 return;
33 };
34
35 // Null-terminate for printf
36 buffer[msg.len] = 0;
37
38 // Print the formatted message (printf with only format string, no args)
39 _ = printf(@as([*c]const c_char, @ptrCast(msg.ptr)));
40 }
41
42 pub fn debug(comptime fmt: []const u8, args: anytype) void {
43 logWithPrefix(.Debug, fmt, args);
44 }
45
46 pub fn info(comptime fmt: []const u8, args: anytype) void {
47 logWithPrefix(.Info, fmt, args);
48 }
49
50 pub fn warn(comptime fmt: []const u8, args: anytype) void {
51 logWithPrefix(.Warn, fmt, args);
52 }
53
54 pub fn err(comptime fmt: []const u8, args: anytype) void {
55 logWithPrefix(.Error, fmt, args);
56 }