logging/logging.go

39 lines
730 B
Go
Raw Normal View History

2017-08-30 04:03:03 +00:00
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
}
}