MCPcopy Create free account
hub / github.com/aptly-dev/aptly / JSONLogger

Function JSONLogger

api/middleware.go:84–116  ·  view source on GitHub ↗

JSONLogger is a gin middleware that takes an instance of Logger and uses it for writing access logs that include error messages if there are any.

()

Source from the content-addressed store, hash-verified

82// JSONLogger is a gin middleware that takes an instance of Logger and uses it for writing access
83// logs that include error messages if there are any.
84func JSONLogger() gin.HandlerFunc {
85 return func(c *gin.Context) {
86 // Start timer
87 start := time.Now()
88 path := c.Request.URL.Path
89 raw := c.Request.URL.RawQuery
90
91 // Process request
92 c.Next()
93
94 ts := time.Now()
95 if raw != "" {
96 path = path + "?" + raw
97 }
98
99 errorMessage := strings.TrimSuffix(c.Errors.ByType(gin.ErrorTypePrivate).String(), "\n")
100 l := log.With().Str("remote", c.ClientIP()).Logger().
101 With().Str("method", c.Request.Method).Logger().
102 With().Str("path", path).Logger().
103 With().Str("protocol", c.Request.Proto).Logger().
104 With().Str("code", fmt.Sprint(c.Writer.Status())).Logger().
105 With().Str("latency", ts.Sub(start).String()).Logger().
106 With().Str("agent", c.Request.UserAgent()).Logger()
107
108 if c.Writer.Status() >= 400 && c.Writer.Status() < 500 {
109 l.Warn().Msg(errorMessage)
110 } else if c.Writer.Status() >= 500 {
111 l.Error().Msg(errorMessage)
112 } else {
113 l.Info().Msg(errorMessage)
114 }
115 }
116}

Callers 2

SetUpTestMethod · 0.85
RouterFunction · 0.85

Calls 2

StringMethod · 0.65
ErrorMethod · 0.45

Tested by 1

SetUpTestMethod · 0.68