互动
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
2.6 KiB

package logger
import (
"github.com/go-stack/stack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
"os"
"path/filepath"
"time"
)
//var Sugar *zap.SugaredLogger
var logger *zap.SugaredLogger
func init() {
SetLevel("debug")
}
// @func SetLevel 设置日志等级
// @param level 日志等级从高大底: fatal panic dpanic error warn info debug
func SetLevel(level string) {
wd, _ := os.Getwd()
SetLogger(filepath.Join(wd, "log", "hdzj.log"), level, 1024, 10, 7)
}
// @func SetLogger 日志定制化, 包括日志切割的定制化
// @param filename 存放日志的文件, 最好带上路径
// @param level 日志写入的等级
// @param size 单个日志文件的大小
// @param backups 日志备份的数量
// @param age 日志存放的时间
func SetLogger(filename, level string, size, backups, age int) {
w := zapcore.AddSync(&lumberjack.Logger{
Filename: filename,
MaxSize: size, // megabytes
MaxBackups: backups,
MaxAge: age, // days
})
core := zapcore.NewCore(
zapcore.NewConsoleEncoder(NewEncoderConfig()),
zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), w),
Level(level))
logger = zap.New(core, zap.AddCaller()).Sugar()
}
func NewEncoderConfig() zapcore.EncoderConfig {
return zapcore.EncoderConfig{
// Keys can be anything except the empty string.
TimeKey: "T",
LevelKey: "L",
NameKey: "N",
CallerKey: "C",
MessageKey: "M",
StacktraceKey: "S",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.CapitalLevelEncoder,
EncodeTime: TimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: func(caller zapcore.EntryCaller, encoder zapcore.PrimitiveArrayEncoder) {
frame := stack.Caller(7).Frame()
caller.Line = frame.Line
caller.File = frame.File
encoder.AppendString(caller.TrimmedPath())
},
}
}
func TimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
}
func Level(level string) zapcore.Level {
switch level {
case "info":
return zap.InfoLevel
case "fatal":
return zap.FatalLevel
case "panic":
return zap.PanicLevel
case "error":
return zap.ErrorLevel
case "dpanic":
return zap.DPanicLevel
case "warn":
return zap.WarnLevel
default:
return zap.DebugLevel
}
}
func Info(args ...interface{}) {
logger.Info(args...)
}
func Debug(args ...interface{}) {
logger.Debug(args...)
}
func Panic(args ...interface{}) {
logger.Panic(args...)
}
func Warn(args ...interface{}) {
logger.Warn(args...)
}
func Error(args ...interface{}) {
logger.Error(args...)
}