logger.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package logger
  2. import (
  3. "io"
  4. "os"
  5. "strings"
  6. "sync"
  7. "github.com/caarlos0/env/v11"
  8. "go.uber.org/zap"
  9. "go.uber.org/zap/zapcore"
  10. )
  11. type Logger struct {
  12. LogLevel string `env:"LEVEL" envDefault:"INFO"`
  13. TraceIDLabel string `env:"TRACE_ID_LABEL" envDefault:"trace_id"`
  14. DateTimeFormat string `env:"DATE_TIME_FORMAT" envDefault:"2006-01-02 15:04:05.000"`
  15. }
  16. var (
  17. once sync.Once
  18. singleton *zap.Logger
  19. cfg Logger
  20. )
  21. const RequestID = "RequestID"
  22. func init() {
  23. cfg = Logger{}
  24. if err := env.Parse(&cfg); err != nil {
  25. Panic("Problemas ao inicializar a aplicação", zap.Error(err))
  26. }
  27. // once ensures the singleton is initialized only once
  28. once.Do(func() {
  29. levelType := getLevelLogType(cfg.LogLevel)
  30. encoderConfig := getEconderConfig()
  31. atom := zap.NewAtomicLevelAt(levelType)
  32. core := zapcore.NewCore(
  33. zapcore.NewJSONEncoder(encoderConfig),
  34. zapcore.AddSync(os.Stdout),
  35. atom,
  36. )
  37. singleton = zap.New(core, zap.AddCallerSkip(1), zap.AddCaller())
  38. })
  39. }
  40. func SetAppName(appName string) {
  41. singleton = singleton.With(zap.String("app", appName))
  42. }
  43. func ChangeWriteSyncer(recurso io.Writer) {
  44. singleton = singleton.WithOptions(
  45. zap.WrapCore(
  46. func(zapcore.Core) zapcore.Core {
  47. return zapcore.NewCore(zapcore.NewJSONEncoder(getEconderConfig()),
  48. zapcore.AddSync(recurso),
  49. zap.NewAtomicLevelAt(zap.DebugLevel))
  50. }))
  51. }
  52. func ChangeLogLevel(level string) {
  53. levelType := getLevelLogType(level)
  54. singleton = singleton.WithOptions(
  55. zap.WrapCore(
  56. func(zapcore.Core) zapcore.Core {
  57. return zapcore.NewCore(zapcore.NewJSONEncoder(getEconderConfig()),
  58. zapcore.AddSync(os.Stdout),
  59. zap.NewAtomicLevelAt(levelType))
  60. }))
  61. }
  62. func getLevelLogType(entrada string) zapcore.Level {
  63. entrada = strings.TrimSpace(entrada)
  64. switch strings.ToUpper(entrada) {
  65. case "INFO":
  66. return zap.InfoLevel
  67. case "DEBUG":
  68. return zap.DebugLevel
  69. case "ERROR":
  70. return zap.ErrorLevel
  71. case "WARN":
  72. return zap.WarnLevel
  73. case "PANIC":
  74. return zap.PanicLevel
  75. case "DPANIC":
  76. return zap.DPanicLevel
  77. case "FATAL":
  78. return zap.FatalLevel
  79. default:
  80. return zap.InfoLevel
  81. }
  82. }
  83. func getEconderConfig() zapcore.EncoderConfig {
  84. return zapcore.EncoderConfig{
  85. MessageKey: "msg",
  86. TimeKey: "time",
  87. LevelKey: "level",
  88. NameKey: "logger",
  89. CallerKey: "caller",
  90. StacktraceKey: "stacktrace",
  91. FunctionKey: "func",
  92. LineEnding: zapcore.DefaultLineEnding,
  93. EncodeLevel: zapcore.CapitalLevelEncoder,
  94. // EncodeTime: zapcore.ISO8601TimeEncoder,
  95. EncodeTime: zapcore.TimeEncoderOfLayout(cfg.DateTimeFormat),
  96. // EncodeDuration: zapcore.SecondsDurationEncoder,
  97. EncodeDuration: zapcore.StringDurationEncoder,
  98. EncodeCaller: zapcore.ShortCallerEncoder,
  99. // EncodeCaller: zapcore.FullCallerEncoder,
  100. }
  101. }
  102. // Debug logs a debug message with the given fields
  103. func Debug(message string, fields ...zap.Field) {
  104. singleton.Debug(message, fields...)
  105. }
  106. // Info logs a debug message with the given fields
  107. func Info(message string, fields ...zap.Field) {
  108. singleton.Info(message, fields...)
  109. }
  110. func Printf(format string, args ...interface{}) {
  111. singleton.Sugar().Infof(format, args...)
  112. }
  113. // Warn logs a debug message with the given fields
  114. func Warn(message string, fields ...zap.Field) {
  115. singleton.Warn(message, fields...)
  116. }
  117. // Error logs a debug message with the given fields
  118. func Error(message string, fields ...zap.Field) {
  119. singleton.Error(message, fields...)
  120. }
  121. // Fatal logs a message than calls os.Exit(1)
  122. func Fatal(message string, fields ...zap.Field) {
  123. singleton.Fatal(message, fields...)
  124. }
  125. func Panic(message string, fields ...zap.Field) {
  126. singleton.Panic(message, fields...)
  127. }
  128. func DPanic(message string, fields ...zap.Field) {
  129. singleton.DPanic(message, fields...)
  130. }
  131. func GetInstance() *zap.Logger {
  132. return singleton
  133. }
  134. func TraceID(traceID string) zap.Field {
  135. return zap.String(cfg.TraceIDLabel, traceID)
  136. }