Skip to content
Myr

Add LoggerWithFormatter method (#1677)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Add LoggerWithFormatter * Add tests for LoggerWithFormatter & LoggerWithConfig * Add note for README * Add tests for DefaultLogFormatter * Add comment * Change DefaultLogFormatter to a private method

authored by Sai · committed by thinkerou · parent cce4958 · Browse files · 3 files+323 added−23 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+323 added−23 removed

  • other:+323 added−23 removed

3 files+323 added−23 removed

modified:logger_test.go+193 added-1 removed
5 unmodified lines
67import (8 "bytes"9 "errors"10 "fmt"11 "net/http"12 "testing"13 "time"1415 "github.com/stretchr/testify/assert"16)17
62 unmodified lines
80 performRequest(router, "GET", "/notfound")81 assert.Contains(t, buffer.String(), "404")82 assert.Contains(t, buffer.String(), "GET")83 assert.Contains(t, buffer.String(), "/notfound")84}8586func TestLoggerWithConfig(t *testing.T) {87 buffer := new(bytes.Buffer)88 router := New()89 router.Use(LoggerWithConfig(LoggerConfig{Output: buffer}))90 router.GET("/example", func(c *Context) {})91 router.POST("/example", func(c *Context) {})92 router.PUT("/example", func(c *Context) {})93 router.DELETE("/example", func(c *Context) {})94 router.PATCH("/example", func(c *Context) {})95 router.HEAD("/example", func(c *Context) {})96 router.OPTIONS("/example", func(c *Context) {})9798 performRequest(router, "GET", "/example?a=100")99 assert.Contains(t, buffer.String(), "200")100 assert.Contains(t, buffer.String(), "GET")101 assert.Contains(t, buffer.String(), "/example")102 assert.Contains(t, buffer.String(), "a=100")103104 // I wrote these first (extending the above) but then realized they are more105 // like integration tests because they test the whole logging process rather106 // than individual functions. Im not sure where these should go.107 buffer.Reset()108 performRequest(router, "POST", "/example")109 assert.Contains(t, buffer.String(), "200")110 assert.Contains(t, buffer.String(), "POST")111 assert.Contains(t, buffer.String(), "/example")112113 buffer.Reset()114 performRequest(router, "PUT", "/example")115 assert.Contains(t, buffer.String(), "200")116 assert.Contains(t, buffer.String(), "PUT")117 assert.Contains(t, buffer.String(), "/example")118119 buffer.Reset()120 performRequest(router, "DELETE", "/example")121 assert.Contains(t, buffer.String(), "200")122 assert.Contains(t, buffer.String(), "DELETE")123 assert.Contains(t, buffer.String(), "/example")124125 buffer.Reset()126 performRequest(router, "PATCH", "/example")127 assert.Contains(t, buffer.String(), "200")128 assert.Contains(t, buffer.String(), "PATCH")129 assert.Contains(t, buffer.String(), "/example")130131 buffer.Reset()132 performRequest(router, "HEAD", "/example")133 assert.Contains(t, buffer.String(), "200")134 assert.Contains(t, buffer.String(), "HEAD")135 assert.Contains(t, buffer.String(), "/example")136137 buffer.Reset()138 performRequest(router, "OPTIONS", "/example")139 assert.Contains(t, buffer.String(), "200")140 assert.Contains(t, buffer.String(), "OPTIONS")141 assert.Contains(t, buffer.String(), "/example")142143 buffer.Reset()144 performRequest(router, "GET", "/notfound")145 assert.Contains(t, buffer.String(), "404")146 assert.Contains(t, buffer.String(), "GET")147 assert.Contains(t, buffer.String(), "/notfound")148}149150func TestLoggerWithFormatter(t *testing.T) {151 buffer := new(bytes.Buffer)152153 d := DefaultWriter154 DefaultWriter = buffer155 defer func() {156 DefaultWriter = d157 }()158159 router := New()160 router.Use(LoggerWithFormatter(func(param LogFormatterParams) string {161 return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %s\n%s",162 param.TimeStamp.Format("2006/01/02 - 15:04:05"),163 param.StatusCode,164 param.Latency,165 param.ClientIP,166 param.Method,167 param.Path,168 param.ErrorMessage,169 )170 }))171 router.GET("/example", func(c *Context) {})172 performRequest(router, "GET", "/example?a=100")173174 // output test175 assert.Contains(t, buffer.String(), "[FORMATTER TEST]")176 assert.Contains(t, buffer.String(), "200")177 assert.Contains(t, buffer.String(), "GET")178 assert.Contains(t, buffer.String(), "/example")179 assert.Contains(t, buffer.String(), "a=100")180}181182func TestLoggerWithConfigFormatting(t *testing.T) {183 var gotParam LogFormatterParams184 buffer := new(bytes.Buffer)185186 router := New()187 router.Use(LoggerWithConfig(LoggerConfig{188 Output: buffer,189 Formatter: func(param LogFormatterParams) string {190 // for assert test191 gotParam = param192193 return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %s\n%s",194 param.TimeStamp.Format("2006/01/02 - 15:04:05"),195 param.StatusCode,196 param.Latency,197 param.ClientIP,198 param.Method,199 param.Path,200 param.ErrorMessage,201 )202 },203 }))204 router.GET("/example", func(c *Context) {205 // set dummy ClientIP206 c.Request.Header.Set("X-Forwarded-For", "20.20.20.20")207 })208 performRequest(router, "GET", "/example?a=100")209210 // output test211 assert.Contains(t, buffer.String(), "[FORMATTER TEST]")212 assert.Contains(t, buffer.String(), "200")213 assert.Contains(t, buffer.String(), "GET")214 assert.Contains(t, buffer.String(), "/example")215 assert.Contains(t, buffer.String(), "a=100")216217 // LogFormatterParams test218 assert.NotNil(t, gotParam.Request)219 assert.NotEmpty(t, gotParam.TimeStamp)220 assert.Equal(t, 200, gotParam.StatusCode)221 assert.NotEmpty(t, gotParam.Latency)222 assert.Equal(t, "20.20.20.20", gotParam.ClientIP)223 assert.Equal(t, "GET", gotParam.Method)224 assert.Equal(t, "/example?a=100", gotParam.Path)225 assert.Empty(t, gotParam.ErrorMessage)226227}228229func TestDefaultLogFormatter(t *testing.T) {230 timeStamp := time.Unix(1544173902, 0).UTC()231232 termFalseParam := LogFormatterParams{233 TimeStamp: timeStamp,234 StatusCode: 200,235 Latency: time.Second * 5,236 ClientIP: "20.20.20.20",237 Method: "GET",238 Path: "/",239 ErrorMessage: "",240 IsTerm: false,241 }242243 termTrueParam := LogFormatterParams{244 TimeStamp: timeStamp,245 StatusCode: 200,246 Latency: time.Second * 5,247 ClientIP: "20.20.20.20",248 Method: "GET",249 Path: "/",250 ErrorMessage: "",251 IsTerm: true,252 }253254 assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 5s | 20.20.20.20 | GET /\n", defaultLogFormatter(termFalseParam))255256 assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m| 5s | 20.20.20.20 |\x1b[97;44m GET \x1b[0m /\n", defaultLogFormatter(termTrueParam))257}258259func TestColorForMethod(t *testing.T) {260 assert.Equal(t, string([]byte{27, 91, 57, 55, 59, 52, 52, 109}), colorForMethod("GET"), "get should be blue")261 assert.Equal(t, string([]byte{27, 91, 57, 55, 59, 52, 54, 109}), colorForMethod("POST"), "post should be cyan")262 assert.Equal(t, string([]byte{27, 91, 57, 48, 59, 52, 51, 109}), colorForMethod("PUT"), "put should be yellow")
37 unmodified lines
300 assert.Equal(t, http.StatusInternalServerError, w.Code)301 assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String())302}303130func TestSkippingPaths(t *testing.T) {304func TestLoggerWithWriterSkippingPaths(t *testing.T) {305 buffer := new(bytes.Buffer)306 router := New()307 router.Use(LoggerWithWriter(buffer, "/skipped"))308 router.GET("/logged", func(c *Context) {})
6 unmodified lines
315 performRequest(router, "GET", "/skipped")316 assert.Contains(t, buffer.String(), "")317}318319func TestLoggerWithConfigSkippingPaths(t *testing.T) {320 buffer := new(bytes.Buffer)321 router := New()322 router.Use(LoggerWithConfig(LoggerConfig{323 Output: buffer,324 SkipPathes: []string{"/skipped"},325 }))326 router.GET("/logged", func(c *Context) {})327 router.GET("/skipped", func(c *Context) {})328329 performRequest(router, "GET", "/logged")330 assert.Contains(t, buffer.String(), "200")331332 buffer.Reset()333 performRequest(router, "GET", "/skipped")334 assert.Contains(t, buffer.String(), "")335}336337func TestDisableConsoleColor(t *testing.T) {338 New()339 assert.False(t, disableColor)340 DisableConsoleColor()
2 unmodified lines
modified:logger.go+92 added-22 removed
24 unmodified lines
25 reset = string([]byte{27, 91, 48, 109})26 disableColor = false27)2829// LoggerConfig defines the config for Logger middleware.30type LoggerConfig struct {31 // Optional. Default value is gin.defaultLogFormatter32 Formatter LogFormatter3334 // Output is a writer where logs are written.35 // Optional. Default value is gin.DefaultWriter.36 Output io.Writer3738 // SkipPathes is a url path array which logs are not written.39 // Optional.40 SkipPathes []string41}4243// LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter44type LogFormatter func(params LogFormatterParams) string4546// LogFormatterParams is the structure any formatter will be handed when time to log comes47type LogFormatterParams struct {48 Request *http.Request49 TimeStamp time.Time50 StatusCode int51 Latency time.Duration52 ClientIP string53 Method string54 Path string55 ErrorMessage string56 IsTerm bool57}5859// defaultLogFormatter is the default log format function Logger middleware uses.60var defaultLogFormatter = func(param LogFormatterParams) string {61 var statusColor, methodColor, resetColor string62 if param.IsTerm {63 statusColor = colorForStatus(param.StatusCode)64 methodColor = colorForMethod(param.Method)65 resetColor = reset66 }6768 return fmt.Sprintf("[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %s\n%s",69 param.TimeStamp.Format("2006/01/02 - 15:04:05"),70 statusColor, param.StatusCode, resetColor,71 param.Latency,72 param.ClientIP,73 methodColor, param.Method, resetColor,74 param.Path,75 param.ErrorMessage,76 )77}7879// DisableConsoleColor disables color output in the console.80func DisableConsoleColor() {81 disableColor = true82}
16 unmodified lines
99100// Logger instances a Logger middleware that will write the logs to gin.DefaultWriter.101// By default gin.DefaultWriter = os.Stdout.102func Logger() HandlerFunc {53 return LoggerWithWriter(DefaultWriter)103 return LoggerWithConfig(LoggerConfig{})104}105106// LoggerWithFormatter instance a Logger middleware with the specified log format function.107func LoggerWithFormatter(f LogFormatter) HandlerFunc {108 return LoggerWithConfig(LoggerConfig{109 Formatter: f,110 })111}112113// LoggerWithWriter instance a Logger middleware with the specified writer buffer.114// Example: os.Stdout, a file opened in write mode, a socket...115func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {116 return LoggerWithConfig(LoggerConfig{117 Output: out,118 SkipPathes: notlogged,119 })120}121122// LoggerWithConfig instance a Logger middleware with config.123func LoggerWithConfig(conf LoggerConfig) HandlerFunc {124 formatter := conf.Formatter125 if formatter == nil {126 formatter = defaultLogFormatter127 }128129 out := conf.Output130 if out == nil {131 out = DefaultWriter132 }133134 notlogged := conf.SkipPathes135136 isTerm := true137138 if w, ok := out.(*os.File); !ok ||139 (os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd()))) ||
21 unmodified lines
161 c.Next()162163 // Log only when path is not being skipped164 if _, ok := skip[path]; !ok {165 param := LogFormatterParams{166 Request: c.Request,167 IsTerm: isTerm,168 }169170 // Stop timer89 end := time.Now()90 latency := end.Sub(start)171 param.TimeStamp = time.Now()172 param.Latency = param.TimeStamp.Sub(start)17392 clientIP := c.ClientIP()93 method := c.Request.Method94 statusCode := c.Writer.Status()95 var statusColor, methodColor, resetColor string96 if isTerm {97 statusColor = colorForStatus(statusCode)98 methodColor = colorForMethod(method)99 resetColor = reset100 }101 comment := c.Errors.ByType(ErrorTypePrivate).String()174 param.ClientIP = c.ClientIP()175 param.Method = c.Request.Method176 param.StatusCode = c.Writer.Status()177 param.ErrorMessage = c.Errors.ByType(ErrorTypePrivate).String()178179 if raw != "" {180 path = path + "?" + raw181 }182107 fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %s\n%s",108 end.Format("2006/01/02 - 15:04:05"),109 statusColor, statusCode, resetColor,110 latency,111 clientIP,112 methodColor, method, resetColor,113 path,114 comment,115 )183 param.Path = path184185 fmt.Fprintf(out, formatter(param))186 }187 }188}189
33 unmodified lines
modified:README.md+38 added
33 unmodified lines
34 - [Grouping routes](#grouping-routes)35 - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default)36 - [Using middleware](#using-middleware)37 - [How to write log file](#how-to-write-log-file)38 - [Custom Log Format](#custom-log-format)39 - [Model binding and validation](#model-binding-and-validation)40 - [Custom Validators](#custom-validators)41 - [Only Bind Query String](#only-bind-query-string)42 - [Bind Query String or Post Data](#bind-query-string-or-post-data)
485 unmodified lines
528    router.Run(":8080")529}530```531532### Custom Log Format533```go534func main() {535 router := gin.New()536537 // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter538 // By default gin.DefaultWriter = os.Stdout539 router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {540541 // your custom format542 return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",543 param.ClientIP,544 param.TimeStamp.Format(time.RFC1123),545 param.Method,546 param.Path,547 param.Request.Proto,548 param.StatusCode,549 param.Latency,550 param.Request.UserAgent(),551 param.ErrorMessage,552 )553 }))554 router.Use(gin.Recovery())555556 router.GET("/ping", func(c *gin.Context) {557 c.String(200, "pong")558 })559560 router.Run(":8080")561}562```563564**Sample Output**565```566::1 - [Fri, 07 Dec 2018 17:04:38 JST] "GET /ping HTTP/1.1 200 122.767µs "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36" "567```568569### Model binding and validation570571To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML and standard form values (foo=bar&boo=baz).572
1470 unmodified lines