-
Notifications
You must be signed in to change notification settings - Fork 13
/
request_logger.go
81 lines (60 loc) · 1.95 KB
/
request_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
75
76
77
78
79
80
81
package middleware
import (
"encoding/json"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/coretrix/hitrix/pkg/entity"
"github.com/coretrix/hitrix/pkg/response"
"github.com/coretrix/hitrix/service"
requestlogger "github.com/coretrix/hitrix/service/component/request_logger"
)
type dbLogger struct {
disabled bool
logs []map[string]interface{}
}
func (l *dbLogger) Disable() {
l.disabled = true
}
func (l *dbLogger) Handle(data map[string]interface{}) {
if l.disabled {
return
}
l.logs = append(l.logs, data)
}
func RequestLogger(ginEngine *gin.Engine, extender func(context *gin.Context, requestEntity *entity.RequestLoggerEntity)) {
ormConfig := service.DI().OrmConfig()
entities := ormConfig.GetEntities()
if _, ok := entities["entity.RequestLoggerEntity"]; !ok {
panic("you should register RequestLoggerEntity")
}
ginEngine.Use(func(context *gin.Context) {
requestStart := time.Now()
ormService := service.DI().OrmEngineForContext(context.Request.Context())
requestLoggerService := service.DI().RequestLogger()
requestLoggerEntity := requestLoggerService.LogRequest(
ormService,
service.DI().App().Name,
context.Request.URL.String(),
context.Request,
context.ContentType(),
)
context.Set(requestlogger.ID, requestLoggerEntity.ID)
context.Header("X-Request-ID", strconv.FormatUint(requestLoggerEntity.ID, 10))
logger := &dbLogger{}
ormService.RegisterQueryLogger(logger, true, true, true)
context.Next()
//nolint //a
requestLoggerEntity.RequestDuration = time.Now().Sub(requestStart).Milliseconds()
logger.Disable()
encoded, err := json.Marshal(logger.logs)
if err != nil {
return
}
extender(context, requestLoggerEntity)
responseBody, _ := context.Get(response.ResponseBody)
responseBodyByte, _ := json.Marshal(responseBody)
requestLoggerEntity.Log = encoded
requestLoggerService.LogResponse(ormService, requestLoggerEntity, responseBodyByte, context.Writer.Status())
})
}