zig-glib-log/src/main.zig

70 lines
2.0 KiB
Zig

const std = @import("std");
const testing = std.testing;
/// Returns the log function, which must be present in the root module.
pub fn log(
/// The value returned by @cImport.
/// Must include the "glib.h" or "glib/gmessages.h" header.
c: anytype,
/// The name of the module used for the log output.
comptime module_name: []const u8,
/// The length of the buffer used for the formatted output.
/// This is the maximum length of log messages.
comptime buf_size: usize,
) fn (
comptime std.log.Level,
comptime @TypeOf(.EnumLiteral),
comptime format: []const u8,
anytype,
) void {
return struct {
pub fn log(
comptime level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
const Buf = struct {
pub threadlocal var fmt_buf: [buf_size]u8 = undefined;
};
const g_level = switch (level) {
.err => c.G_LOG_LEVEL_ERROR,
.warn => c.G_LOG_LEVEL_WARNING,
.info => c.G_LOG_LEVEL_INFO,
.debug => c.G_LOG_LEVEL_DEBUG,
};
const s = std.fmt.bufPrintZ(
&Buf.fmt_buf,
format,
args,
) catch return;
var fields = [_]c.GLogField{
c.GLogField{
.key = "GLIB_DOMAIN",
.value = module_name ++ "-" ++ @tagName(scope),
.length = -1,
},
c.GLogField{
.key = "MESSAGE",
.value = @ptrCast(*const anyopaque, s),
.length = -1,
},
};
c.g_log_structured_array(
g_level,
&fields,
fields.len,
);
}
}.log;
}
export fn add(a: i32, b: i32) i32 {
return a + b;
}