-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmongorus.go
64 lines (49 loc) · 1.52 KB
/
mongorus.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
package mongorus
import (
"context"
"fmt"
"github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var MongoClient *mongo.Client
type M bson.M
type MongoHook struct {
MongoCollection *mongo.Collection
}
func NewMongoHook(mongoUrl, db, collection string) (*MongoHook, error) {
clientOptions := options.Client().ApplyURI(fmt.Sprintf("mongodb://%s",mongoUrl))
var err error
MongoClient, err = mongo.Connect(context.Background(), clientOptions)
if err != nil {
return nil, err
}
return &MongoHook{MongoCollection: MongoClient.Database(db).Collection(collection)}, nil
}
func NewAuthMongoHook(mongoUrl, db, collection string, auth options.Credential) (*MongoHook, error) {
clientOptions := options.Client().ApplyURI(fmt.Sprintf("mongodb://%s",mongoUrl)).SetAuth(auth)
var err error
MongoClient, err = mongo.Connect(context.Background(), clientOptions)
if err != nil {
return nil, err
}
return &MongoHook{MongoCollection: MongoClient.Database(db).Collection(collection)}, nil
}
func (h *MongoHook)Fire(entry *logrus.Entry) error{
data := make(logrus.Fields)
data["Level"] = entry.Level.String()
data["Time"] = entry.Time.Format("2006-01-02 15:04:05")
data["Message"] = entry.Message
for k, filed := range entry.Data {
data[k] = filed
}
_, err := h.MongoCollection.InsertOne(context.Background(), M(data))
if err != nil {
return err
}
return nil
}
func (h *MongoHook) Levels() []logrus.Level {
return logrus.AllLevels
}