Mongodb go driver

How can I enable logging or set a logger in go driver?

Hi @Chaoxing_Xian,

Welcome to the MongoDB Community forums :sparkles:

Here is the code snippet which connects to a MongoDB instance using the MongoDB Golang driver and logs all the steps in a text file:

package main

import (
	"context"
	"log"
	"os"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var (
	WarningLogger *log.Logger
	InfoLogger    *log.Logger
	ErrorLogger   *log.Logger
)

func init() {
	file, err := os.OpenFile("logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		log.Fatal(err)
	}

	InfoLogger = log.New(file, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
	WarningLogger = log.New(file, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile)
	ErrorLogger = log.New(file, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
}

func main() {
	// Set up MongoDB client options
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	// Connect to MongoDB
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	client, err := mongo.Connect(ctx, clientOptions)
	if err != nil {
		ErrorLogger.Println(err)
	}
	defer func() {
		if err = client.Disconnect(ctx); err != nil {
			ErrorLogger.Println(err)
		}
	}()

	// Ping the MongoDB server to verify that the connection is established
	if err = client.Ping(ctx, nil); err != nil {
		ErrorLogger.Println(err)
	} else {
		InfoLogger.Println("Connected to MongoDB!")
	}

	// Access a database and a collection
	db := client.Database("mydatabase")
	collection := db.Collection("mycollection")

	// Insert a document into the collection
	res, err := collection.InsertOne(ctx, map[string]string{"name": "John Doe", "email": "johndoe@example.com"})
	if err != nil {
		ErrorLogger.Println(err)
	} else {
		InfoLogger.Printf("Inserted document with ID %v\n", res.InsertedID)
	}

	// Find a document in the collection
	var result map[string]string
	filter := map[string]string{"name": "John Doe"}
	err = collection.FindOne(ctx, filter).Decode(&result)
	if err != nil {
		ErrorLogger.Println(err)
	} else {
		InfoLogger.Printf("Found document: %v\n", result)
	}

	// Disconnect from MongoDB
	if err = client.Disconnect(ctx); err != nil {
		ErrorLogger.Println(err)
	} else {
		InfoLogger.Println("Disconnected from MongoDB")
	}
}

It outputs the following:

INFO: 2023/03/07 11:46:20 hello.go:51: Connected to MongoDB!
INFO: 2023/03/07 11:46:20 hello.go:63: Inserted document with ID ObjectID("6406d6b4b8e2aafb98416f08")
INFO: 2023/03/07 11:46:20 hello.go:73: Found document: map[_id:6406d6b4b8e2aafb98416f08 email:johndoe@example.com name:John Doe]
INFO: 2023/03/07 11:46:20 hello.go:88: Disconnected from MongoDB
ERROR: 2023/03/07 11:46:20 hello.go:43: client is disconnected

This uses MongoDB’s official Go driver to connect to a local MongoDB instance. It creates a context with a timeout of 10 seconds to manage the connection and disconnection. It uses the log package to log all the steps to a text file named logs.txt .

I hope it helps!

Regards,
Kushagra

Appreciate your apply, actually I tried to ask ChatGPT and got the below answer:

package main

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"os"
)

type customLogger struct {}

func (l *customLogger) Logf(level mongo.Level, format string, args ...interface{}) {
	log.Printf("MongoDB %s: %s\n", level, fmt.Sprintf(format, args...))
}

func main() {
	// Create a new client with the logger set
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017").SetAppName("my-app").SetLogger(&customLogger{}))
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	
	// Connect to MongoDB
	err = client.Connect(context.Background())
	if err != nil {
		log.Fatalf("Failed to connect to MongoDB: %v", err)
	}
	defer client.Disconnect(context.Background())
	
	// Use the client to perform operations on the database
	// ...
}

I initially believed that I had found the solution I needed, but it appears that the ‘SetLogger’ method suggested by ChatGPT is no longer available. So my new question is: Does the Go driver not generate any logs at all?

Hi :wave: @Chaoxing_Xian,

From my understanding, the MongoDB Go Driver has the capability to generate logs. Here is the documentation link where you can learn about various error logs that can be generated by the MongoDB Go driver.

In general, the drivers generate the logs to notify the user of any issues that may arise within the development. However, if you want to customize the logs according to your specific needs or preferences, you can use the log package of Golang, as I’ve shared in the above response.

Let us know if you have any further questions!

Best,
Kushagra

I think I’ve got my answer, thanks~

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.