generated from sv-tools/go-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
92 lines (75 loc) · 2.49 KB
/
log.go
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
package main
import (
"context"
"fmt"
"net/http"
"os"
"time"
"github.com/go-chi/chi/v5/middleware"
"golang.org/x/exp/slog"
)
func LogHandler() *slog.JSONHandler {
// Setup a JSON handler for the new log/slog library
return slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
// Remove default time slog.Attr, we create our own later
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
})
}
// StructuredLogger is a simple, but powerful implementation of a custom structured
// logger backed on log/slog. I encourage users to copy it, adapt it and make it their
// own. Also take a look at https://github.com/go-chi/httplog for a dedicated pkg based
// on this work, designed for context-based http routers.
func NewStructuredLogger(handler slog.Handler) func(next http.Handler) http.Handler {
return middleware.RequestLogger(&StructuredLogger{Logger: handler})
}
type StructuredLogger struct {
Logger slog.Handler
}
func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
ctx := r.Context()
var logFields []slog.Attr
logFields = append(logFields, slog.String("ts", time.Now().UTC().Format(time.RFC1123)))
if reqID := middleware.GetReqID(r.Context()); reqID != "" {
logFields = append(logFields, slog.String("req_id", reqID))
}
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
handler := l.Logger.WithAttrs(append(logFields,
slog.String("http_scheme", scheme),
slog.String("http_proto", r.Proto),
slog.String("http_method", r.Method),
slog.String("remote_addr", r.RemoteAddr),
slog.String("user_agent", r.UserAgent()),
slog.String("uri", fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)),
))
entry := StructuredLoggerEntry{
ctx: ctx,
Logger: slog.New(handler),
}
entry.Logger.LogAttrs(ctx, slog.LevelInfo, "request started")
return &entry
}
type StructuredLoggerEntry struct {
ctx context.Context
Logger *slog.Logger
}
func (l *StructuredLoggerEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) {
l.Logger.LogAttrs(l.ctx, slog.LevelInfo, "request complete",
slog.Int("resp_status", status),
slog.Int("resp_byte_length", bytes),
slog.Float64("resp_elapsed_ms", float64(elapsed.Nanoseconds())/1000000.0),
)
}
func (l *StructuredLoggerEntry) Panic(v any, stack []byte) {
l.Logger.LogAttrs(l.ctx, slog.LevelInfo, "",
slog.String("stack", string(stack)),
slog.String("panic", fmt.Sprintf("%+v", v)),
)
}