add(timestamp): timestamp build configuration option to add timestamps before log messages
All checks were successful
Run Tests / test (push) Successful in 9m33s
Run Tests / lint (push) Successful in 9m43s

This commit is contained in:
2024-08-28 22:25:06 +02:00
parent 510b3ddfcf
commit eb7e78697c
3 changed files with 32 additions and 20 deletions

View File

@@ -1,13 +1,7 @@
const build_options = @import("build_options");
const c_time = if (build_options.timestamp) @cImport(@cInclude("time.h")) else null;
const std = @import("std");
// pub fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void
// TODO: provide comptime helper function to add format function for user types:
// - pretty printing
// - compact printing
// - show types of struct members
// Maybe the corresponding configurations for the `format` function could also
// be effected by build time configurations
pub const std_options: std.Options = .{
.logFn = logFn,
};
@@ -20,15 +14,9 @@ fn logFn(
args: anytype,
) void {
// TODO: provide build time configuration to allow tweaking corresponding output
// - add timestamp to all log messages
// - change output file for writing messages to (default `stderr`)
// TODO: improve formatting output, such that the resulting log has a good feel
// - should there be indenting?
// - should there be spacing?
// - should the messages be aligned (left, center, right)?
const level_txt = comptime message_level.asText();
const prefix = if (scope == .default) ":\t" else "(" ++ @tagName(scope) ++ "):\t";
const prefix = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
const stderr = std.io.getStdErr().writer();
var bw = std.io.bufferedWriter(stderr);
const writer = bw.writer();
@@ -36,6 +24,14 @@ fn logFn(
std.debug.lockStdErr();
defer std.debug.unlockStdErr();
nosuspend {
if (build_options.timestamp) {
const curtime = c_time.time(null);
const tm = c_time.localtime(&curtime);
var buf: [32]u8 = undefined;
_ = c_time.strftime(@ptrCast(&buf), 32, "%F %R", tm);
writer.print("[{s}] ", .{buf}) catch return;
}
writer.print(level_txt ++ prefix ++ format ++ "\n", args) catch return;
bw.flush() catch return;
}