Files
photoview/api/log/context.go
Googol Lee 0da8bef69e Update log for passing attrs with context. (#1216)
* Update log for passing attrs with context.

* Check type-casting

* add tests.

* Use t.Cleanup() to restore the global value.

* Fix error.

* Update tests.

* Add comments.

* Remove cover.cov

* Update doc.

* Update git ignore.
2025-06-07 17:11:50 +02:00

42 lines
717 B
Go

package log
import (
"context"
"log/slog"
)
var defaultLogger *slog.Logger
func init() {
defaultLogger = slog.Default()
}
type loggerKeyType string
const loggerKey loggerKeyType = "logger"
func getLogger(ctx context.Context) *slog.Logger {
if ctx == nil {
return defaultLogger
}
logger := ctx.Value(loggerKey)
if logger == nil {
return defaultLogger
}
ret, ok := logger.(*slog.Logger)
if !ok {
return defaultLogger
}
return ret
}
// WithAttrs creates a new context containing a new logger with [args] as logging attributes.
func WithAttrs(ctx context.Context, args ...any) context.Context {
old := getLogger(ctx)
new := old.With(args...)
return context.WithValue(ctx, loggerKey, new)
}