mirror of
https://git.vectorsigma.ru/public/photoview.git
synced 2026-08-03 17:39:10 +00:00
* 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.
42 lines
717 B
Go
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)
|
|
}
|