1
0

logger.go 2.3 KB

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