69 lines
1.4 KiB
Go
Raw Normal View History

2021-12-28 00:52:26 +08:00
package logrusmgo
import (
"github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/mongo"
)
type LogrusMongoHook struct {
col *mongo.Collection
levels []logrus.Level
}
func NewLogrusMongoHook(col *mongo.Collection,
levels ...logrus.Level) *LogrusMongoHook {
return &LogrusMongoHook{
col: col,
levels: levels,
}
}
var _ logrus.Hook = (*LogrusMongoHook)(nil)
func (hook *LogrusMongoHook) Fire(entry *logrus.Entry) error {
doc := make(logrus.Fields)
doc["Level"] = entry.Level.String()
doc["Time"] = entry.Time
doc["Message"] = entry.Message
if caller := entry.Caller; caller != nil {
doc["File"] = caller.File
doc["Line"] = caller.Line
doc["Func"] = caller.Function
}
if data := hook.FieldsData(entry.Data); len(data) > 0 {
doc["Data"] = data
}
_, err := hook.col.InsertOne(entry.Context, doc)
if err != nil {
return err
}
return nil
}
func (hook *LogrusMongoHook) SetLevels(levels ...logrus.Level) {
hook.levels = append(hook.levels, levels...)
}
func (hook *LogrusMongoHook) Levels() []logrus.Level {
if len(hook.levels) == 0 {
return logrus.AllLevels
}
return hook.levels
}
func (hook *LogrusMongoHook) FieldsData(fields logrus.Fields) map[string]interface{} {
data := make(map[string]interface{})
for k, v := range fields {
if errData, isError := v.(error); logrus.ErrorKey == k && v != nil && isError {
data[k] = errData.Error()
} else {
data[k] = v
}
}
return data
}