-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog.go
More file actions
63 lines (52 loc) · 1.69 KB
/
log.go
File metadata and controls
63 lines (52 loc) · 1.69 KB
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
package temple
import (
"context"
"log/slog"
)
type ctxKey struct{}
var (
slogCtxKey = ctxKey{}
)
func logger(ctx context.Context) *slog.Logger {
val := ctx.Value(slogCtxKey)
if val == nil {
return slog.New(noopHandler{})
}
logger, ok := val.(*slog.Logger)
if !ok {
return slog.New(noopHandler{})
}
return logger
}
// LoggingContext returns a context.Context with the slog.Logger embedded in it
// in such a way that temple will be able to find it. Passing the returned
// context.Context to temple functions will let temple write its logging output
// to that logger.
func LoggingContext(ctx context.Context, logger *slog.Logger) context.Context {
return context.WithValue(ctx, slogCtxKey, logger)
}
// SetInLogger updates the slog.Logger embedded in the passed context.Context
// to associate the passed keys and values with it. Any log lines temple prints
// using the returned context.Context will include the passed keys and values.
func SetInLogger(ctx context.Context, args ...any) context.Context {
return LoggingContext(ctx, logger(ctx).With(args...))
}
type noopHandler struct{}
// Enabled always returns false for the noopHandler.
func (noopHandler) Enabled(_ context.Context, _ slog.Level) bool {
return false
}
// Handle always returns a nil error and does nothing else for the noopHandler.
func (noopHandler) Handle(_ context.Context, _ slog.Record) error {
return nil
}
// WithAttrs always returns the noopHandler as it was before WithAttrs was
// called.
func (n noopHandler) WithAttrs(_ []slog.Attr) slog.Handler {
return n
}
// WithGroup always returns the noopHandler as it was before WithGroup was
// called.
func (n noopHandler) WithGroup(_ string) slog.Handler {
return n
}