Home > Blockchain >  Question about the crud logs with mongo go driver
Question about the crud logs with mongo go driver

Time:11-10

I have a simple CRUD book app with, golang, mongo-go-driver

Want: logs every CRUD actions to a single collection.

e.g:

  1. create a book
  2. insert the book to book collection
  3. insert book.created event to history collection with bookId, timestamp..etc

Questions:

  1. Wondering what is the recommended way to implement this feature?
  2. Is there a hook feature in mongo-go-driver? (hook will be triggered on update event on a collection..etc)

CodePudding user response:

This is currently not supported, and if you think about it, insertion and update may not happen at the driver level, but in the database itself (e.g. an aggregation result may be "dumped" into a collection).

Instead you may take a look at change streams supported by the MongoDB database itself. You may "subscribe" to change events, and when a change operation happens, you'll get notified.

This is not exactly the same what asked, because the source (or cause) of change may not come from your application, so this may or may not be an advantage to you.

You may subscribe to changes of a collection using the Collection.Watch() method. Here's an example from the documentation how to subscribe and get notified of "insert" operations:

var collection *mongo.Collection

// Specify a pipeline that will only match "insert" events.
// Specify the MaxAwaitTimeOption to have each attempt wait two seconds for
// new documents.
matchStage := bson.D{{"$match", bson.D{{"operationType", "insert"}}}}
opts := options.ChangeStream().SetMaxAwaitTime(2 * time.Second)
changeStream, err := collection.Watch(
    context.TODO(),
    mongo.Pipeline{matchStage},
    opts)
if err != nil {
    log.Fatal(err)
}

// Print out all change stream events in the order they're received.
// See the mongo.ChangeStream documentation for more examples of using
// change streams.
for changeStream.Next(context.TODO()) {
    fmt.Println(changeStream.Current)
}

The list of supported operations you may subscribe from the MongoDB docs:

  • insert
  • delete
  • replace
  • update
  • drop
  • rename
  • dropDatabase
  • invalidate

CodePudding user response:

I'm not familiar with Go itself, but the general mongo (client-side) approach for this is command monitoring which I assume go driver also supports. You can read something about it here and here. The event you need is CommandSucceededEvent

  • Related