ing
This commit is contained in:
parent
f529ff9fb5
commit
56fd172eaf
|
@ -1,5 +1,4 @@
|
||||||
package: git.loafle.net/commons_go/logging
|
package: git.loafle.net/commons_go/logging
|
||||||
import:
|
import:
|
||||||
- package: github.com/uber-go/zap
|
|
||||||
- package: go.uber.org/zap
|
- package: go.uber.org/zap
|
||||||
version: v1.5.0
|
version: v1.5.0
|
23
logging.go
23
logging.go
|
@ -5,34 +5,37 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
|
|
||||||
"github.com/uber-go/zap"
|
"go.uber.org/zap"
|
||||||
|
"go.uber.org/zap/zapcore"
|
||||||
)
|
)
|
||||||
|
|
||||||
type loggerKeyType int
|
type loggerKeyType int
|
||||||
|
|
||||||
const loggerKey loggerKeyType = iota
|
const loggerKey loggerKeyType = iota
|
||||||
|
|
||||||
var defaultLogger zap.Logger
|
var defaultLogger *zap.Logger
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
defaultLogger = zap.New(
|
l, _ := zap.NewDevelopment()
|
||||||
zap.NewJSONEncoder(zap.TimeFormatter(TimestampField)),
|
defaultLogger = l.With(
|
||||||
zap.Fields(zap.Int("pid", os.Getpid())),
|
zap.Int("pid", os.Getpid()),
|
||||||
zap.String("exe", path.Base(os.Args[0])),
|
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...))
|
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 {
|
if ctx == nil {
|
||||||
return defaultLogger
|
return defaultLogger
|
||||||
}
|
}
|
||||||
if ctxLogger, ok := ctx.Value(loggerKey).(zap.Logger); ok {
|
if ctxLogger, ok := ctx.Value(loggerKey).(*zap.Logger); ok {
|
||||||
return ctxLogger
|
return ctxLogger
|
||||||
} else {
|
}
|
||||||
return defaultLogger
|
return defaultLogger
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user