互动
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.1 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package logger
  2. import (
  3. "go.uber.org/zap"
  4. "go.uber.org/zap/zapcore"
  5. "gopkg.in/natefinch/lumberjack.v2"
  6. "os"
  7. "time"
  8. )
  9. var Sugar *zap.SugaredLogger
  10. var logger *zap.Logger
  11. func init() {
  12. InitZap()
  13. }
  14. func InitZap() {
  15. w := zapcore.AddSync(&lumberjack.Logger{
  16. Filename: "log/hdzj.log",
  17. MaxSize: 50, // megabytes
  18. MaxBackups: 3,
  19. MaxAge: 7, // days
  20. })
  21. core := zapcore.NewCore(
  22. zapcore.NewConsoleEncoder(NewEncoderConfig()),
  23. zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), w),
  24. zap.DebugLevel)
  25. logger = zap.New(core, zap.AddCaller())
  26. Sugar = logger.Sugar()
  27. }
  28. func NewEncoderConfig() zapcore.EncoderConfig {
  29. return zapcore.EncoderConfig{
  30. // Keys can be anything except the empty string.
  31. TimeKey: "T",
  32. LevelKey: "L",
  33. NameKey: "N",
  34. CallerKey: "C",
  35. MessageKey: "M",
  36. StacktraceKey: "S",
  37. LineEnding: zapcore.DefaultLineEnding,
  38. EncodeLevel: zapcore.CapitalLevelEncoder,
  39. EncodeTime: TimeEncoder,
  40. EncodeDuration: zapcore.StringDurationEncoder,
  41. EncodeCaller: zapcore.ShortCallerEncoder,
  42. }
  43. }
  44. func TimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
  45. enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
  46. }
  47. func level(level string) zapcore.Level {
  48. switch level {
  49. case "info":
  50. return zap.InfoLevel
  51. case "fatal":
  52. return zap.FatalLevel
  53. case "panic":
  54. return zap.PanicLevel
  55. case "error":
  56. return zap.ErrorLevel
  57. case "dpanic":
  58. return zap.DPanicLevel
  59. case "warn":
  60. return zap.WarnLevel
  61. default:
  62. return zap.DebugLevel
  63. }
  64. }
  65. func Info(msg string, fields ...zap.Field) {
  66. logger.Info(msg, fields...)
  67. }
  68. func Debug(msg string, fields ...zap.Field) {
  69. logger.Debug(msg, fields...)
  70. }
  71. func Panic(msg string, fields ...zap.Field) {
  72. logger.Debug(msg, fields...)
  73. }
  74. func Warn(msg string, fields ...zap.Field) {
  75. logger.Warn(msg, fields...)
  76. }
  77. func DPanic(msg string, fields ...zap.Field) {
  78. logger.DPanic(msg, fields...)
  79. }
  80. func Error(msg string, fields ...zap.Field) {
  81. logger.Error(msg, fields...)
  82. }
  83. func With(fields ...zap.Field) {
  84. logger.With(fields...)
  85. }
  86. func WithOptions(opts ...zap.Option) {
  87. logger.WithOptions(opts...)
  88. }