-
Notifications
You must be signed in to change notification settings - Fork 14
/
db_logger.go
71 lines (53 loc) · 1.64 KB
/
db_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
package requestlogger
import (
"net/http"
"net/http/httputil"
"github.com/latolukasz/beeorm"
"github.com/coretrix/hitrix/pkg/entity"
"github.com/coretrix/hitrix/service/component/clock"
)
type DBLogger struct {
clockService clock.IClock
}
func NewDBLogger(clockService clock.IClock) IRequestLogger {
return &DBLogger{clockService}
}
func (g *DBLogger) LogRequest(ormService *beeorm.Engine, appName, url string, request *http.Request, contentType string) *entity.RequestLoggerEntity {
content, err := httputil.DumpRequest(request, true)
if err != nil {
panic(err)
}
requestLoggerEntity := &entity.RequestLoggerEntity{
URL: url,
AppName: appName,
CreatedAt: g.clockService.Now(),
}
if isText(contentType) && len(content)*4 <= 64000 {
requestLoggerEntity.Request = content
} else {
requestLoggerEntity.Request = []byte("__TOO_LARGE__")
}
ormService.Flush(requestLoggerEntity)
return requestLoggerEntity
}
func (g *DBLogger) LogResponse(ormService *beeorm.Engine, requestLoggerEntity *entity.RequestLoggerEntity, responseBody []byte, status int) {
requestLoggerEntity.Status = status
if len(responseBody) > 0 && len(string(responseBody))*4 <= 64000 {
requestLoggerEntity.Response = responseBody
} else {
requestLoggerEntity.Response = []byte("__TOO_LARGE__")
}
if len(string(requestLoggerEntity.Log))*4 > 64000 {
requestLoggerEntity.Log = []byte("__TOO_LARGE__")
}
ormService.Flush(requestLoggerEntity)
}
func isText(contentType string) bool {
allowedHeaders := map[string]struct{}{
"application/json": {},
"text/plain": {},
"text/html": {},
}
_, ok := allowedHeaders[contentType]
return ok
}