暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Gin框架如何写日志

go技术沙龙 2020-05-07
1657
简单的日志格式
  1. func main() {

  2. // Disable Console Color, you don't need console color when writing the logs to file.

  3. gin.DisableConsoleColor()


  4. // Logging to a file.

  5. f, _ := os.Create("gin.log")

  6. gin.DefaultWriter = io.MultiWriter(f)


  7. // Use the following code if you need to write the logs to file and console at the same time.

  8. // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)


  9. router := gin.Default()

  10. router.GET("/ping", func(c *gin.Context) {

  11. c.String(200, "pong")

  12. })


  13. router.Run(":8080")

  14. }

日志格式化
  1. func main() {

  2. router := gin.New()


  3. // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter

  4. // By default gin.DefaultWriter = os.Stdout

  5. router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {


  6. // your custom format

  7. return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",

  8. param.ClientIP,

  9. param.TimeStamp.Format(time.RFC1123),

  10. param.Method,

  11. param.Path,

  12. param.Request.Proto,

  13. param.StatusCode,

  14. param.Latency,

  15. param.Request.UserAgent(),

  16. param.ErrorMessage,

  17. )

  18. }))

  19. router.Use(gin.Recovery())


  20. router.GET("/ping", func(c *gin.Context) {

  21. c.String(200, "pong")

  22. })


  23. router.Run(":8080")

  24. }

控制台打印日志着色
  1. 不着色

  2. func main() {

  3. // Disable log's color

  4. gin.DisableConsoleColor()


  5. // Creates a gin router with default middleware:

  6. // logger and recovery (crash-free) middleware

  7. router := gin.Default()


  8. router.GET("/ping", func(c *gin.Context) {

  9. c.String(200, "pong")

  10. })


  11. router.Run(":8080")

  12. }


  13. 着色

  14. func main() {

  15. // Force log's color

  16. gin.ForceConsoleColor()


  17. // Creates a gin router with default middleware:

  18. // logger and recovery (crash-free) middleware

  19. router := gin.Default()


  20. router.GET("/ping", func(c *gin.Context) {

  21. c.String(200, "pong")

  22. })


  23. router.Run(":8080")

  24. }

后面会介绍下,zap,logrus的用法,以及自己写一个日志中间件。


文章转载自go技术沙龙,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论