-
Notifications
You must be signed in to change notification settings - Fork 52
/
logger.go
70 lines (57 loc) · 2.28 KB
/
logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package mid
import (
"fmt"
"time"
"github.com/sirupsen/logrus"
"github.com/valyala/fasthttp"
"github.com/wallarm/api-firewall/internal/platform/router"
"github.com/wallarm/api-firewall/internal/platform/web"
)
// Logger writes some information about the request to the logs in the
// format: TraceID : (200) GET /foo -> IP ADDR (latency)
func Logger(logger *logrus.Logger) web.Middleware {
// This is the actual middleware function to be executed.
m := func(before router.Handler) router.Handler {
// Create the handler that will be attached in the middleware chain.
h := func(ctx *fasthttp.RequestCtx) error {
start := time.Now()
logger.WithFields(logrus.Fields{
"request_id": ctx.UserValue(web.RequestID),
"method": string(ctx.Request.Header.Method()),
"path": string(ctx.Path()),
"uri": string(ctx.Request.URI().RequestURI()),
"client_address": ctx.RemoteAddr(),
}).Debug("Received request from client")
err := before(ctx)
// check method and path
if isProxyNoRouteValue := ctx.Value(web.RequestProxyNoRoute); isProxyNoRouteValue != nil {
if isProxyNoRouteValue.(bool) {
logger.WithFields(logrus.Fields{
"request_id": ctx.UserValue(web.RequestID),
"status_code": ctx.Response.StatusCode(),
"response_length": fmt.Sprintf("%d", ctx.Response.Header.ContentLength()),
"method": string(ctx.Request.Header.Method()),
"path": string(ctx.Path()),
"uri": string(ctx.Request.URI().RequestURI()),
"client_address": ctx.RemoteAddr(),
}).Error("Method or path not found in the OpenAPI specification")
}
}
logger.WithFields(logrus.Fields{
"request_id": ctx.UserValue(web.RequestID),
"status_code": ctx.Response.StatusCode(),
"method": string(ctx.Request.Header.Method()),
"path": string(ctx.Path()),
"uri": string(ctx.Request.URI().RequestURI()),
"client_address": ctx.RemoteAddr(),
"processing_time": time.Since(start),
}).Debug("Sending response to client")
// log all information about the request
web.LogRequestResponseAtTraceLevel(ctx, logger)
// Return the error, so it can be handled further up the chain.
return err
}
return h
}
return m
}