log.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package fslog
  2. import (
  3. "go.uber.org/zap"
  4. "go.uber.org/zap/zapcore"
  5. "gopkg.in/natefinch/lumberjack.v2"
  6. "io"
  7. "os"
  8. )
  9. var log *Logger
  10. func init() {
  11. consoleCfg := zap.NewDevelopmentEncoderConfig()
  12. consoleCfg.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05")
  13. jsonCfg := zap.NewProductionEncoderConfig()
  14. jsonCfg.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05")
  15. log = &Logger{
  16. lv: zap.NewAtomicLevelAt(zap.DebugLevel),
  17. }
  18. log.cores = append(log.cores,
  19. zapcore.NewCore(zapcore.NewConsoleEncoder(consoleCfg), zapcore.AddSync(os.Stdout), log.lv),
  20. zapcore.NewCore(zapcore.NewJSONEncoder(jsonCfg), zapcore.AddSync(&lumberjack.Logger{
  21. Filename: "logs/log",
  22. MaxSize: 1,
  23. MaxAge: 10,
  24. LocalTime: true,
  25. }), log.lv),
  26. )
  27. log.flushLogger()
  28. }
  29. // With 见 Logger.With
  30. func With(k string, v any) *Logger {
  31. return log.With(k, v)
  32. }
  33. // Info 见 Logger.Info
  34. func Info(msg string, vs ...any) *Logger {
  35. log.Info(msg, vs...)
  36. return log
  37. }
  38. // Debug 见 Logger.Debug
  39. func Debug(msg string, vs ...any) *Logger {
  40. log.Debug(msg, vs...)
  41. return log
  42. }
  43. // Warn 见 Logger.Warn
  44. func Warn(msg string, vs ...any) *Logger {
  45. log.Warn(msg, vs...)
  46. return log
  47. }
  48. // Error 见 Logger.Error
  49. func Error(vs ...any) *Logger {
  50. log.Error(vs...)
  51. return log
  52. }
  53. // Lv 见 Logger.Lv
  54. func Lv() Level {
  55. return log.Lv()
  56. }
  57. // SetLv 见 Logger.SetLv
  58. func SetLv(lv Level) *Logger {
  59. log.SetLv(lv)
  60. return log
  61. }
  62. // NewFileOutput 见 Logger.NewFileOutput
  63. func NewFileOutput(opts ...FileOutputOpt) *Logger {
  64. log.NewFileOutput(opts...)
  65. return log
  66. }
  67. // NewOutput 见 Logger.NewOutput
  68. func NewOutput(writer io.Writer) *Logger {
  69. log.NewOutput(writer)
  70. return log
  71. }
  72. // SetLogger 替换fslog包默认的log对象
  73. // Logger 支持了zapcore级别的底层配置,见 Logger
  74. func SetLogger(logger *Logger) *Logger {
  75. log = logger
  76. return log
  77. }
  78. // Flush 见 Logger.Flush
  79. func Flush() {
  80. log.Flush()
  81. }