-
Notifications
You must be signed in to change notification settings - Fork 0
/
hook.go
109 lines (91 loc) · 2.15 KB
/
hook.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package boltlogrus
import (
"os"
"github.com/boltdb/bolt"
log "github.com/sirupsen/logrus"
)
//HookOptions is struct to
//give the ability for user
//in order to configure bolt hook
type HookOptions struct {
IDGenerator UniqueID
Dbpath string
FileMode os.FileMode
BoltOptions *bolt.Options
}
//HookOption will handle the options given
type HookOption func(*HookOptions)
//IDGenerator is a function to set
//key generator that will be used
//when we would like to store the log
//inside boltdb
func IDGenerator(uid UniqueID) HookOption {
return func(args *HookOptions) {
args.IDGenerator = uid
}
}
//Dbpath is a function to set the option
func Dbpath(dbpath string) HookOption {
return func(args *HookOptions) {
args.Dbpath = dbpath
}
}
//Filemode sets the filemode used in bolt
func Filemode(filemode os.FileMode) HookOption {
return func(args *HookOptions) {
args.FileMode = filemode
}
}
//BoltOptions set the options used by bolt db
func BoltOptions(opts *bolt.Options) HookOption {
return func(args *HookOptions) {
args.BoltOptions = opts
}
}
type boltHook struct {
db *bolt.DB
idGenerator UniqueID
}
//NewBoltHook will return new hook for logrus
func NewBoltHook(options ...HookOption) log.Hook {
defaultOptions := &HookOptions{
IDGenerator: NewSatoru(),
Dbpath: "log.db",
FileMode: 0600,
BoltOptions: nil,
}
for _, option := range options {
option(defaultOptions)
}
boltDb, err := bolt.Open(defaultOptions.Dbpath, defaultOptions.FileMode, defaultOptions.BoltOptions)
if err != nil {
log.Fatal(err)
}
return &boltHook{boltDb, defaultOptions.IDGenerator}
}
func (bh *boltHook) Fire(entry *log.Entry) error {
err := bh.db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte("logs"))
if err != nil {
return err
}
uid, err := bh.idGenerator.GenerateID()
if err != nil {
return err
}
str, err := entry.String()
if err != nil {
return err
}
err = bucket.Put([]byte(uid), []byte(str))
return err
})
err = bh.Flush()
return err
}
func (bh *boltHook) Levels() []log.Level {
return log.AllLevels
}
func (bh *boltHook) Flush() error {
return bh.db.Close()
}