49 lines
1.1 kB
1
package log
2
3
import (
4
"context"
5
"log/slog"
6
"os"
7
)
8
9
// NewHandler sets up a new slog.Handler with the service name
10
// as an attribute
11
func NewHandler(name string) slog.Handler {
12
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{})
13
14
var attrs []slog.Attr
15
attrs = append(attrs, slog.Attr{Key: "service", Value: slog.StringValue(name)})
16
handler.WithAttrs(attrs)
17
return handler
18
}
19
20
func New(name string) *slog.Logger {
21
return slog.New(NewHandler(name))
22
}
23
24
func NewContext(ctx context.Context, name string) context.Context {
25
return IntoContext(ctx, New(name))
26
}
27
28
type ctxKey struct{}
29
30
// IntoContext adds a logger to a context. Use FromContext to
31
// pull the logger out.
32
func IntoContext(ctx context.Context, l *slog.Logger) context.Context {
33
return context.WithValue(ctx, ctxKey{}, l)
34
}
35
36
// FromContext returns a logger from a context.Context;
37
// if the passed context is nil, we return the default slog
38
// logger.
39
func FromContext(ctx context.Context) *slog.Logger {
40
if ctx != nil {
41
v := ctx.Value(ctxKey{})
42
if v == nil {
43
return slog.Default()
44
}
45
return v.(*slog.Logger)
46
}
47
48
return slog.Default()
49
}
50