feat(platform): tag requests, logs and api errors with a request id
A well-formed X-Request-ID from a proxy is kept, otherwise a UUIDv7 is generated. The ID is echoed in the response header, added to every log record written with the request context and returned in API error bodies. Closes #44 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
b6843330a8
commit
c485d1a96f
6 files changed
+191
-12
No files matched your search
@@ -1,19 +1,49 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
)
|
||||
|
||||
// NewLogger returns a JSON logger tagged with component and the release
|
||||
// version, and the level variable controlling it. The level can be changed
|
||||
// once configuration is loaded; the logger is needed before that to report
|
||||
// configuration errors.
|
||||
//
|
||||
// Records logged with a request context carry its request_id, so handlers
|
||||
// should prefer the *Context logging methods.
|
||||
func NewLogger(component string) (*slog.Logger, *slog.LevelVar) {
|
||||
return newLogger(os.Stderr, component)
|
||||
}
|
||||
|
||||
func newLogger(w io.Writer, component string) (*slog.Logger, *slog.LevelVar) {
|
||||
level := new(slog.LevelVar)
|
||||
l := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: level})).
|
||||
With("component", component, "app_version", buildinfo.Version)
|
||||
return l, level
|
||||
h := contextHandler{slog.NewJSONHandler(w, &slog.HandlerOptions{Level: level})}
|
||||
return slog.New(h).With("component", component, "app_version", buildinfo.Version), level
|
||||
}
|
||||
|
||||
// contextHandler adds attributes carried in the context to each record.
|
||||
type contextHandler struct{ slog.Handler }
|
||||
|
||||
// Handle implements slog.Handler.
|
||||
func (h contextHandler) Handle(ctx context.Context, r slog.Record) error {
|
||||
if id := requestid.FromContext(ctx); id != "" {
|
||||
r.AddAttrs(slog.String("request_id", id))
|
||||
}
|
||||
return h.Handler.Handle(ctx, r)
|
||||
}
|
||||
|
||||
// WithAttrs keeps the wrapper so derived loggers still add the request ID.
|
||||
func (h contextHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return contextHandler{h.Handler.WithAttrs(attrs)}
|
||||
}
|
||||
|
||||
// WithGroup keeps the wrapper so derived loggers still add the request ID.
|
||||
func (h contextHandler) WithGroup(name string) slog.Handler {
|
||||
return contextHandler{h.Handler.WithGroup(name)}
|
||||
}
|
||||
Reference in new issue
Block a user