add field

master v0.0.6
ehlxr 2020-12-31 16:21:31 +08:00
parent 63ba3dd7ab
commit ac33bdc69f
5 changed files with 64 additions and 53 deletions

View File

@ -35,15 +35,15 @@ const (
White White
) )
func (lc *logConfig) initColor() { func (config *logConfig) initColor() {
for level, color := range _levelToColor { for level, color := range _levelToColor {
lcs := level.String() lcs := level.String()
if lc.EnableCapitalLevel { if config.EnableCapitalLevel {
lcs = level.CapitalString() lcs = level.CapitalString()
} }
if lc.EnableLevelTruncation { if config.EnableLevelTruncation {
lcs = lcs[:4] lcs = lcs[:4]
} }
_levelToColorStrings[level] = color.Add(lcs) _levelToColorStrings[level] = color.Add(lcs)

89
log.go
View File

@ -43,22 +43,23 @@ type logConfig struct {
EnableCapitalLevel bool EnableCapitalLevel bool
atomicLevel zap.AtomicLevel atomicLevel zap.AtomicLevel
Name string Name string
Fields []zap.Field
*lumberjack.Logger *lumberjack.Logger
} }
func init() { func init() {
lc := &logConfig{ config := &logConfig{
Logger: &lumberjack.Logger{ Logger: &lumberjack.Logger{
LocalTime: true, LocalTime: true,
}, },
} }
logger = lc.newLogger().Sugar() logger = config.newLogger().Sugar()
} }
func (lc *logConfig) Init() { func (config *logConfig) Init() {
logger = lc.newLogger().Sugar() logger = config.newLogger().Sugar()
} }
func NewLogConfig() *logConfig { func NewLogConfig() *logConfig {
@ -84,54 +85,54 @@ func NewLogConfig() *logConfig {
} }
} }
func (lc *logConfig) newLogger() *zap.Logger { func (config *logConfig) newLogger() *zap.Logger {
if lc.CrashLogFilename != "" { if config.CrashLogFilename != "" {
writeCrashLog(lc.CrashLogFilename) writeCrashLog(config.CrashLogFilename)
} }
lc.atomicLevel = zap.NewAtomicLevelAt(lc.Level) config.atomicLevel = zap.NewAtomicLevelAt(config.Level)
lc.initColor() config.initColor()
cores := []zapcore.Core{ cores := []zapcore.Core{
zapcore.NewCore( zapcore.NewCore(
encoder.NewTextEncoder(lc.encoderConfig()), encoder.NewTextEncoder(config.encoderConfig()),
zapcore.Lock(os.Stdout), zapcore.Lock(os.Stdout),
lc.atomicLevel, config.atomicLevel,
)} )}
if lc.Filename != "" { if config.Filename != "" {
cores = append(cores, lc.fileCore()) cores = append(cores, config.fileCore())
} }
if lc.ErrorLogFilename != "" { if config.ErrorLogFilename != "" {
cores = append(cores, lc.errorFileCore()) cores = append(cores, config.errorFileCore())
} }
core := zapcore.NewTee(cores...) core := zapcore.NewTee(cores...)
var options []zap.Option var options []zap.Option
if lc.EnableLineNumber { if config.EnableLineNumber {
options = append(options, zap.AddCaller(), zap.AddCallerSkip(1)) options = append(options, zap.AddCaller(), zap.AddCallerSkip(1))
} }
if lc.EnableErrorStacktrace { if config.EnableErrorStacktrace {
options = append(options, zap.AddStacktrace(zapcore.ErrorLevel)) options = append(options, zap.AddStacktrace(zapcore.ErrorLevel))
} }
zapLog := zap.New(core, options...) zapLog := zap.New(core, options...)
if lc.Name != "" { if config.Name != "" {
zapLog = zapLog.Named(fmt.Sprintf("[%s]", lc.Name)) zapLog = zapLog.Named(fmt.Sprintf("[%s]", config.Name))
} }
return zapLog return zapLog.With(config.Fields...)
} }
func (lc *logConfig) encoderConfig() zapcore.EncoderConfig { func (config *logConfig) encoderConfig() zapcore.EncoderConfig {
el := lc.encodeLevel el := config.encodeLevel
if lc.EnableColors { if config.EnableColors {
el = lc.encodeColorLevel el = config.encodeColorLevel
} }
return zapcore.EncoderConfig{ return zapcore.EncoderConfig{
@ -145,8 +146,8 @@ func (lc *logConfig) encoderConfig() zapcore.EncoderConfig {
EncodeLevel: el, EncodeLevel: el,
EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
tf := time.RFC3339 tf := time.RFC3339
if lc.TimestampFormat != "" { if config.TimestampFormat != "" {
tf = lc.TimestampFormat tf = config.TimestampFormat
} }
enc.AppendString(t.Format(fmt.Sprintf("[%s]", tf))) enc.AppendString(t.Format(fmt.Sprintf("[%s]", tf)))
}, },
@ -157,40 +158,40 @@ func (lc *logConfig) encoderConfig() zapcore.EncoderConfig {
} }
} }
func (lc *logConfig) fileCore() zapcore.Core { func (config *logConfig) fileCore() zapcore.Core {
return zapcore.NewCore( return zapcore.NewCore(
encoder.NewTextEncoder(lc.encoderConfig()), encoder.NewTextEncoder(config.encoderConfig()),
// zapcore.NewMultiWriteSyncer( // zapcore.NewMultiWriteSyncer(
// zapcore.Lock(os.Stdout), // zapcore.Lock(os.Stdout),
// lc.fileWriteSyncer(), // config.fileWriteSyncer(),
// ), // ),
lc.fileWriteSyncer(lc.Filename), config.fileWriteSyncer(config.Filename),
lc.atomicLevel, config.atomicLevel,
) )
} }
func (lc *logConfig) errorFileCore() zapcore.Core { func (config *logConfig) errorFileCore() zapcore.Core {
return zapcore.NewCore( return zapcore.NewCore(
encoder.NewTextEncoder(lc.encoderConfig()), encoder.NewTextEncoder(config.encoderConfig()),
lc.fileWriteSyncer(lc.ErrorLogFilename), config.fileWriteSyncer(config.ErrorLogFilename),
zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= zapcore.ErrorLevel return lvl >= zapcore.ErrorLevel
}), }),
) )
} }
func (lc *logConfig) encodeLevel(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) { func (config *logConfig) encodeLevel(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
levelString := l.CapitalString() levelString := l.CapitalString()
if lc.EnableLevelTruncation { if config.EnableLevelTruncation {
levelString = levelString[:4] levelString = levelString[:4]
} }
enc.AppendString(fmt.Sprintf("[%s]", levelString)) enc.AppendString(fmt.Sprintf("[%s]", levelString))
} }
func (lc *logConfig) encodeColorLevel(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) { func (config *logConfig) encodeColorLevel(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
s, ok := _levelToColorStrings[l] s, ok := _levelToColorStrings[l]
if !ok { if !ok {
s = _unknownLevelColor.Add(l.CapitalString()) s = _unknownLevelColor.Add(l.CapitalString())
@ -219,7 +220,7 @@ func trimCallerFilePath(ec zapcore.EntryCaller) string {
return fmt.Sprintf(" %s", caller) return fmt.Sprintf(" %s", caller)
} }
func (lc *logConfig) fileWriteSyncer(fileName string) zapcore.WriteSyncer { func (config *logConfig) fileWriteSyncer(fileName string) zapcore.WriteSyncer {
// go get github.com/lestrrat-go/file-rotatelogs // go get github.com/lestrrat-go/file-rotatelogs
// writer, err := rotatelogs.New( // writer, err := rotatelogs.New(
// name+".%Y%m%d", // name+".%Y%m%d",
@ -233,12 +234,12 @@ func (lc *logConfig) fileWriteSyncer(fileName string) zapcore.WriteSyncer {
writer := &lumberjack.Logger{ writer := &lumberjack.Logger{
Filename: fileName, Filename: fileName,
MaxSize: lc.MaxSize, // 单个日志文件大小MB MaxSize: config.MaxSize, // 单个日志文件大小MB
MaxBackups: lc.MaxBackups, MaxBackups: config.MaxBackups,
MaxAge: lc.MaxAge, // 保留多少天的日志 MaxAge: config.MaxAge, // 保留多少天的日志
LocalTime: lc.LocalTime, LocalTime: config.LocalTime,
Compress: lc.Compress, Compress: config.Compress,
BackupTimeFormat: lc.BackupTimeFormat, BackupTimeFormat: config.BackupTimeFormat,
} }
// Rotating log files daily // Rotating log files daily

View File

@ -1,6 +1,7 @@
package log package log
import ( import (
"go.uber.org/zap"
"testing" "testing"
"time" "time"
) )
@ -13,14 +14,19 @@ func TestLog(t *testing.T) {
} }
func TestLogWithConfig(t *testing.T) { func TestLogWithConfig(t *testing.T) {
lc := NewLogConfig() config := NewLogConfig()
_ = lc.Level.Set("info") _ = config.Level.Set("d")
lc.Name = "main" config.Name = "main"
lc.Init() //config.Fields = []zap.Field{zap.String("traceid", "12123123123")}
config.Init()
With("foo", "baz")
Debugf("this is %s message", "debug") Debugf("this is %s message", "debug")
config.Init()
With(zap.String("traceid", "12123123123"))
Infof("this is %s message", "info") Infof("this is %s message", "info")
Errorf("this is %s message", "error") //Errorf("this is %s message", "error")
// Panicf("this is %s message", "panic") // Panicf("this is %s message", "panic")
} }

View File

@ -1,5 +1,9 @@
package log package log
func With(args ...interface{}) {
logger = logger.With(args...)
}
func Debug(args ...interface{}) { func Debug(args ...interface{}) {
logger.Debug(args...) logger.Debug(args...)
} }

View File

@ -1 +1 @@
v0.0.5 v0.0.6