aboutsummaryrefslogtreecommitdiff
path: root/echo/middleware/json_logger.go
blob: 1aa7e9dc4bcf99df06f75e6d38fb9552ef6144ab (plain)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package middleware

import (
	"encoding/json"
	"io"
	"strings"
	"sync"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

// This is very close in functionality to the echo.Logger middleware
// (it started as a copy) but instead of using string functions to
// write JSON data it uses a proper JSON encoder for safety, speed, and
// simplicity. It also removes color output because it's pointless.

type JsonLoggerConfig struct {
	Skipper middleware.Skipper

	// Tags to construct the logger format.
	//
	// - time_unix
	// - time_unix_milli
	// - time_unix_micro
	// - time_unix_nano
	// - time_rfc3339
	// - time_rfc3339_nano
	// - time_custom
	// - id (Request ID)
	// - remote_ip
	// - uri
	// - host
	// - method
	// - path
	// - protocol
	// - referer
	// - user_agent
	// - status
	// - error
	// - latency (In nanoseconds)
	// - latency_human (Human readable)
	// - bytes_in (Bytes received)
	// - bytes_out (Bytes sent)
	// - header:<NAME>
	// - query:<NAME>
	// - form:<NAME>
	//
	// Optional. Default value DefaultLoggerConfig.Format.
	Format map[string]string

	CustomTimeFormat string
	Output           io.Writer

	encoder *json.Encoder
	pool    *sync.Pool
}

var DefaultLoggerConfig = JsonLoggerConfig{
	Skipper: middleware.DefaultSkipper,
	Format: map[string]string{
		"time":          "time_rfc3339_nano",
		"id":            "id",
		"remote_ip":     "remote_ip",
		"host":          "host",
		"method":        "method",
		"uri":           "uri",
		"user_agent":    "user_agent",
		"status":        "status",
		"error":         "error",
		"latency":       "latency",
		"latency_human": "latency_human",
		"bytes_in":      "bytes_in",
		"bytes_out":     "bytes_out",
	},
	CustomTimeFormat: "2006-01-02 15:04:05.00000",
}

func JsonLoggerWithConfig(config JsonLoggerConfig) echo.MiddlewareFunc {
	if config.Skipper == nil {
		config.Skipper = DefaultLoggerConfig.Skipper
	}
	if config.CustomTimeFormat == "" {
		config.CustomTimeFormat = DefaultLoggerConfig.CustomTimeFormat
	}
	if config.Format == nil {
		panic("LoggerWithConfig: constructed without a logging format")
	}
	if config.Output == nil {
		panic("LoggerWithConfig: constructed without a logging output")
	}

	config.encoder = json.NewEncoder(config.Output)
	config.encoder.SetEscapeHTML(false)

	config.pool = &sync.Pool{
		New: func() any {
			return make(map[string]any, len(config.Format))
		},
	}

	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) (err error) {
			if config.Skipper(c) {
				return next(c)
			}

			req := c.Request()
			res := c.Response()
			start := time.Now()
			if err = next(c); err != nil {
				c.Error(err)
			}
			stop := time.Now()

			template := config.pool.Get().(map[string]any)
			defer config.pool.Put(template)

			for k, v := range config.Format {
				switch v {
				case "time_unix":
					template[k] = time.Now().Unix()
				case "time_unix_milli":
					// go 1.17 or later, it supports time#UnixMilli()
					template[k] = time.Now().UnixNano() / 1000000
				case "time_unix_micro":
					// go 1.17 or later, it supports time#UnixMicro()
					template[k] = time.Now().UnixNano() / 1000
				case "time_unix_nano":
					template[k] = time.Now().UnixNano()
				case "time_rfc3339":
					template[k] = time.Now().Format(time.RFC3339)
				case "time_rfc3339_nano":
					template[k] = time.Now().Format(time.RFC3339Nano)
				case "time_custom":
					template[k] = time.Now().Format(config.CustomTimeFormat)
				case "id":
					id := req.Header.Get(echo.HeaderXRequestID)
					if id == "" {
						id = res.Header().Get(echo.HeaderXRequestID)
					}
					template[k] = id
				case "remote_ip":
					template[k] = c.RealIP()
				case "host":
					template[k] = req.Host
				case "uri":
					template[k] = req.RequestURI
				case "method":
					template[k] = req.Method
				case "path":
					p := req.URL.Path
					if p == "" {
						p = "/"
					}
					template[k] = p
				case "protocol":
					template[k] = req.Proto
				case "referer":
					template[k] = req.Referer()
				case "user_agent":
					template[k] = req.UserAgent()
				case "status":
					template[k] = res.Status
				case "error":
					if err != nil {
						template[k] = err.Error()
					} else {
						template[k] = ""
					}
				case "latency":
					template[k] = stop.Sub(start)
				case "latency_human":
					template[k] = stop.Sub(start).String()
				case "bytes_in":
					cl := req.Header.Get(echo.HeaderContentLength)
					if cl == "" {
						cl = "0"
					}
					template[k] = cl
				case "bytes_out":
					template[k] = res.Size
				default:
					switch {
					case strings.HasPrefix(v, "header:"):
						template[k] = c.Request().Header.Get(v[7:])
					case strings.HasPrefix(v, "query:"):
						template[k] = c.QueryParam(v[6:])
					case strings.HasPrefix(v, "form:"):
						template[k] = c.FormValue(v[5:])
					case strings.HasPrefix(v, "cookie:"):
						cookie, err := c.Cookie(v[7:])
						if err == nil {
							template[k] = cookie.Value
						}
					}
				}
			}

			config.encoder.Encode(template)
			return
		}
	}
}