...

Source file src/go.mongodb.org/mongo-driver/mongo/options/example_test.go

Documentation: go.mongodb.org/mongo-driver/mongo/options

     1  // Copyright (C) MongoDB, Inc. 2023-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  package options_test
     8  
     9  import (
    10  	"bytes"
    11  	"context"
    12  	"fmt"
    13  	"io"
    14  	"log"
    15  	"sync"
    16  
    17  	"go.mongodb.org/mongo-driver/mongo"
    18  	"go.mongodb.org/mongo-driver/mongo/options"
    19  )
    20  
    21  type CustomLogger struct {
    22  	io.Writer
    23  	mu sync.Mutex
    24  }
    25  
    26  func (logger *CustomLogger) Info(level int, msg string, _ ...interface{}) {
    27  	logger.mu.Lock()
    28  	defer logger.mu.Unlock()
    29  
    30  	fmt.Fprintf(logger, "level=%d msg=%s\n", level, msg)
    31  }
    32  
    33  func (logger *CustomLogger) Error(err error, msg string, _ ...interface{}) {
    34  	logger.mu.Lock()
    35  	defer logger.mu.Unlock()
    36  
    37  	fmt.Fprintf(logger, "err=%v msg=%s\n", err, msg)
    38  }
    39  
    40  func ExampleClientOptions_SetLoggerOptions_customLogger() {
    41  	buf := bytes.NewBuffer(nil)
    42  	sink := &CustomLogger{Writer: buf}
    43  
    44  	// Create a client with our logger options.
    45  	loggerOptions := options.
    46  		Logger().
    47  		SetSink(sink).
    48  		SetMaxDocumentLength(25).
    49  		SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug)
    50  
    51  	clientOptions := options.
    52  		Client().
    53  		ApplyURI("mongodb://localhost:27017").
    54  		SetLoggerOptions(loggerOptions)
    55  
    56  	client, err := mongo.Connect(context.TODO(), clientOptions)
    57  
    58  	if err != nil {
    59  		log.Fatalf("error connecting to MongoDB: %v", err)
    60  	}
    61  
    62  	defer func() { _ = client.Disconnect(context.TODO()) }()
    63  
    64  	// Make a database request to test our logging solution.
    65  	coll := client.Database("test").Collection("test")
    66  
    67  	_, err = coll.InsertOne(context.TODO(), map[string]string{"foo": "bar"})
    68  	if err != nil {
    69  		log.Fatalf("InsertOne failed: %v", err)
    70  	}
    71  
    72  	// Print the logs.
    73  	fmt.Println(buf.String())
    74  }
    75  

View as plain text