“This is the 27th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge in 2021”

directory

  • preface
  • The body of the
    • Write log file
    • Customize the log output format
  • At the end

preface

Gin is an HTTP Web framework implemented using the pure Golang language. Gin is now widely used for its simple interface design and high performance. The last article covered Gin middleware, and today we’ll take a closer look at Gin’s log management module.

The body of the

Write log file

It is very necessary to have persistent logs on the server, because we need to troubleshoot historical problems, and logs are necessary auxiliary tools. Using the Gin framework, we can do log collection very easily. Here is the sample code:

func main(a) {
    // Do not enable color control
    gin.DisableConsoleColor()

    // Create a log file
    f, _ := os.Create("gin.log")
    gin.DefaultWriter = io.MultiWriter(f)

    // Use the following code to record the log file and display the console synchronously
    // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)

    router := gin.Default()
    router.GET("/ping".func(c *gin.Context) {
        c.String(200."pong")
    })

    router.Run(": 8080")}Copy the code

The above code shows that we have created a log file named gin. Log and bound the output of gin’s own log module to the log file to record historical logs.

Customize the log output format

Now that we have saved logs to a file, can we define the format of the log output? The answer is yes, and we can be very flexible in defining the log output format.

func main(a) {
	router := gin.New()
	router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {

		// Customize the log output format
		return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
				param.ClientIP,
				param.TimeStamp.Format(time.RFC1123),
				param.Method,
				param.Path,
				param.Request.Proto,
				param.StatusCode,
				param.Latency,
				param.Request.UserAgent(),
				param.ErrorMessage,
		)
	}))
        // Apply crash recovery middleware
	router.Use(gin.Recovery())

	router.GET("/ping".func(c *gin.Context) {
		c.String(200."pong")
	})

	router.Run(": 8080")}Copy the code

As shown in the code above, We define log formats including param.clientip (ClientIP), param.timestamp.Format(time.rfc1123) (TimeStamp), param.method (interface request type), param.path (API route), Param.request.Proto (protocol), param.statuscode (result StatusCode, Normal 200), param.latency (Latency), param.request.useragent () (client type), param.errormessage (ErrorMessage).

We have used curl and Chrome to test the effect of the ping interface.

::1 - [Sat, 27 Nov 2021 17:04:22 CST] "GET /ping HTTP/1.1 200 84.952µs "curl/ 5.64.1 "::1 - [Sat, 27 Nov 2021 17:04:22 CST]" 27 Nov 2021 17:21:14 CST] "GET /ping HTTP/1.1 200 53.335µs" Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36" "::1 - [Sat, 27 Nov 2021 17:21:15 CST] "GET /favicon.ico HTTP/1.1 404 650ns" Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36" "Copy the code

Screenshot of demo effect:

From the above results, we can see that our custom log output format has taken effect, OK, we are done!

At the end

Ok, so much for the log management of Gin framework today. If you are interested, do it yourself!

About the author: Hello, everyone, I am Liuzhen007, an audio and video technology fan, CSDN blog expert, Huawei Cloud community cloud sharing expert, signed the author, welcome to follow me to share more dry products!