Skip to content

Commit

Permalink
Expose logging slog context functions
Browse files Browse the repository at this point in the history
  • Loading branch information
janos committed Mar 23, 2023
1 parent a2957e1 commit ef4ce7d
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func NewDailyReplaceableWriterConstructor(dir, name string) func(flag string) (f
// name.
func NewContextLoggerHandler(h http.Handler, l *slog.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r = r.WithContext(newSlogContext(r.Context(), l))
r = r.WithContext(NewSlogContext(r.Context(), l))
h.ServeHTTP(w, r)
})
}
Expand All @@ -89,20 +89,20 @@ const HandlerKey = "handler"
// HandlerLogger provides a logger from HTTP request with attached name of the
// handler.
func HandlerLogger(r *http.Request, handlerName string) *slog.Logger {
return fromSlogContext(r.Context()).With(HandlerKey, handlerName)
return SlogFromContext(r.Context()).With(HandlerKey, handlerName)
}

type contextKeySlog struct{}

// newSlogContext returns a context that contains the given Logger.
// NewSlogContext returns a context that contains the given Logger.
// Use FromContext to retrieve the Logger.
func newSlogContext(ctx context.Context, l *slog.Logger) context.Context {
func NewSlogContext(ctx context.Context, l *slog.Logger) context.Context {
return context.WithValue(ctx, contextKeySlog{}, l)
}

// fromSlogContext returns the Logger stored in ctx by NewContext, or the default
// SlogFromContext returns the Logger stored in ctx by NewContext, or the default
// Logger if there is none.
func fromSlogContext(ctx context.Context) *slog.Logger {
func SlogFromContext(ctx context.Context) *slog.Logger {
if l, ok := ctx.Value(contextKeySlog{}).(*slog.Logger); ok {
return l
}
Expand Down

0 comments on commit ef4ce7d

Please sign in to comment.