-
Notifications
You must be signed in to change notification settings - Fork 3
/
exec.go
54 lines (44 loc) · 1005 Bytes
/
exec.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
package hook
import (
"context"
"github.com/abulo/ratel/mongodb"
"github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
)
// ExecCloser 将logrus条目写入数据库并关闭数据库
type ExecCloser interface {
Exec(entry *logrus.Entry) error
}
type defaultExec struct {
sess *mongodb.MongoDB
canClose bool
}
// NewExec create an exec instance
func NewExec(sess *mongodb.MongoDB) ExecCloser {
return &defaultExec{
sess: sess,
canClose: true,
}
}
// NewExecWithURL create an exec instance
func NewExecWithURL(sess *mongodb.MongoDB) ExecCloser {
return &defaultExec{
sess: sess,
canClose: true,
}
}
func (e *defaultExec) Exec(entry *logrus.Entry) error {
item := make(bson.M)
for k, v := range entry.Data {
item[k] = v
}
item["level"] = entry.Level
item["message"] = entry.Message
item["created"] = entry.Time.Unix()
ctx := context.TODO()
_, err := e.sess.Collection("logger").InsertOne(ctx, item)
if err != nil {
return err
}
return nil
}