本文介绍了在基于gin框架开发的项目中如何配置并使用zap来接收并记录gin框架默认的日志和如何配置日志归档。
我们在基于gin框架开发项目时通常都会选择使用专业的日志库来记录项目中的日志,go语言常用的日志库有zaplogrus等。网上也有很多类似的教程,我之前也翻译过一篇《在Go语言项目中使用Zap日志库》
但是我们该如何在日志中记录gin框架本身输出的那些日志呢?

gin默认的中间件

首先我们来看一个最简单的gin项目:

  1. func main() {
  2. r := gin.Default()
  3. r.GET("/hello", func(c *gin.Context) {
  4. c.String("hello q1mi!")
  5. })
  6. r.Run(
  7. }

接下来我们看一下gin.Default()的源码:

  1. func Default() *Engine {
  2. debugPrintWARNINGDefault()
  3. engine := New()
  4. engine.Use(Logger(), Recovery())
  5. return engine
  6. }

也就是我们在使用gin.Default()的同时是用到了gin框架内的两个默认中间件Logger()Recovery()
其中Logger()是把gin框架本身的日志输出到标准输出(我们本地开发调试时在终端输出的那些日志就是它的功劳),而Recovery()是在程序出现panic的时候恢复现场并写入500响应的。

基于zap的中间件

我们可以模仿Logger()Recovery()的实现,使用我们的日志库来接收gin框架默认输出的日志。
这里以zap为例,我们实现两个中间件如下:

  1. // GinLogger 接收gin框架默认的日志
  2. func GinLogger(logger *zap.Logger) gin.HandlerFunc {
  3. return func(c *gin.Context) {
  4. start := time.Now()
  5. path := c.Request.URL.Path
  6. query := c.Request.URL.RawQuery
  7. c.Next()
  8. cost := time.Since(start)
  9. logger.Info(path,
  10. zap.Int("status", c.Writer.Status()),
  11. zap.String("method", c.Request.Method),
  12. zap.String("path", path),
  13. zap.String("query", query),
  14. zap.String("ip", c.ClientIP()),
  15. zap.String("user-agent", c.Request.UserAgent()),
  16. zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
  17. zap.Duration("cost", cost),
  18. )
  19. }
  20. }
  21. // GinRecovery recover掉项目可能出现的panic
  22. func GinRecovery(logger *zap.Logger, stack bool) gin.HandlerFunc {
  23. return func(c *gin.Context) {
  24. defer func() {
  25. if err := recover(); err != nil {
  26. // Check for a broken connection, as it is not really a
  27. // condition that warrants a panic stack trace.
  28. var brokenPipe bool
  29. if ne, ok := err.(*net.OpError); ok {
  30. if se, ok := ne.Err.(*os.SyscallError); ok {
  31. if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
  32. brokenPipe = true
  33. }
  34. }
  35. }
  36. httpRequest, _ := httputil.DumpRequest(c.Request, false)
  37. if brokenPipe {
  38. logger.Error(c.Request.URL.Path,
  39. zap.Any("error", err),
  40. zap.String("request", string(httpRequest)),
  41. )
  42. // If the connection is dead, we can't write a status to it.
  43. c.Error(err.(error)) // nolint: errcheck
  44. c.Abort()
  45. return
  46. }
  47. if stack {
  48. logger.Error("[Recovery from panic]",
  49. zap.Any("error", err),
  50. zap.String("request", string(httpRequest)),
  51. zap.String("stack", string(debug.Stack())),
  52. )
  53. } else {
  54. logger.Error("[Recovery from panic]",
  55. zap.Any("error", err),
  56. zap.String("request", string(httpRequest)),
  57. )
  58. }
  59. c.AbortWithStatus(http.StatusInternalServerError)
  60. }
  61. }()
  62. c.Next()
  63. }
  64. }

如果不想自己实现,可以使用github上有别人封装好的https://github.com/gin-contrib/zap
这样我们就可以在gin框架中使用我们上面定义好的两个中间件来代替gin框架默认的Logger()Recovery()了。

  1. r := gin.New()
  2. r.Use(GinLogger(), GinRecovery())

在gin项目中使用zap

最后我们再加入我们项目中常用的日志切割,完整版的logger.go代码如下:

  1. package logger
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/natefinch/lumberjack"
  5. "go.uber.org/zap"
  6. "go.uber.org/zap/zapcore"
  7. "net"
  8. "net/http"
  9. "net/http/httputil"
  10. "os"
  11. "runtime/debug"
  12. "scheduler/config"
  13. "strings"
  14. "time"
  15. )
  16. var Logger *zap.Logger
  17. // InitLogger 初始化Logger
  18. func InitLogger(cfg *config.LogConfig) (err error) {
  19. writeSyncer := getLogWriter(cfg.Filename, cfg.MaxSize, cfg.MaxBackups, cfg.MaxAge)
  20. encoder := getEncoder()
  21. var l = new(zapcore.Level)
  22. err = l.UnmarshalText([]byte(cfg.Level))
  23. if err != nil {
  24. return
  25. }
  26. core := zapcore.NewCore(encoder, writeSyncer, l)
  27. Logger = zap.New(core, zap.AddCaller())
  28. return
  29. }
  30. func getEncoder() zapcore.Encoder {
  31. encoderConfig := zap.NewProductionEncoderConfig()
  32. encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
  33. encoderConfig.TimeKey = "time"
  34. encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
  35. encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder
  36. encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
  37. return zapcore.NewJSONEncoder(encoderConfig)
  38. }
  39. func getLogWriter(filename string, maxSize, maxBackup, maxAge int) zapcore.WriteSyncer {
  40. lumberJackLogger := &lumberjack.Logger{
  41. Filename: filename,
  42. MaxSize: maxSize,
  43. MaxBackups: maxBackup,
  44. MaxAge: maxAge,
  45. }
  46. return zapcore.AddSync(lumberJackLogger)
  47. }
  48. // GinLogger 接收gin框架默认的日志
  49. func GinLogger(logger *zap.Logger) gin.HandlerFunc {
  50. return func(c *gin.Context) {
  51. start := time.Now()
  52. path := c.Request.URL.Path
  53. query := c.Request.URL.RawQuery
  54. c.Next()
  55. cost := time.Since(start)
  56. logger.Info(path,
  57. zap.Int("status", c.Writer.Status()),
  58. zap.String("method", c.Request.Method),
  59. zap.String("path", path),
  60. zap.String("query", query),
  61. zap.String("ip", c.ClientIP()),
  62. zap.String("user-agent", c.Request.UserAgent()),
  63. zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
  64. zap.Duration("cost", cost),
  65. )
  66. }
  67. }
  68. // GinRecovery recover掉项目可能出现的panic,并使用zap记录相关日志
  69. func GinRecovery(logger *zap.Logger, stack bool) gin.HandlerFunc {
  70. return func(c *gin.Context) {
  71. defer func() {
  72. if err := recover(); err != nil {
  73. // Check for a broken connection, as it is not really a
  74. // condition that warrants a panic stack trace.
  75. var brokenPipe bool
  76. if ne, ok := err.(*net.OpError); ok {
  77. if se, ok := ne.Err.(*os.SyscallError); ok {
  78. if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
  79. brokenPipe = true
  80. }
  81. }
  82. }
  83. httpRequest, _ := httputil.DumpRequest(c.Request, false)
  84. if brokenPipe {
  85. logger.Error(c.Request.URL.Path,
  86. zap.Any("error", err),
  87. zap.String("request", string(httpRequest)),
  88. )
  89. // If the connection is dead, we can't write a status to it.
  90. c.Error(err.(error)) // nolint: errcheck
  91. c.Abort()
  92. return
  93. }
  94. if stack {
  95. logger.Error("[Recovery from panic]",
  96. zap.Any("error", err),
  97. zap.String("request", string(httpRequest)),
  98. zap.String("stack", string(debug.Stack())),
  99. )
  100. } else {
  101. logger.Error("[Recovery from panic]",
  102. zap.Any("error", err),
  103. zap.String("request", string(httpRequest)),
  104. )
  105. }
  106. c.AbortWithStatus(http.StatusInternalServerError)
  107. }
  108. }()
  109. c.Next()
  110. }
  111. }

然后定义日志相关配置:

  1. type LogConfig struct {
  2. Level string `json:"level"`
  3. Filename string `json:"filename"`
  4. MaxSize int `json:"maxsize"`
  5. MaxAge int `json:"max_age"`
  6. MaxBackups int `json:"max_backups"`
  7. }

在项目中先初始化配置信息,再调用logger.InitLogger(cfg.LogConfig)即可完成日志的初识化。

  1. func main() {
  2. // load config from conf/conf.json
  3. if len(os.Args) < 1 {
  4. return
  5. }
  6. if err := config.Init(os.Args[1]); err != nil {
  7. panic(err)
  8. }
  9. // init logger
  10. if err := logger.InitLogger(config.Conf.LogConfig); err != nil {
  11. fmt.Printf("init logger failed, err:%v\n", err)
  12. return
  13. }
  14. r := routes.SetupRouter()
  15. addr := fmt.Sprintf(":%v", config.Conf.ServerConfig.Port)
  16. r.Run(addr)
  17. }

注册中间件的操作在routes.SetupRouter()中:

  1. func SetupRouter() *gin.Engine {
  2. //gin.SetMode(gin.ReleaseMode)
  3. r := gin.New()
  4. r.Use(logger.GinLogger(logger.Logger), logger.GinRecovery(logger.Logger, true))
  5. mainGroup := r.Group("/api")
  6. {
  7. ...
  8. }
  9. r.GET("/ping", func(c *gin.Context) {
  10. c.String(200, "pong")
  11. })
  12. return r
  13. }

更多zap技巧,未完待续…