精简后的项目:仅保留 api/ui 源码、文档、构建依赖
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user