Browse Source

feat: custom log format

dev
Dnomd343 1 year ago
parent
commit
ac17a453de
  1. 44
      next/logger/logger.go
  2. 2
      next/main.go

44
next/logger/logger.go

@ -62,15 +62,17 @@ func GetLogger() {
FunctionKey: "F",
StacktraceKey: "S",
SkipLineEnding: false,
LineEnding: "!!!\n",
LineEnding: "\n",
EncodeLevel: logEncodeLevel,
//EncodeLevel: zapcore.CapitalColorLevelEncoder,
EncodeTime: logEncodeTime,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: logEncodeCaller,
//EncodeCaller: logEncodeCaller,
EncodeCaller: zapcore.ShortCallerEncoder,
EncodeName: logEncodeName,
ConsoleSeparator: "$$",
//EncodeName: logEncodeName,
ConsoleSeparator: " ",
}
//var zc = zap.Config{
@ -89,24 +91,44 @@ func GetLogger() {
newCore := zapcore.NewCore(zapcore.NewConsoleEncoder(config), zapcore.Lock(os.Stderr), zapcore.DebugLevel)
//newCore := zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.Lock(os.Stderr), zapcore.DebugLevel)
logger := zap.New(newCore, zap.AddCaller())
//logger := zap.New(newCore)
//logger, _ := zc.Build()
//logger.Named("123")
//fmt.Println(logger.Name())
zap.ReplaceGlobals(logger)
Logger = logger.Sugar()
}
func logEncodeLevel(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[" + level.CapitalString() + "]")
enc.AppendString(func(level zapcore.Level) string {
levelStr := level.CapitalString()
// TODO: using shell codes map
switch level {
case zapcore.DebugLevel:
return fmt.Sprintf("\x1b[39m[%s]\x1b[0m", levelStr)
case zapcore.InfoLevel:
return fmt.Sprintf("\x1b[32m[%s]\x1b[0m", levelStr)
case zapcore.WarnLevel:
return fmt.Sprintf("\x1b[33m[%s]\x1b[0m", levelStr)
case zapcore.ErrorLevel:
return fmt.Sprintf("\x1b[31m[%s]\x1b[0m", levelStr)
case zapcore.PanicLevel:
return fmt.Sprintf("\x1b[95m[%s]\x1b[0m", levelStr)
default:
return fmt.Sprintf("[%s]", levelStr)
}
}(level))
}
func logEncodeTime(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[[" + t.Format(logTmFmt) + "]]")
// TODO: using `2006-01-02 15:04:05.xxx` format
enc.AppendString(fmt.Sprintf(
"\x1b[36m%s\x1b[0m \x1b[90m%s\x1b[0m",
"[XProxy]", t.Format("2006-01-02 15:04:05"),
))
}
func logEncodeCaller(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("{" + caller.TrimmedPath() + "}")
}
func logEncodeName(loggerName string, enc zapcore.PrimitiveArrayEncoder) {
fmt.Println(loggerName)
enc.AppendString("{{" + loggerName + "}}")
}

2
next/main.go

@ -9,5 +9,5 @@ func main() {
Logger.Infof("here is %s level", "info")
Logger.Warnf("here is %s level", "warn")
Logger.Errorf("here is %s level", "error")
//Logger.Panicf("here is %s level", "panic")
}

Loading…
Cancel
Save