39 lines
730 B
Go
39 lines
730 B
Go
|
package logging
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"os"
|
||
|
"path"
|
||
|
|
||
|
"github.com/uber-go/zap"
|
||
|
)
|
||
|
|
||
|
type loggerKeyType int
|
||
|
|
||
|
const loggerKey loggerKeyType = iota
|
||
|
|
||
|
var defaultLogger zap.Logger
|
||
|
|
||
|
func init() {
|
||
|
defaultLogger = zap.New(
|
||
|
zap.NewJSONEncoder(zap.TimeFormatter(TimestampField)),
|
||
|
zap.Fields(zap.Int("pid", os.Getpid())),
|
||
|
zap.String("exe", path.Base(os.Args[0])),
|
||
|
)
|
||
|
}
|
||
|
|
||
|
func NewContext(ctx context.Context, fields ...zap.Field) context.Context {
|
||
|
return context.WithValue(ctx, loggerKey, WithContext(ctx).With(fields...))
|
||
|
}
|
||
|
|
||
|
func WithContext(ctx context.Context) zap.Logger {
|
||
|
if ctx == nil {
|
||
|
return defaultLogger
|
||
|
}
|
||
|
if ctxLogger, ok := ctx.Value(loggerKey).(zap.Logger); ok {
|
||
|
return ctxLogger
|
||
|
} else {
|
||
|
return defaultLogger
|
||
|
}
|
||
|
}
|