logger.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package logger
  2. import (
  3. "github.com/natefinch/lumberjack"
  4. "go.uber.org/zap"
  5. "go.uber.org/zap/zapcore"
  6. "os"
  7. "time"
  8. )
  9. // error logger
  10. var log *zap.SugaredLogger
  11. var levelMap = map[string]zapcore.Level{
  12. "debug": zapcore.DebugLevel,
  13. "info": zapcore.InfoLevel,
  14. "warn": zapcore.WarnLevel,
  15. "error": zapcore.ErrorLevel,
  16. "panic": zapcore.PanicLevel,
  17. "fatal": zapcore.FatalLevel,
  18. }
  19. type Config struct {
  20. Compress bool
  21. ConsoleStdout bool
  22. FileStdout bool
  23. Level string
  24. LocalTime bool
  25. MaxAge int
  26. MaxBackups int
  27. MaxSize int
  28. Path string
  29. }
  30. func Init(conf *Config) {
  31. var syncWriters []zapcore.WriteSyncer
  32. level := getLoggerLevel(conf.Level)
  33. fileConfig := &lumberjack.Logger{
  34. Filename: conf.Path, // 日志文件名
  35. MaxSize: conf.MaxSize, // 日志文件大小
  36. MaxAge: conf.MaxAge, // 最长保存天数
  37. MaxBackups: conf.MaxBackups, // 最多备份几个
  38. LocalTime: conf.LocalTime, // 日志时间戳
  39. Compress: conf.Compress, // 是否压缩文件,使用gzip
  40. }
  41. encoder := zap.NewProductionEncoderConfig()
  42. encoder.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
  43. enc.AppendString(t.Format("2006-01-02 15:04:05"))
  44. }
  45. if conf.ConsoleStdout {
  46. syncWriters = append(syncWriters, zapcore.AddSync(os.Stdout))
  47. }
  48. if conf.FileStdout {
  49. syncWriters = append(syncWriters, zapcore.AddSync(fileConfig))
  50. }
  51. core := zapcore.NewCore(
  52. zapcore.NewJSONEncoder(encoder),
  53. zapcore.NewMultiWriteSyncer(syncWriters...),
  54. zap.NewAtomicLevelAt(level))
  55. logger := zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
  56. log = logger.Sugar()
  57. }
  58. func getLoggerLevel(lvl string) zapcore.Level {
  59. if level, ok := levelMap[lvl]; ok {
  60. return level
  61. }
  62. return zapcore.InfoLevel
  63. }
  64. func Debug(args ...interface{}) {
  65. log.Debug(args...)
  66. }
  67. func Info(args ...interface{}) {
  68. log.Info(args...)
  69. }
  70. func Infof(format string, args ...interface{}) {
  71. log.Infof(format, args...)
  72. }
  73. func Warn(args ...interface{}) {
  74. log.Warn(args...)
  75. }
  76. func Error(args ...interface{}) {
  77. log.Error(args...)
  78. }
  79. func DPanic(args ...interface{}) {
  80. log.DPanic(args...)
  81. }
  82. func Panic(args ...interface{}) {
  83. log.Panic(args...)
  84. }
  85. func Fatal(args ...interface{}) {
  86. log.Fatal(args...)
  87. }