Files
kopia/repo/logging/ctx.go
Jarek Kowalski 80423cf5f6 feat(server): fixed server logging file & console (#3262)
Previously some logs from a running server were only kept in memory
(including storage activity logs) which was confusing to many folks.

This changes the behavior so that logs are sent to their regular
(console/file) file locations in addition to the UI tasks.

Old behavior can be restored by adding `--no-persistent-logs` to
server.
2023-09-02 18:10:18 -07:00

55 lines
1.3 KiB
Go

package logging
import (
"context"
"sync"
)
type contextKey string
const loggerCacheKey contextKey = "logger"
type loggerCache struct {
createLoggerForModule LoggerFactory
loggers sync.Map
}
func (s *loggerCache) getLogger(module string) Logger {
v, ok := s.loggers.Load(module)
if !ok {
v, _ = s.loggers.LoadOrStore(module, s.createLoggerForModule(module))
}
return v.(Logger) //nolint:forcetypeassert
}
// WithLogger returns a derived context with associated logger.
func WithLogger(ctx context.Context, l LoggerFactory) context.Context {
if l == nil {
l = getNullLogger
}
return context.WithValue(ctx, loggerCacheKey, &loggerCache{
createLoggerForModule: l,
})
}
// WithAdditionalLogger returns a context where all logging is emitted the original output plus the provided logger factory.
func WithAdditionalLogger(ctx context.Context, fact LoggerFactory) context.Context {
originalLogFactory := loggerFactoryFromContext(ctx)
return WithLogger(ctx, func(module string) Logger {
return Broadcast(originalLogFactory(module), fact(module))
})
}
// loggerFactoryFromContext returns a LoggerFactory associated with current context.
func loggerFactoryFromContext(ctx context.Context) LoggerFactory {
v := ctx.Value(loggerCacheKey)
if v == nil {
return getNullLogger
}
return v.(*loggerCache).getLogger //nolint:forcetypeassert
}