🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ package main import ( "demo/library/dao/config" ) func main() { cli := InitLog2(&config.LogCfg{ LogName: "Demo", TypeName: "Server_1", Debug: false, }) go cli.WriteMessage() cli.WriteChannel("aaaaa", "bbbbb", "cccccc", "dddddd") } ~~~ ~~~ package main import ( "demo/library/dao/common" "demo/library/dao/config" "fmt" "go.uber.org/zap" "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" "os" "path/filepath" "runtime" "strings" ) type LogMgr2 struct { LogName string TypeName string writeChan chan []interface{} } func InitLog2(cfg *config.LogCfg) *LogMgr2 { if cfg.LogName == "" || cfg.TypeName == "" { common.SimplePanic("ProgramName or TypeName Is Empty") } SetLogger(cfg.LogName+cfg.TypeName, NewLogger(cfg.LogName+cfg.TypeName+".log")) return &LogMgr2{ LogName: cfg.LogName, TypeName: cfg.TypeName, writeChan: make(chan []interface{}, 2048), } } func (mgr *LogMgr2) WriteChannel(keysAndValues ...interface{}) { mgr.writeChan <- keysAndValues } func (mgr *LogMgr2) WriteMessage() { for msg := range mgr.writeChan { _, file, line, _ := runtime.Caller(1) msg = append(msg, file) msg = append(msg, line) GetLogger(mgr.LogName+mgr.TypeName). Infow(mgr.TypeName, msg[:]...) } } //----------------------------------------------------------------------------------------- var maploggers map[string]*zap.SugaredLogger func init() { maploggers = make(map[string]*zap.SugaredLogger) } func GetWorkDir() string { dir, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { fmt.Println(err.Error()) } return strings.Replace(dir, "\\", "/", -1) } func GetLogger(logName string) *zap.SugaredLogger { if v, ok := maploggers[logName]; ok { return v } return nil } func SetLogger(logName string, logger *zap.SugaredLogger) { maploggers[logName] = logger } func NewLogger(fileName string) *zap.SugaredLogger { tmp := GetLogger(fileName) if tmp != nil { return tmp } fileName = GetWorkDir() + "/logs/" + fileName fmt.Println("log path:", fileName) if tmp != nil { return tmp } w := zapcore.AddSync(&lumberjack.Logger{ Filename: fileName, MaxSize: 20, // megabytes MaxBackups: 20, //最多保留20个备份 MaxAge: 7, // days Compress: true, //是否压缩备份文件 }) newProductionEncoderConfig := zap.NewProductionEncoderConfig() newProductionEncoderConfig.TimeKey = "T" newProductionEncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder newProductionEncoderConfig.CallerKey = "T" core := zapcore.NewTee( //打印级别 zapcore.NewCore(zapcore.NewJSONEncoder(newProductionEncoderConfig), w, zapcore.InfoLevel), ) logger := zap.New(core, zap.AddCaller()) return logger.Sugar() } ~~~