-
Notifications
You must be signed in to change notification settings - Fork 1
/
echolog.go
159 lines (131 loc) · 3.7 KB
/
echolog.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
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
package echolog
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"runtime/debug"
"time"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
// RequestIDHeader is the name of the HTTP Header which contains the request id.
// Exported so that it can be changed by developers
var RequestIDHeader = "X-Request-Id"
type logFields struct {
RemoteIP string
Host string
Method string
Path string
Body string
StatusCode int
Latency float64
Error error
Stack []byte
}
func (l *logFields) MarshalZerologObject(e *zerolog.Event) {
e.
Str("remote_ip", l.RemoteIP).
Str("host", l.Host).
Str("method", l.Method).
Str("path", l.Path).
Str("body", l.Body).
Int("status_code", l.StatusCode).
Float64("latency", l.Latency).
Str("tag", "request")
if l.Error != nil {
e.Err(l.Error)
}
if l.Stack != nil {
e.Bytes("stack", l.Stack)
}
}
// Middleware contains functionality of request_id, logger and recover for request traceability
func Middleware(filter func(c echo.Context) bool) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if filter != nil && filter(c) {
return next(c)
}
// Start timer
start := time.Now()
// Generate request ID
// will search for a request ID header and set into the log context
if c.Request().Header.Get(RequestIDHeader) == "" {
c.Request().Header.Set(RequestIDHeader, uuid.New().String())
}
ctx := log.With().
Str("request_id", c.Request().Header.Get(RequestIDHeader)).
Logger().
WithContext(c.Request().Context())
// Read request body
var buf []byte
if c.Request().Body != nil {
buf, _ = io.ReadAll(c.Request().Body)
// Restore the io.ReadCloser to its original state
c.Request().Body = io.NopCloser(bytes.NewBuffer(buf))
}
// Create log fields
fields := &logFields{
RemoteIP: c.RealIP(),
Method: c.Request().Method,
Host: c.Request().Host,
Path: c.Request().RequestURI,
Body: formatReqBody(buf),
}
defer func() {
rvr := recover()
if rvr != nil {
if rvr == http.ErrAbortHandler {
// We don't recover http.ErrAbortHandler so the response
// to the client is aborted, this should not be logged
panic(rvr)
}
err, ok := rvr.(error)
if !ok {
err = fmt.Errorf("%v", rvr)
}
fields.Error = err
fields.Stack = debug.Stack()
c.Error(err)
}
fields.StatusCode = c.Response().Status
fields.Latency = float64(time.Since(start).Nanoseconds()/1e4) / 100.0
switch {
case rvr != nil:
log.Ctx(ctx).Error().EmbedObject(fields).Msg("panic recover")
case fields.StatusCode >= 500:
log.Ctx(ctx).Error().EmbedObject(fields).Msg("server error")
case fields.StatusCode >= 400:
log.Ctx(ctx).Error().EmbedObject(fields).Msg("client error")
case fields.StatusCode >= 300:
log.Ctx(ctx).Warn().EmbedObject(fields).Msg("redirect")
case fields.StatusCode >= 200:
log.Ctx(ctx).Info().EmbedObject(fields).Msg("success")
case fields.StatusCode >= 100:
log.Ctx(ctx).Info().EmbedObject(fields).Msg("informative")
default:
log.Ctx(ctx).Warn().EmbedObject(fields).Msg("unknown status")
}
}()
newReq := c.Request().WithContext(ctx)
c.SetRequest(newReq)
return next(c)
}
}
}
func formatReqBody(data []byte) string {
var js map[string]interface{}
if json.Unmarshal(data, &js) != nil {
return string(data)
}
result := new(bytes.Buffer)
if err := json.Compact(result, data); err != nil {
log.Error().Err(err).Msg("error compacting body request json")
return ""
}
return result.String()
}