fslog_instance.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package fslog
  2. import (
  3. "fmt"
  4. "go.uber.org/zap"
  5. "go.uber.org/zap/zapcore"
  6. "os"
  7. "path/filepath"
  8. "sync"
  9. )
  10. const (
  11. LoggerLevelInfo = "info"
  12. LoggerLevelError = "error"
  13. LoggerLevelDebug = "debug"
  14. LoggerLevelWarn = "Warn"
  15. )
  16. var LoggerLever = LoggerLevelDebug
  17. func chooseLoggerLever() zapcore.Level {
  18. switch LoggerLever {
  19. case LoggerLevelInfo:
  20. return zapcore.InfoLevel
  21. case LoggerLevelError:
  22. return zapcore.ErrorLevel
  23. case LoggerLevelDebug:
  24. return zapcore.DebugLevel
  25. case LoggerLevelWarn:
  26. return zapcore.WarnLevel
  27. default:
  28. return zapcore.DebugLevel
  29. }
  30. }
  31. var logger *zap.Logger
  32. var initLoggerOnce sync.Once
  33. const logDir = "logs"
  34. func lazyInitialize() {
  35. initLoggerOnce.Do(func() {
  36. if !pathExists(logDir) {
  37. err := os.MkdirAll(logDir, os.ModeDir|os.ModePerm)
  38. if err != nil {
  39. panic(err)
  40. }
  41. }
  42. logFilePath := filepath.Join(logDir, "log")
  43. file, err := os.Create(logFilePath)
  44. if err != nil {
  45. panic(err)
  46. }
  47. developmentEncoderConfig := zap.NewDevelopmentEncoderConfig()
  48. encoder := zapcore.NewConsoleEncoder(developmentEncoderConfig)
  49. core := zapcore.NewTee(
  50. zapcore.NewCore(encoder, zapcore.AddSync(file), chooseLoggerLever()),
  51. zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), chooseLoggerLever()),
  52. )
  53. logger = zap.New(core, zap.AddCaller(),zap.AddCallerSkip(1))
  54. })
  55. }
  56. func Info(message string) {
  57. lazyInitialize()
  58. logger.Info(message)
  59. }
  60. func Error(err error) {
  61. lazyInitialize()
  62. message:= fmt.Sprintf("\n%+v\n", err)
  63. logger.Error(message)
  64. }
  65. func Debug(message string) {
  66. lazyInitialize()
  67. logger.Debug(message)
  68. }
  69. func Warn(message string) {
  70. lazyInitialize()
  71. logger.Warn(message)
  72. }
  73. func pathExists(path string) bool {
  74. _, err := os.Stat(path)
  75. if err == nil {
  76. return true
  77. }
  78. if os.IsNotExist(err) {
  79. return false
  80. }
  81. return false
  82. }