You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.7 KiB

  1. package logger
  2. import (
  3. "context"
  4. "fmt"
  5. "go.mongodb.org/mongo-driver/mongo"
  6. "go.mongodb.org/mongo-driver/mongo/options"
  7. "strconv"
  8. "time"
  9. )
  10. var (
  11. collectionMap map[string]*mongo.Collection
  12. )
  13. func NewMongoDriver(config db, level int) (driver, error) {
  14. if collectionMap == nil {
  15. collectionMap = make(map[string]*mongo.Collection)
  16. }
  17. var collection *mongo.Collection
  18. mKey := config.Host + strconv.Itoa(config.Port) + config.Database + config.Table
  19. collection = collectionMap[mKey]
  20. if collection == nil {
  21. ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
  22. client, err := mongo.Connect(ctx, options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%d", config.Host, config.Port)))
  23. if err != nil {
  24. return nil, err
  25. }
  26. err = client.Ping(ctx, nil)
  27. if err != nil {
  28. return nil, err
  29. }
  30. collection = client.Database(config.Database).Collection(config.Table)
  31. collectionMap[mKey] = collection
  32. }
  33. return &mongoLogger{
  34. level: level,
  35. collection: collection,
  36. }, nil
  37. }
  38. type mongoLogger struct {
  39. level int
  40. collection *mongo.Collection
  41. }
  42. func (m *mongoLogger) Record(message message) {
  43. if (message.Level == debugLevel || message.Level == DebugLevel) && m.level > debugLevelInt {
  44. return
  45. }
  46. if (message.Level == infoLevel || message.Level == InfoLevel) && m.level > infoLevelInt {
  47. return
  48. }
  49. if (message.Level == warnLevel || message.Level == WarnLevel) && m.level > warnLevelInt {
  50. return
  51. }
  52. if (message.Level == errorLevel || message.Level == ErrorLevel) && m.level > errorLevelInt {
  53. return
  54. }
  55. if (message.Level == fatalLevel || message.Level == FatalLevel) && m.level > fatalLevelInt {
  56. return
  57. }
  58. _, _ = m.collection.InsertOne(context.TODO(), message)
  59. }