-
Notifications
You must be signed in to change notification settings - Fork 1
/
logging.go
81 lines (65 loc) · 1.72 KB
/
logging.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
71
72
73
74
75
76
77
78
79
80
81
package server
import (
"context"
"io"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/hashicorp/go-uuid"
"github.com/sirupsen/logrus"
)
type contextKey int
const (
ctxKeyLogger contextKey = iota
)
type oddometer struct {
io.ReadCloser
bytes int
}
func (o *oddometer) Read(p []byte) (int, error) {
n, err := o.ReadCloser.Read(p)
o.bytes += n
return n, err
}
func logging(c *gin.Context) {
start := time.Now()
log := logrus.WithFields(logrus.Fields{
"req_method": c.Request.Method,
"req_url": c.Request.URL.String(),
"req_bytes": c.GetHeader("Content-Length"),
"downstream_remote_addr": c.Request.RemoteAddr,
"x_forwarded_for": c.GetHeader("X-Forwarded-For"),
"user_agent": c.GetHeader("User-Agent"),
})
requestID := c.GetHeader("X-Request-ID")
if requestID == "" {
var err error
requestID, err = uuid.GenerateUUID()
if err != nil {
log.Errorf("Failed to generate UUID for request: %s", err)
}
}
c.Header("X-Request-ID", requestID)
log = log.WithField("id", requestID)
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxKeyLogger, log))
requestRead := oddometer{c.Request.Body, 0}
c.Request.Body = &requestRead
c.Next()
for _, err := range c.Errors {
log.Error(err.Error())
c.String(http.StatusInternalServerError, err.Error())
}
log.WithFields(logrus.Fields{
"req_read": requestRead.bytes,
"res_code": c.Writer.Status(),
"res_bytes": c.Writer.Size(),
"duration": time.Since(start).Seconds(),
}).Info("Request complete")
}
func log(ctx context.Context) logrus.FieldLogger {
log, ok := ctx.Value(ctxKeyLogger).(logrus.FieldLogger)
if !ok {
return logrus.StandardLogger()
}
return log
}