logging/logging.go

42 lines
816 B
Go
Raw Normal View History

2017-08-30 04:03:03 +00:00
package logging
import (
"context"
"os"
"path"
2017-08-30 05:00:22 +00:00
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
2017-08-30 04:03:03 +00:00
)
type loggerKeyType int
const loggerKey loggerKeyType = iota
2017-08-30 05:00:22 +00:00
var defaultLogger *zap.Logger
2017-08-30 04:03:03 +00:00
func init() {
2017-08-30 05:00:22 +00:00
l, _ := zap.NewDevelopment()
defaultLogger = l.With(
zap.Int("pid", os.Getpid()),
2017-08-30 04:03:03 +00:00
zap.String("exe", path.Base(os.Args[0])),
)
}
2017-08-30 05:00:22 +00:00
func NewContext(ctx context.Context, logger *zap.Logger, fields ...zapcore.Field) context.Context {
if nil != logger {
return context.WithValue(ctx, loggerKey, logger.With(fields...))
}
2017-08-30 04:03:03 +00:00
return context.WithValue(ctx, loggerKey, WithContext(ctx).With(fields...))
}
2017-08-30 05:00:22 +00:00
func WithContext(ctx context.Context) *zap.Logger {
2017-08-30 04:03:03 +00:00
if ctx == nil {
return defaultLogger
}
2017-08-30 05:00:22 +00:00
if ctxLogger, ok := ctx.Value(loggerKey).(*zap.Logger); ok {
2017-08-30 04:03:03 +00:00
return ctxLogger
}
2017-08-30 05:00:22 +00:00
return defaultLogger
2017-08-30 04:03:03 +00:00
}