File: logger.go

package info (click to toggle)
golang-github-chainguard-dev-clog 1.7.0-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 424 kB
  • sloc: makefile: 4
file content (204 lines) | stat: -rw-r--r-- 6,298 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package clog

import (
	"context"
	"fmt"
	"log/slog"
	"os"
	"runtime"
	"time"
)

// Logger implements a wrapper around [slog.Logger] that adds formatter functions (e.g. Infof, Errorf)
type Logger struct {
	ctx context.Context
	slog.Logger
}

// DefaultLogger returns a new logger that uses the default [slog.Logger].
func DefaultLogger() *Logger {
	return NewLogger(nil)
}

// NewLogger returns a new logger that wraps the given [slog.Logger] with the default context.
func NewLogger(l *slog.Logger) *Logger {
	return NewLoggerWithContext(context.Background(), l)
}

// NewLoggerWithContext returns a new logger that wraps the given [slog.Logger].
func NewLoggerWithContext(ctx context.Context, l *slog.Logger) *Logger {
	if l == nil {
		l = slog.New(NewHandler(slog.Default().Handler()))
	}
	return &Logger{
		ctx:    ctx,
		Logger: *l,
	}
}

// New returns a new logger that wraps the given [slog.Handler].
func New(h slog.Handler) *Logger {
	return NewWithContext(context.Background(), h)
}

// New returns a new logger that wraps the given [slog.Handler].
func NewWithContext(ctx context.Context, h slog.Handler) *Logger {
	return NewLoggerWithContext(ctx, slog.New(NewHandler(h)))
}

// With calls [Logger.With] on the default logger.
func With(args ...any) *Logger {
	return DefaultLogger().With(args...)
}

// With calls [Logger.With] on the logger.
func (l *Logger) With(args ...any) *Logger {
	return NewLoggerWithContext(l.context(), l.Logger.With(args...))
}

// WithGroup calls [Logger.WithGroup] on the default logger.
func (l *Logger) WithGroup(name string) *Logger {
	return NewLoggerWithContext(l.context(), l.Logger.WithGroup(name))
}

func (l *Logger) context() context.Context {
	if l.ctx == nil {
		return context.Background()
	}
	return l.ctx
}

// Infof logs at LevelInfo with the given format and arguments.
func (l *Logger) Info(format string, args ...any) {
	wrap(l.context(), l, slog.LevelInfo, format, args...)
}

// Infof logs at LevelInfo with the given format and arguments.
func (l *Logger) Infof(format string, args ...any) {
	wrapf(l.context(), l, slog.LevelInfo, format, args...)
}

// InfoContextf logs at LevelInfo with the given context, format and arguments.
func (l *Logger) InfoContextf(ctx context.Context, format string, args ...any) {
	wrapf(ctx, l, slog.LevelInfo, format, args...)
}

// Warn logs at LevelWarn with the given format and arguments.
func (l *Logger) Warn(format string, args ...any) {
	wrap(l.context(), l, slog.LevelWarn, format, args...)
}

// Warnf logs at LevelWarn with the given format and arguments.
func (l *Logger) Warnf(format string, args ...any) {
	wrapf(l.context(), l, slog.LevelWarn, format, args...)
}

// WarnContextf logs at LevelWarn with the given context, format and arguments.
func (l *Logger) WarnContextf(ctx context.Context, format string, args ...any) {
	wrapf(ctx, l, slog.LevelWarn, format, args...)
}

// Error logs at LevelError with the given format and arguments.
func (l *Logger) Error(format string, args ...any) {
	wrap(l.context(), l, slog.LevelError, format, args...)
}

// Errorf logs at LevelError with the given format and arguments.
func (l *Logger) Errorf(format string, args ...any) {
	wrapf(l.context(), l, slog.LevelError, format, args...)
}

// ErrorContextf logs at LevelError with the given context, format and arguments.
func (l *Logger) ErrorContextf(ctx context.Context, format string, args ...any) {
	wrapf(ctx, l, slog.LevelError, format, args...)
}

// Debug logs at LevelDebug with the given format and arguments.
func (l *Logger) Debug(format string, args ...any) {
	wrap(l.context(), l, slog.LevelDebug, format, args...)
}

// Debugf logs at LevelDebug with the given format and arguments.
func (l *Logger) Debugf(format string, args ...any) {
	wrapf(l.context(), l, slog.LevelDebug, format, args...)
}

// DebugContextf logs at LevelDebug with the given context, format and arguments.
func (l *Logger) DebugContextf(ctx context.Context, format string, args ...any) {
	wrapf(ctx, l, slog.LevelDebug, format, args...)
}

// Fatalf logs at LevelError with the given format and arguments, then exits.
func (l *Logger) Fatalf(format string, args ...any) {
	wrapf(l.context(), l, slog.LevelError, format, args...)
	os.Exit(1)
}

// Fatal logs at LevelError with the given message, then exits.
func (l *Logger) Fatal(msg string, args ...any) {
	wrap(l.context(), l, slog.LevelError, msg, args...)
	os.Exit(1)
}

// FatalfContextf logs at LevelError with the given context, format and arguments, then exits.
func (l *Logger) FatalContextf(ctx context.Context, format string, args ...any) {
	wrapf(ctx, l, slog.LevelError, format, args...)
	os.Exit(1)
}

// FatalfContext logs at LevelError with the given context and message, then exits.
func (l *Logger) FatalContext(ctx context.Context, msg string, args ...any) {
	wrap(ctx, l, slog.LevelError, msg, args...)
	os.Exit(1)
}

// Base returns the underlying [slog.Logger].
func (l *Logger) Base() *slog.Logger {
	return &l.Logger
}

// Handler returns the underlying [slog.Handler].
func (l *Logger) Handler() slog.Handler {
	return l.Logger.Handler()
}

func wrap(ctx context.Context, logger *Logger, level slog.Level, msg string, args ...any) {
	if !logger.Handler().Enabled(ctx, level) {
		return
	}

	var pcs [1]uintptr
	runtime.Callers(3, pcs[:]) // skip [Callers, Infof, wrapf]
	r := slog.NewRecord(time.Now(), level, msg, pcs[0])
	r.Add(args...)
	_ = logger.Handler().Handle(ctx, r)
}

// wrapf is like wrap, but uses fmt.Sprintf to format the message.
// NOTE: args are passed to fmt.Sprintf, not as [slog.Attr].
func wrapf(ctx context.Context, logger *Logger, level slog.Level, format string, args ...any) {
	if !logger.Handler().Enabled(ctx, level) {
		return
	}

	var pcs [1]uintptr
	runtime.Callers(3, pcs[:]) // skip [Callers, Infof, wrapf]
	r := slog.NewRecord(time.Now(), level, fmt.Sprintf(format, args...), pcs[0])
	_ = logger.Handler().Handle(ctx, r)
}

type loggerKey struct{}

func WithLogger(ctx context.Context, logger *Logger) context.Context {
	return context.WithValue(ctx, loggerKey{}, logger.Logger)
}

func FromContext(ctx context.Context) *Logger {
	if logger, ok := ctx.Value(loggerKey{}).(slog.Logger); ok {
		return &Logger{
			ctx:    ctx,
			Logger: logger,
		}
	}
	return NewLoggerWithContext(ctx, nil)
}