-
Notifications
You must be signed in to change notification settings - Fork 14
/
api_logger.go
80 lines (62 loc) · 1.62 KB
/
api_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
package apilogger
import (
"reflect"
"time"
"github.com/latolukasz/orm"
)
type LogEntity interface {
orm.Entity
SetID(value uint64)
SetType(value string)
SetStatus(value string)
SetRequest(value interface{})
SetResponse(value interface{})
SetMessage(value string)
SetCreatedAt(value time.Time)
}
type APILogger interface {
LogStart(logType string, request interface{})
LogError(message string, response interface{})
LogSuccess(response interface{})
}
type DBLog struct {
ormService *orm.Engine
logEntity LogEntity
currentLog LogEntity
}
func NewAPILog(ormService *orm.Engine, entity LogEntity) APILogger {
return &DBLog{ormService: ormService, logEntity: entity}
}
func (l *DBLog) LogStart(logType string, request interface{}) {
var logEntity LogEntity
if l.logEntity.GetID() == 0 {
logEntity = l.logEntity
} else {
logEntity = reflect.New(reflect.ValueOf(l.logEntity).Elem().Type()).Interface().(LogEntity)
}
logEntity.SetType(logType)
logEntity.SetRequest(request)
logEntity.SetStatus("new")
logEntity.SetCreatedAt(time.Now())
l.ormService.Flush(logEntity)
l.currentLog = logEntity
}
func (l *DBLog) LogError(message string, response interface{}) {
if l.currentLog == nil {
panic("log is not created")
}
currentLog := l.currentLog
currentLog.SetMessage(message)
currentLog.SetResponse(response)
currentLog.SetStatus("failed")
l.ormService.Flush(currentLog)
}
func (l *DBLog) LogSuccess(response interface{}) {
if l.currentLog == nil {
panic("log is not created")
}
currentLog := l.currentLog
currentLog.SetStatus("completed")
currentLog.SetResponse(response)
l.ormService.Flush(currentLog)
}