-
Notifications
You must be signed in to change notification settings - Fork 13
/
db_logger.go
68 lines (51 loc) · 1.53 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
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,
Request: content,
CreatedAt: g.clockService.Now(),
}
if isText(contentType) && len(content) <= 16_000_000 {
requestLoggerEntity.RequestText = string(content)
} else {
requestLoggerEntity.Request = content
}
ormService.Flush(requestLoggerEntity)
return requestLoggerEntity
}
func (g *DBLogger) LogResponse(ormService *beeorm.Engine, requestLoggerEntity *entity.RequestLoggerEntity, responseBody []byte, status int) {
requestLoggerEntity.Status = status
if len(string(responseBody)) <= 16_000_000 {
requestLoggerEntity.ResponseText = string(responseBody)
} else {
requestLoggerEntity.Response = responseBody
}
ormService.Flush(requestLoggerEntity)
}
func isText(contentType string) bool {
allowedHeaders := map[string]struct{}{
"application/json": {},
"text/plain": {},
"text/html": {},
}
_, ok := allowedHeaders[contentType]
return ok
}