编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《定制你的 Go Gin 记录器输出格式的方法》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。
如何自定义gin api应用程序的记录器格式?
我尝试使用 logrus 包来做到这一点,但我的问题是:当我故意犯 404 或 400 错误时,控制台中没有打印错误消息。
我还希望记录器在记录器中显示响应正文。
func requestloggingmiddleware(logger *logrus.logger) gin.handlerfunc {
return func(c *gin.context) {
// read the request body
bodybytes, _ := ioutil.readall(c.request.body)
c.request.body = ioutil.nopcloser(bytes.newbuffer(bodybytes))
bodystring := string(bodybytes)
// process request
c.next()
// log request details
// include request error message
logger.withfields(logrus.fields{
"status": c.writer.status(),
"method": c.request.method,
"path": c.request.url.path,
"query_params": c.request.url.query(),
"req_body": bodystring,
// "res_error_1": c.errors.bytype(gin.errortypeprivate).string(),
"res_error_2": c.errors.string(),
}).info("request details")
}
}
func main() {
logrus.info("starting the application...")
// 1. create a new instance of the application.
app := gin.new()
// option 1
logger := logrus.new()
logger.setlevel(logrus.infolevel)
app.use(gin.loggerwithwriter(logger.writer()))
app.use(requestloggingmiddleware(logger))
...
}
这是控制台上显示的内容:
INFO[0015] Request details body="{\"d\":\"D\"}" error= method=POST path=/ping query_params="map[]" status=404正确答案
根据@pratheesh pc的建议,我根据您的需求整理了一个小示例。代码分为三部分:中间件、http 处理程序和主包。让我们从 http 处理程序开始。
handlers/handlers.go 文件
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
type message struct {
name string `json:"name" binding:"required"`
}
func ping(c *gin.context) {
var message message
if err := c.shouldbindbodywith(&message, binding.json); err != nil {
c.json(http.statusbadrequest, err.error())
return
}
c.json(http.statusok, message)
}
这里唯一要提到的是 shouldbindbodywith 方法的使用,该方法使您可以多次读取请求负载。事实上,第一次调用它时(在中间件内),它将请求主体复制到上下文中。后续调用将从那里读取正文(例如 http 处理程序中的调用)。
middlewares/middlewares.go 文件
package middlewares
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
)
type ginbodylogger struct {
// get all the methods implementation from the original one
// override only the write() method
gin.responsewriter
body bytes.buffer
}
func (g *ginbodylogger) write(b []byte) (int, error) {
g.body.write(b)
return g.responsewriter.write(b)
}
func requestloggingmiddleware(logger *logrus.logger) gin.handlerfunc {
return func(ctx *gin.context) {
ginbodylogger := &ginbodylogger{
body: bytes.buffer{},
responsewriter: ctx.writer,
}
ctx.writer = ginbodylogger
var req interface{}
if err := ctx.shouldbindbodywith(&req, binding.json); err != nil {
ctx.json(http.statusbadrequest, err.error())
return
}
data, err := json.marshal(req)
if err != nil {
panic(fmt.errorf("err while marshaling req msg: %v", err))
}
ctx.next()
logger.withfields(log.fields{
"status": ctx.writer.status(),
"method": ctx.request.method,
"path": ctx.request.url.path,
"query_params": ctx.request.url.query(),
"req_body": string(data),
"res_body": ginbodylogger.body.string(),
}).info("request details")
}
}
在这里,我们做了三件主要的事情。
首先,我们定义了 ginbodylogger 结构体,该结构体嵌入了 gin.responsewriter 结构体,并添加了一个 bytes.buffer 来记录我们关心的响应负载。
然后,我们为方法 write 提供了自定义实现,该方法将在写入响应流时调用。在写入之前,我们将信息保存在属于 ginbodylogger 结构体的缓冲区中。
最后,我们通过我们提供给中间件函数的 logger 来跟踪这些信息。
main.go 文件
package main
import (
"ginlogger/handlers"
"ginlogger/middlewares"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
)
var logger *log.Logger
func init() {
logger = logrus.New()
logger.SetLevel(log.InfoLevel)
}
func main() {
gin.SetMode(gin.DebugMode)
r := gin.Default()
r.Use(middlewares.RequestLoggingMiddleware(logger))
r.Use(gin.LoggerWithWriter(logger.Writer()))
r.POST("/ping", handlers.Ping)
r.Run(":8000")
}
main 包负责初始化程序中所需的所有内容。涉及到两个函数:init和main。
在 init 函数中,我们初始化记录器。
在 main 函数中,我们初始化 gin.engine 实例,对其进行检测并运行。
如果您运行代码,您应该会获得所需的日志。如果不是这样,请告诉我,我会回复您,谢谢!
以上就是《定制你的 Go Gin 记录器输出格式的方法》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
