Debian Codegraph @

logger.go

raw symbols SCIP
1 package clog
2
3 import (
4 "context"
5 "fmt"
6 "log/slog"
7 "os"
8 "runtime"
9 "time"
10 )
11
12 // Logger implements a wrapper around [slog.Logger] that adds formatter functions (e.g. Infof, Errorf)
13 type Logger struct {
14 ctx context.Context
15 slog.Logger
16 }
17
18 // DefaultLogger returns a new logger that uses the default [slog.Logger].
19 func DefaultLogger() *Logger {
20 return NewLogger(nil)
21 }
22
23 // NewLogger returns a new logger that wraps the given [slog.Logger] with the default context.
24 func NewLogger(l *slog.Logger) *Logger {
25 return NewLoggerWithContext(context.Background(), l)
26 }
27
28 // NewLoggerWithContext returns a new logger that wraps the given [slog.Logger].
29 func NewLoggerWithContext(ctx context.Context, l *slog.Logger) *Logger {
30 if l == nil {
31 l = slog.New(NewHandler(slog.Default().Handler()))
32 }
33 return &Logger{
34 ctx: ctx,
35 Logger: *l,
36 }
37 }
38
39 // New returns a new logger that wraps the given [slog.Handler].
40 func New(h slog.Handler) *Logger {
41 return NewWithContext(context.Background(), h)
42 }
43
44 // NewWithContext returns a new logger that wraps the given [slog.Handler] using the given context.
45 func NewWithContext(ctx context.Context, h slog.Handler) *Logger {
46 return NewLoggerWithContext(ctx, slog.New(NewHandler(h)))
47 }
48
49 // With calls [Logger.With] on the default logger.
50 func With(args ...any) *Logger {
51 return DefaultLogger().With(args...)
52 }
53
54 // With calls [Logger.With] on the logger.
55 func (l *Logger) With(args ...any) *Logger {
56 return NewLoggerWithContext(l.context(), l.Logger.With(args...))
57 }
58
59 // WithGroup calls [Logger.WithGroup] on the default logger.
60 func (l *Logger) WithGroup(name string) *Logger {
61 return NewLoggerWithContext(l.context(), l.Logger.WithGroup(name))
62 }
63
64 func (l *Logger) context() context.Context {
65 if l.ctx == nil {
66 return context.Background()
67 }
68 return l.ctx
69 }
70
71 // Info logs at LevelInfo with the given message and treats the args as key/value pairs to form log message attributes.
72 func (l *Logger) Info(msg string, args ...any) {
73 wrap(l.context(), l, slog.LevelInfo, msg, args...)
74 }
75
76 // Infof logs at LevelInfo with the given format and arguments.
77 func (l *Logger) Infof(format string, args ...any) {
78 wrapf(l.context(), l, slog.LevelInfo, format, args...)
79 }
80
81 // InfoContextf logs at LevelInfo with the given context, format, and arguments.
82 func (l *Logger) InfoContextf(ctx context.Context, format string, args ...any) {
83 wrapf(ctx, l, slog.LevelInfo, format, args...)
84 }
85
86 // Warn logs at LevelWarn with the given message and treats the args as key/value pairs to form log message attributes.
87 func (l *Logger) Warn(msg string, args ...any) {
88 wrap(l.context(), l, slog.LevelWarn, msg, args...)
89 }
90
91 // Warnf logs at LevelWarn with the given format and arguments.
92 func (l *Logger) Warnf(format string, args ...any) {
93 wrapf(l.context(), l, slog.LevelWarn, format, args...)
94 }
95
96 // WarnContextf logs at LevelWarn with the given context, format and arguments.
97 func (l *Logger) WarnContextf(ctx context.Context, format string, args ...any) {
98 wrapf(ctx, l, slog.LevelWarn, format, args...)
99 }
100
101 // Error logs at LevelError with the given message and treats the args as key/value pairs to form log message attributes.
102 func (l *Logger) Error(msg string, args ...any) {
103 wrap(l.context(), l, slog.LevelError, msg, args...)
104 }
105
106 // Errorf logs at LevelError with the given format and arguments.
107 func (l *Logger) Errorf(format string, args ...any) {
108 wrapf(l.context(), l, slog.LevelError, format, args...)
109 }
110
111 // ErrorContextf logs at LevelError with the given context, format and arguments.
112 func (l *Logger) ErrorContextf(ctx context.Context, format string, args ...any) {
113 wrapf(ctx, l, slog.LevelError, format, args...)
114 }
115
116 // Debug logs at LevelDebug with the given message and treats the args as key/value pairs to form log message attributes.
117 func (l *Logger) Debug(msg string, args ...any) {
118 wrap(l.context(), l, slog.LevelDebug, msg, args...)
119 }
120
121 // Debugf logs at LevelDebug with the given format and arguments.
122 func (l *Logger) Debugf(format string, args ...any) {
123 wrapf(l.context(), l, slog.LevelDebug, format, args...)
124 }
125
126 // DebugContextf logs at LevelDebug with the given context, format and arguments.
127 func (l *Logger) DebugContextf(ctx context.Context, format string, args ...any) {
128 wrapf(ctx, l, slog.LevelDebug, format, args...)
129 }
130
131 // Fatal logs at LevelError with the given message, then exits.
132 func (l *Logger) Fatal(msg string, args ...any) {
133 wrap(l.context(), l, slog.LevelError, msg, args...)
134 os.Exit(1)
135 }
136
137 // Fatalf logs at LevelError with the given format and arguments, then exits.
138 func (l *Logger) Fatalf(format string, args ...any) {
139 wrapf(l.context(), l, slog.LevelError, format, args...)
140 os.Exit(1)
141 }
142
143 // FatalContextf logs at LevelError with the given context, format and arguments, then exits.
144 func (l *Logger) FatalContextf(ctx context.Context, format string, args ...any) {
145 wrapf(ctx, l, slog.LevelError, format, args...)
146 os.Exit(1)
147 }
148
149 // FatalContext logs at LevelError with the given context and message, then exits.
150 func (l *Logger) FatalContext(ctx context.Context, msg string, args ...any) {
151 wrap(ctx, l, slog.LevelError, msg, args...)
152 os.Exit(1)
153 }
154
155 // Base returns the underlying [slog.Logger].
156 func (l *Logger) Base() *slog.Logger {
157 return &l.Logger
158 }
159
160 // Handler returns the underlying [slog.Handler].
161 func (l *Logger) Handler() slog.Handler {
162 return l.Logger.Handler()
163 }
164
165 func wrap(ctx context.Context, logger *Logger, level slog.Level, msg string, args ...any) {
166 if !logger.Handler().Enabled(ctx, level) {
167 return
168 }
169
170 var pcs [1]uintptr
171 runtime.Callers(3, pcs[:]) // skip [Callers, Infof, wrapf]
172 r := slog.NewRecord(time.Now(), level, msg, pcs[0])
173 r.Add(args...)
174 _ = logger.Handler().Handle(ctx, r)
175 }
176
177 // wrapf is like wrap, but uses fmt.Sprintf to format the message.
178 // NOTE: args are passed to fmt.Sprintf, not as [slog.Attr].
179 func wrapf(ctx context.Context, logger *Logger, level slog.Level, format string, args ...any) {
180 if !logger.Handler().Enabled(ctx, level) {
181 return
182 }
183
184 var pcs [1]uintptr
185 runtime.Callers(3, pcs[:]) // skip [Callers, Infof, wrapf]
186 r := slog.NewRecord(time.Now(), level, fmt.Sprintf(format, args...), pcs[0])
187 _ = logger.Handler().Handle(ctx, r)
188 }
189
190 type loggerKey struct{}
191
192 func WithLogger(ctx context.Context, logger *Logger) context.Context {
193 return context.WithValue(ctx, loggerKey{}, logger.Logger)
194 }
195
196 func FromContext(ctx context.Context) *Logger {
197 if logger, ok := ctx.Value(loggerKey{}).(slog.Logger); ok {
198 return &Logger{
199 ctx: ctx,
200 Logger: logger,
201 }
202 }
203 return NewLoggerWithContext(ctx, nil)
204 }