fslog_instance.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. MaxSize: 1,
  41. MaxAge: 10,
  42. }
  43. developmentEncoderConfig := zap.NewDevelopmentEncoderConfig()
  44. encoder := zapcore.NewConsoleEncoder(developmentEncoderConfig)
  45. core := zapcore.NewTee(
  46. zapcore.NewCore(encoder, zapcore.AddSync(lumberJackLogger), chooseLoggerLever()),
  47. zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), chooseLoggerLever()),
  48. )
  49. logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
  50. })
  51. }
  52. func Info(message string) {
  53. lazyInitialize()
  54. logger.Info(message)
  55. }
  56. func Error(err error) {
  57. lazyInitialize()
  58. message := fmt.Sprintf("\n%+v\n", err)
  59. logger.Error(message)
  60. }
  61. func Debug(message string) {
  62. lazyInitialize()
  63. logger.Debug(message)
  64. }
  65. func Warn(message string) {
  66. lazyInitialize()
  67. logger.Warn(message)
  68. }