Browse Source

update: enhance log module

dev
Dnomd343 10 months 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 (
github.com/fatih/color v1.15.0 // 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
go.uber.org/multierr v1.11.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/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/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/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
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/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/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
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/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-20220811171246-fbc7d0a398ab/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/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
import (
"fmt"
"go.uber.org/zap"
"os"
"time"
"go.uber.org/zap/zapcore"
)
import "go.uber.org/zap/zapcore"
var Logger *zap.SugaredLogger
const (
logTmFmt = "2006-01-02 15:04:05"
)
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")
//}
type Logger struct {
logger *zap.Logger
level *zap.AtomicLevel
sugar *zap.SugaredLogger
}
// TODO: more zap logger configure
// TODO: reserve raw logger handle
var handle Logger
//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() {
config := zapcore.EncoderConfig{
MessageKey: "M",
LevelKey: "L",
TimeKey: "T",
NameKey: "N",
CallerKey: "C",
FunctionKey: "F",
StacktraceKey: "S",
SkipLineEnding: false,
LineEnding: "\n",
func init() {
EncodeLevel: logEncodeLevel,
//EncodeLevel: zapcore.CapitalColorLevelEncoder,
EncodeTime: logEncodeTime,
EncodeDuration: zapcore.StringDurationEncoder,
//EncodeCaller: logEncodeCaller,
EncodeCaller: zapcore.ShortCallerEncoder,
level := zap.NewAtomicLevelAt(DebugLevel)
//EncodeName: logEncodeName,
ConsoleSeparator: " ",
}
writer, _, _ := zap.Open("/dev/stderr", "/root/XProxy/next/lalala.log")
//var zc = zap.Config{
// Level: zap.NewAtomicLevelAt(zapcore.DebugLevel),
// Development: false,
// DisableCaller: false,
// DisableStacktrace: false,
// Sampling: nil,
// Encoding: "json",
// EncoderConfig: config,
// OutputPaths: []string{"stdout"},
// ErrorOutputPaths: []string{"stderr"},
// InitialFields: map[string]interface{}{"app": "zapdex"},
//}
core := zapcore.NewCore(
zapcore.NewConsoleEncoder(logConfig(level, false)),
//zapcore.Lock(os.Stderr),
writer,
level,
)
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())
//zapcore.AddSync()
//zap.Open()
zap.ReplaceGlobals(logger)
Logger = logger.Sugar()
}
//return core
func logEncodeLevel(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
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))
}
logger := zap.New(core, zap.AddCaller())
func logEncodeTime(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
// 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"),
))
}
handle = Logger{
logger: logger,
level: &level,
sugar: logger.Sugar(),
}
func logEncodeCaller(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("{" + caller.TrimmedPath() + "}")
}

16
next/main.go

@ -1,13 +1,13 @@
package main
import (
. "XProxy/next/logger"
)
import "XProxy/next/logger"
func main() {
Logger.Debugf("here is %s level", "debug")
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")
logger.Debugf("here is %s level", "debug")
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