Browse Source

update: enhance log module

dev
Dnomd343 1 year ago
parent
commit
4664428b6e
  1. 3
      go.mod
  2. 8
      go.sum
  3. 46
      next/logger/encoder.go
  4. 39
      next/logger/interface.go
  5. 157
      next/logger/logger.go
  6. 16
      next/main.go

3
go.mod

@ -14,7 +14,10 @@ require (
) )
require ( require (
github.com/fatih/color v1.15.0 // indirect
github.com/gookit/color v1.5.4 // indirect github.com/gookit/color v1.5.4 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
go.uber.org/multierr v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sys v0.10.0 // indirect golang.org/x/sys v0.10.0 // indirect

8
go.sum

@ -2,10 +2,17 @@ github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbi
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
github.com/go-http-utils/headers v0.0.0-20181008091004-fed159eddc2a/go.mod h1:I79BieaU4fxrw4LMXby6q5OS9XnoR9UIKLOzDFjUmuw= github.com/go-http-utils/headers v0.0.0-20181008091004-fed159eddc2a/go.mod h1:I79BieaU4fxrw4LMXby6q5OS9XnoR9UIKLOzDFjUmuw=
github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k= github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
@ -18,6 +25,7 @@ go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN8
go.uber.org/zap v1.25.0 h1:4Hvk6GtkucQ790dqmj7l1eEnRdKm3k3ZUrUMS2d5+5c= go.uber.org/zap v1.25.0 h1:4Hvk6GtkucQ790dqmj7l1eEnRdKm3k3ZUrUMS2d5+5c=
go.uber.org/zap v1.25.0/go.mod h1:JIAUzQIH94IC4fOJQm7gMmBJP5k7wQfdcnYdPoEXJYk= go.uber.org/zap v1.25.0/go.mod h1:JIAUzQIH94IC4fOJQm7gMmBJP5k7wQfdcnYdPoEXJYk=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

46
next/logger/encoder.go

@ -0,0 +1,46 @@
package logger
import (
"github.com/fatih/color"
"go.uber.org/zap/zapcore"
"time"
)
func encodeTime(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
}
func encodeColoredTime(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(color.WhiteString(t.Format("2006-01-02 15:04:05.000")))
}
func encodeCaller(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[" + caller.TrimmedPath() + "]")
}
func encodeColoredCaller(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(color.MagentaString("[" + caller.TrimmedPath() + "]"))
}
func encodeLevel(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[" + level.CapitalString() + "]")
}
func encodeColoredLevel(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(func(level zapcore.Level) func(string, ...interface{}) string {
switch level {
case zapcore.DebugLevel:
return color.CyanString
case zapcore.InfoLevel:
return color.GreenString
case zapcore.WarnLevel:
return color.YellowString
case zapcore.ErrorLevel:
return color.RedString
case zapcore.PanicLevel:
return color.HiRedString
default:
return color.WhiteString
}
}(level)("[" + level.CapitalString() + "]"))
}

39
next/logger/interface.go

@ -0,0 +1,39 @@
package logger
import "go.uber.org/zap/zapcore"
const (
DebugLevel = zapcore.DebugLevel
InfoLevel = zapcore.InfoLevel
WarnLevel = zapcore.WarnLevel
ErrorLevel = zapcore.ErrorLevel
PanicLevel = zapcore.PanicLevel
)
func GetLevel() zapcore.Level {
return handle.level.Level()
}
func SetLevel(level zapcore.Level) {
handle.level.SetLevel(level)
}
func Debugf(template string, args ...interface{}) {
handle.sugar.Debugf(template, args...)
}
func Infof(template string, args ...interface{}) {
handle.sugar.Infof(template, args...)
}
func Warnf(template string, args ...interface{}) {
handle.sugar.Warnf(template, args...)
}
func Errorf(template string, args ...interface{}) {
handle.sugar.Errorf(template, args...)
}
func Panicf(template string, args ...interface{}) {
handle.sugar.Panicf(template, args...)
}

157
next/logger/logger.go

@ -1,134 +1,61 @@
package logger package logger
import ( import (
"fmt"
"go.uber.org/zap" "go.uber.org/zap"
"os" "go.uber.org/zap/zapcore"
"time"
) )
import "go.uber.org/zap/zapcore"
var Logger *zap.SugaredLogger type Logger struct {
logger *zap.Logger
const ( level *zap.AtomicLevel
logTmFmt = "2006-01-02 15:04:05" sugar *zap.SugaredLogger
) }
func init() {
//coreConfig := zapcore.EncoderConfig{
// TimeKey: "ts",
// LevelKey: "level",
// NameKey: "logger",
// CallerKey: "caller",
// FunctionKey: zapcore.OmitKey,
// MessageKey: "msg",
// StacktraceKey: "stacktrace",
// LineEnding: zapcore.DefaultLineEnding, // 默认换行符"\n"
// EncodeLevel: zapcore.CapitalColorLevelEncoder,
// EncodeTime: zapcore.RFC3339TimeEncoder, // 日志时间格式显示
// EncodeDuration: zapcore.MillisDurationEncoder, // 时间序列化,Duration为经过的浮点秒数
// EncodeCaller: zapcore.ShortCallerEncoder, // 日志行号显示
//}
//
//encoder := zapcore.NewConsoleEncoder(coreConfig)
//
//newCore := zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), zapcore.DebugLevel)
//
//logger := zap.New(newCore)
//
//Logger = logger.Sugar()
GetLogger()
//log, err := zap.NewDevelopment()
//if err != nil {
// panic("log utils init failed")
//}
// TODO: more zap logger configure var handle Logger
// TODO: reserve raw logger handle
//Logger = log.Sugar() func logConfig(level zap.AtomicLevel, colored bool) zapcore.EncoderConfig {
config := zapcore.EncoderConfig{
ConsoleSeparator: " ",
MessageKey: "msg",
LevelKey: "level",
TimeKey: "time",
CallerKey: "caller",
EncodeTime: encodeTime,
EncodeLevel: encodeLevel,
EncodeCaller: encodeCaller,
}
if colored {
config.EncodeTime = encodeColoredTime
config.EncodeLevel = encodeColoredLevel
config.EncodeCaller = encodeColoredCaller
}
return config
} }
func GetLogger() { func init() {
config := zapcore.EncoderConfig{
MessageKey: "M",
LevelKey: "L",
TimeKey: "T",
NameKey: "N",
CallerKey: "C",
FunctionKey: "F",
StacktraceKey: "S",
SkipLineEnding: false,
LineEnding: "\n",
EncodeLevel: logEncodeLevel, level := zap.NewAtomicLevelAt(DebugLevel)
//EncodeLevel: zapcore.CapitalColorLevelEncoder,
EncodeTime: logEncodeTime,
EncodeDuration: zapcore.StringDurationEncoder,
//EncodeCaller: logEncodeCaller,
EncodeCaller: zapcore.ShortCallerEncoder,
//EncodeName: logEncodeName, writer, _, _ := zap.Open("/dev/stderr", "/root/XProxy/next/lalala.log")
ConsoleSeparator: " ",
}
//var zc = zap.Config{ core := zapcore.NewCore(
// Level: zap.NewAtomicLevelAt(zapcore.DebugLevel), zapcore.NewConsoleEncoder(logConfig(level, false)),
// Development: false, //zapcore.Lock(os.Stderr),
// DisableCaller: false, writer,
// DisableStacktrace: false, level,
// Sampling: nil, )
// Encoding: "json",
// EncoderConfig: config,
// OutputPaths: []string{"stdout"},
// ErrorOutputPaths: []string{"stderr"},
// InitialFields: map[string]interface{}{"app": "zapdex"},
//}
newCore := zapcore.NewCore(zapcore.NewConsoleEncoder(config), zapcore.Lock(os.Stderr), zapcore.DebugLevel) //zapcore.AddSync()
//newCore := zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.Lock(os.Stderr), zapcore.DebugLevel) //zap.Open()
logger := zap.New(newCore, zap.AddCaller())
//logger := zap.New(newCore)
//logger, _ := zc.Build()
//logger.Named("123")
//fmt.Println(logger.Name())
zap.ReplaceGlobals(logger) //return core
Logger = logger.Sugar()
}
func logEncodeLevel(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) { logger := zap.New(core, zap.AddCaller())
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) { handle = Logger{
// TODO: using `2006-01-02 15:04:05.xxx` format logger: logger,
enc.AppendString(fmt.Sprintf( level: &level,
"\x1b[36m%s\x1b[0m \x1b[90m%s\x1b[0m", sugar: logger.Sugar(),
"[XProxy]", t.Format("2006-01-02 15:04:05"), }
))
}
func logEncodeCaller(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("{" + caller.TrimmedPath() + "}")
} }

16
next/main.go

@ -1,13 +1,13 @@
package main package main
import ( import "XProxy/next/logger"
. "XProxy/next/logger"
)
func main() { func main() {
Logger.Debugf("here is %s level", "debug")
Logger.Infof("here is %s level", "info") logger.Debugf("here is %s level", "debug")
Logger.Warnf("here is %s level", "warn") logger.Infof("here is %s level", "info")
Logger.Errorf("here is %s level", "error") logger.Warnf("here is %s level", "warn")
//Logger.Panicf("here is %s level", "panic") logger.Errorf("here is %s level", "error")
//logger.Panicf("here is %s level", "panic")
} }

Loading…
Cancel
Save