this repo has no description
1const std = @import("std");
2const zeit = @import("zeit");
3
4const default_logger = Logger{ .prefix = "" };
5
6var isatty: bool = false;
7
8/// Call init if you want to check for a tty. By default, we assume output is not a tty. If it is a
9/// tty, we will use some color
10pub fn init() void {
11 isatty = std.io.getStdErr().isTty();
12}
13
14pub fn err(comptime fmt: []const u8, args: anytype) void {
15 return default_logger.log(.err, fmt, args) catch return;
16}
17
18pub fn warn(comptime fmt: []const u8, args: anytype) void {
19 return default_logger.log(.warn, fmt, args) catch return;
20}
21
22pub fn info(comptime fmt: []const u8, args: anytype) void {
23 return default_logger.log(.info, fmt, args) catch return;
24}
25
26pub fn debug(comptime fmt: []const u8, args: anytype) void {
27 return default_logger.log(.debug, fmt, args) catch return;
28}
29
30pub const TimeFormat = union(enum) {
31 strftime: []const u8,
32 gofmt: []const u8,
33};
34
35pub const Logger = struct {
36 prefix: []const u8,
37
38 fn log(self: Logger, level: std.log.Level, comptime fmt: []const u8, args: anytype) !void {
39 const stderr = std.io.getStdErr().writer();
40 var bw = std.io.bufferedWriter(stderr);
41 const writer = bw.writer();
42
43 if (isatty) try writer.writeAll("\x1b[2m");
44 const now = (zeit.instant(.{}) catch unreachable).time();
45 try writer.print(
46 "{d}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}Z",
47 .{
48 now.year,
49 @intFromEnum(now.month),
50 now.day,
51 now.hour,
52 now.minute,
53 now.second,
54 now.millisecond,
55 },
56 );
57 if (isatty) try writer.writeAll("\x1b[m");
58
59 const level_txt: []const u8 = if (isatty)
60 switch (level) {
61 .err => "\x1b[31mERR\x1b[m",
62 .info => "\x1b[34mINF\x1b[m",
63 .warn => "\x1b[33mWRN\x1b[m",
64 .debug => "\x1b[35mDBG\x1b[m",
65 }
66 else switch (level) {
67 .err => "ERR",
68 .info => "INF",
69 .warn => "WRN",
70 .debug => "DBG",
71 };
72
73 std.debug.lockStdErr();
74 defer std.debug.unlockStdErr();
75 nosuspend {
76 writer.print(" {s} {s}", .{ level_txt, self.prefix }) catch return;
77 writer.print(fmt ++ "\n", args) catch return;
78 bw.flush() catch return;
79 }
80 }
81
82 pub fn err(self: Logger, comptime fmt: []const u8, args: anytype) void {
83 return self.log(.err, fmt, args) catch return;
84 }
85
86 pub fn warn(self: Logger, comptime fmt: []const u8, args: anytype) void {
87 return self.log(.warn, fmt, args) catch return;
88 }
89
90 pub fn info(self: Logger, comptime fmt: []const u8, args: anytype) void {
91 return self.log(.info, fmt, args) catch return;
92 }
93
94 pub fn debug(self: Logger, comptime fmt: []const u8, args: anytype) void {
95 return self.log(.debug, fmt, args) catch return;
96 }
97};