fslog_instance.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package fslog
  2. import (
  3. "fmt"
  4. "go.uber.org/zap"
  5. "go.uber.org/zap/zapcore"
  6. "gopkg.in/natefinch/lumberjack.v2"
  7. "os"
  8. "path/filepath"
  9. "sync"
  10. )
  11. const (
  12. LoggerLevelInfo = "info"
  13. LoggerLevelError = "error"
  14. LoggerLevelDebug = "debug"
  15. LoggerLevelWarn = "Warn"
  16. )
  17. var LoggerLever = LoggerLevelDebug
  18. func chooseLoggerLever() zapcore.Level {
  19. switch LoggerLever {
  20. case LoggerLevelInfo:
  21. return zapcore.InfoLevel
  22. case LoggerLevelError:
  23. return zapcore.ErrorLevel
  24. case LoggerLevelDebug:
  25. return zapcore.DebugLevel
  26. case LoggerLevelWarn:
  27. return zapcore.WarnLevel
  28. default:
  29. return zapcore.DebugLevel
  30. }
  31. }
  32. var logger *zap.Logger
  33. var initLoggerOnce sync.Once
  34. const logDir = "logs"
  35. func lazyInitialize() {
  36. initLoggerOnce.Do(func() {
  37. logFilePath := filepath.Join(logDir, "log")
  38. lumberJackLogger := &lumberjack.Logger{
  39. Filename: logFilePath,
  40. MaxAge: 10,
  41. }
  42. developmentEncoderConfig := zap.NewDevelopmentEncoderConfig()
  43. encoder := zapcore.NewConsoleEncoder(developmentEncoderConfig)
  44. core := zapcore.NewTee(
  45. zapcore.NewCore(encoder, zapcore.AddSync(lumberJackLogger), chooseLoggerLever()),
  46. zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), chooseLoggerLever()),
  47. )
  48. logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
  49. })
  50. }
  51. func Info(message string) {
  52. lazyInitialize()
  53. logger.Info(message)
  54. }
  55. func Error(err error) {
  56. lazyInitialize()
  57. message := fmt.Sprintf("\n%+v\n", err)
  58. logger.Error(message)
  59. }
  60. func Debug(message string) {
  61. lazyInitialize()
  62. logger.Debug(message)
  63. }
  64. func Warn(message string) {
  65. lazyInitialize()
  66. logger.Warn(message)
  67. }