logger.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package logger
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "go.uber.org/zap"
  5. "go.uber.org/zap/zapcore"
  6. "os"
  7. )
  8. var logger *zap.SugaredLogger
  9. func Init(runMode string) {
  10. // First, define our level-handling logic.
  11. highPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
  12. return lvl >= zapcore.ErrorLevel
  13. })
  14. lowPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
  15. switch runMode {
  16. case gin.ReleaseMode:
  17. return lvl >= zapcore.InfoLevel && lvl < zapcore.ErrorLevel
  18. default:
  19. fallthrough
  20. case gin.DebugMode:
  21. return lvl < zapcore.ErrorLevel
  22. }
  23. })
  24. // Directly output to stdout and stderr, and add caller information.
  25. consoleDebugging := zapcore.Lock(os.Stdout)
  26. consoleErrors := zapcore.Lock(os.Stderr)
  27. encoderConfig := zap.NewDevelopmentEncoderConfig()
  28. encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05")
  29. encoderConfig.ConsoleSeparator = " "
  30. encoderConfig.EncodeLevel = colorLevelEncoder
  31. consoleEncoder := zapcore.NewConsoleEncoder(encoderConfig)
  32. // Join the outputs, encoders, and level-handling functions into
  33. // zapcore.Cores, then tee the two cores together.
  34. core := zapcore.NewTee(
  35. zapcore.NewCore(consoleEncoder, consoleErrors, highPriority),
  36. zapcore.NewCore(consoleEncoder, consoleDebugging, lowPriority),
  37. )
  38. // From a zapcore.Core, it's easy to construct a Logger.
  39. logger = zap.New(core, zap.AddCaller()).WithOptions(zap.AddCallerSkip(1)).Sugar()
  40. }
  41. func Sync() {
  42. _ = logger.Sync()
  43. }
  44. func GetLogger() *zap.SugaredLogger {
  45. return logger
  46. }
  47. func Info(args ...interface{}) {
  48. logger.Infoln(args...)
  49. }
  50. func Error(args ...interface{}) {
  51. logger.Errorln(args...)
  52. }
  53. func Fatal(args ...interface{}) {
  54. logger.Fatalln(args...)
  55. }
  56. func Warn(args ...interface{}) {
  57. logger.Warnln(args...)
  58. }
  59. func Debug(args ...interface{}) {
  60. logger.Debugln(args...)
  61. }
  62. func Infof(format string, args ...interface{}) {
  63. logger.Infof(format, args...)
  64. }
  65. func Errorf(format string, args ...interface{}) {
  66. logger.Errorf(format, args...)
  67. }
  68. func Fatalf(format string, args ...interface{}) {
  69. logger.Fatalf(format, args...)
  70. }
  71. func Warnf(format string, args ...interface{}) {
  72. logger.Warnf(format, args...)
  73. }
  74. func Debugf(format string, args ...interface{}) {
  75. logger.Debugf(format, args...)
  76. }