forked from trK54Ylmz/logrus-boltdb-hook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhook.go
More file actions
68 lines (53 loc) · 1.17 KB
/
hook.go
File metadata and controls
68 lines (53 loc) · 1.17 KB
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 logrusbolt
import (
"fmt"
"github.com/coreos/bbolt"
"github.com/sirupsen/logrus"
"math/rand"
"time"
)
const (
format = "2006-01-02 15:04:05.000000000"
)
type BoltHook struct {
DBLoc string
Bucket string
Formatter logrus.Formatter
db *bolt.DB
}
// Creates a hook for instance of logrus logger
func NewHook(b BoltHook) (*BoltHook, error) {
boltDB, err := bolt.Open(b.DBLoc, 0600, nil)
if err != nil {
return nil, err
}
return &BoltHook{
DBLoc: b.DBLoc,
Bucket: b.Bucket,
Formatter: b.Formatter,
db: boltDB,
}, nil
}
// Formats boltdb key
func (b *BoltHook) now() string {
return time.Now().Format(format) + "." + fmt.Sprint(rand.Uint32())
}
// Calls Fire method when event is fired
func (b *BoltHook) Fire(e *logrus.Entry) error {
return b.db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte(b.Bucket))
if err != nil {
return err
}
bytes, err := b.Formatter.Format(e)
if err != nil {
return err
}
bucket.Put([]byte(b.now()), bytes)
return nil
})
}
// Returns the available logging levels in logrus
func (b *BoltHook) Levels() []logrus.Level {
return logrus.AllLevels
}