logging/logging.go
2017-08-30 13:03:03 +09:00

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
}
}