aboutsummaryrefslogtreecommitdiff
path: root/api/logger.go
blob: ea7266ba4fe450e4bb406afe7dee7adb693d2b86 (plain) (blame)
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
package api

import (
	"fmt"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/gin-gonic/gin"
	"github.com/jloup/utils"
)

var log = utils.StandardL().WithField("module", "api")

func SetContextLogField(c *gin.Context, field string, value interface{}) {
	itf, ok := c.Get("logFields")
	var fields map[string]interface{}
	if !ok {
		fields = make(map[string]interface{})
	} else {
		fields = itf.(map[string]interface{})
	}

	fields[field] = value
	c.Set("logFields", fields)
}

func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.Request.URL.Path
		rawQuery := c.Request.URL.RawQuery
		start := time.Now()

		c.Next()

		latency := time.Now().Sub(start).Round(10 * time.Microsecond)
		code := c.Writer.Status()

		l := log
		l = l.WithField("latency", latency)
		l = l.WithField("client_ip", c.ClientIP())
		l = l.WithField("method", c.Request.Method)
		l = l.WithField("status_code", code)

		if itf, ok := c.Get("logFields"); ok {
			for field, value := range itf.(map[string]interface{}) {
				l = l.WithField(field, value)
			}
		}

		if rawQuery != "" {
			path = fmt.Sprintf("%s?%s", path, rawQuery)
		}

		l = l.WithField("path", path)

		msgLog := fmt.Sprintf("[%v] %d %s '%s'", latency, code, c.Request.Method, path)

		var level logrus.Level
		switch {
		case code >= 200 && code < 400:
			level = logrus.DebugLevel
		case code >= 400 && code < 500:
			level = logrus.InfoLevel
		default:
			level = logrus.ErrorLevel
		}

		errors := c.Errors.ByType(gin.ErrorTypePrivate)

		for _, err := range errors {
			l.WithField("description", err.Err).Logf(level, "%s: %s", msgLog, err.Err)
		}

		if errors == nil {
			l.Logf(level, msgLog)
		}
	}
}