-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
74 lines (69 loc) · 1.51 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
71
72
73
74
package middlewares
import (
"encoding/json"
"github.com/dpwgc/easierweb"
"log/slog"
"time"
)
func Logger() easierweb.Handle {
return func(ctx *easierweb.Context) {
start := time.Now().UnixMilli()
ctx.Next()
end := time.Now().UnixMilli()
timeCost := end - start
path := ""
query := ""
form := ""
body := ""
result := ""
if len(ctx.Path) > 0 {
marshal, err := json.Marshal(ctx.Path)
if err != nil {
path = err.Error()
} else {
path = string(marshal)
}
}
if len(ctx.Query) > 0 {
marshal, err := json.Marshal(ctx.Query)
if err != nil {
query = err.Error()
} else {
query = string(marshal)
}
}
if len(ctx.Form) > 0 {
marshal, err := json.Marshal(ctx.Form)
if err != nil {
form = err.Error()
} else {
form = string(marshal)
}
}
sizeLimit := 1024 * 1024
if len(ctx.Body) > 0 {
if len(ctx.Body) > sizeLimit {
body = "body is too large"
} else {
body = string(ctx.Body)
}
}
if len(ctx.Result) > 0 {
if len(ctx.Result) > sizeLimit {
result = "result is too large"
} else {
result = string(ctx.Result)
}
}
ctx.Logger.Info(ctx.Proto(), slog.String("method", ctx.Request.Method),
slog.String("url", ctx.Request.URL.String()),
slog.String("client", ctx.Request.RemoteAddr),
slog.String("path", path),
slog.String("query", query),
slog.String("form", form),
slog.String("body", body),
slog.Int("code", ctx.Code),
slog.String("result", result),
slog.Int64("timeCost", timeCost))
}
}