From 642f5df0abbcfda47df94ba657b24a913d6903d4 Mon Sep 17 00:00:00 2001 From: Jonathan Marler Date: Thu, 24 Jun 2021 04:11:28 -0600 Subject: [PATCH] Expose default std.log implementation This allows root.log implementations to capture log messages, process them, and forward them to the default implementation if desired. --- lib/std/log.zig | 51 +++++++++++++++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/lib/std/log.zig b/lib/std/log.zig index a20648626e..5cff132e44 100644 --- a/lib/std/log.zig +++ b/lib/std/log.zig @@ -145,30 +145,43 @@ fn log( if (@typeInfo(@TypeOf(root.log)) != .Fn) @compileError("Expected root.log to be a function"); root.log(message_level, scope, format, args); - } else if (std.Target.current.os.tag == .freestanding) { - // On freestanding one must provide a log function; we do not have - // any I/O configured. - return; } else { - const level_txt = switch (message_level) { - .emerg => "emergency", - .alert => "alert", - .crit => "critical", - .err => "error", - .warn => "warning", - .notice => "notice", - .info => "info", - .debug => "debug", - }; - const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; - const stderr = std.io.getStdErr().writer(); - const held = std.debug.getStderrMutex().acquire(); - defer held.release(); - nosuspend stderr.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return; + defaultLog(message_level, scope, format, args); } } } +/// The default implementation for root.log. root.log may forward log messages +/// to this function. +pub fn defaultLog( + comptime message_level: Level, + comptime scope: @Type(.EnumLiteral), + comptime format: []const u8, + args: anytype, +) void { + if (std.Target.current.os.tag == .freestanding) { + // On freestanding one must provide a log function; we do not have + // any I/O configured. + return; + } + + const level_txt = switch (message_level) { + .emerg => "emergency", + .alert => "alert", + .crit => "critical", + .err => "error", + .warn => "warning", + .notice => "notice", + .info => "info", + .debug => "debug", + }; + const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; + const stderr = std.io.getStdErr().writer(); + const held = std.debug.getStderrMutex().acquire(); + defer held.release(); + nosuspend stderr.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return; +} + /// Returns a scoped logging namespace that logs all messages using the scope /// provided here. pub fn scoped(comptime scope: @Type(.EnumLiteral)) type {