This commit is contained in:
crusader 2017-08-30 14:00:22 +09:00
parent f529ff9fb5
commit 56fd172eaf
2 changed files with 13 additions and 11 deletions

View File

@ -1,5 +1,4 @@
package: git.loafle.net/commons_go/logging
import:
- package: github.com/uber-go/zap
- package: go.uber.org/zap
version: v1.5.0

View File

@ -5,34 +5,37 @@ import (
"os"
"path"
"github.com/uber-go/zap"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type loggerKeyType int
const loggerKey loggerKeyType = iota
var defaultLogger zap.Logger
var defaultLogger *zap.Logger
func init() {
defaultLogger = zap.New(
zap.NewJSONEncoder(zap.TimeFormatter(TimestampField)),
zap.Fields(zap.Int("pid", os.Getpid())),
l, _ := zap.NewDevelopment()
defaultLogger = l.With(
zap.Int("pid", os.Getpid()),
zap.String("exe", path.Base(os.Args[0])),
)
}
func NewContext(ctx context.Context, fields ...zap.Field) context.Context {
func NewContext(ctx context.Context, logger *zap.Logger, fields ...zapcore.Field) context.Context {
if nil != logger {
return context.WithValue(ctx, loggerKey, logger.With(fields...))
}
return context.WithValue(ctx, loggerKey, WithContext(ctx).With(fields...))
}
func WithContext(ctx context.Context) zap.Logger {
func WithContext(ctx context.Context) *zap.Logger {
if ctx == nil {
return defaultLogger
}
if ctxLogger, ok := ctx.Value(loggerKey).(zap.Logger); ok {
if ctxLogger, ok := ctx.Value(loggerKey).(*zap.Logger); ok {
return ctxLogger
} else {
}
return defaultLogger
}
}