Overview
このガイドでは、ドライバーを使用してアプリケーションのログを構成する方法を学習できます。 ロギングの目的は、ドライバー イベントを記録することです。
ロガーは、指定可能な重大度または冗長レベルでメッセージをログに記録します。 アプリケーションでロガーを有効にすると、アプリケーションのアクティビティに関する情報を高レベル、詳細レベル、またはその両方で受け取ることができます。
Tip
ロギング重大度レベルの詳細については、メッセージ ロギング用の Syslog 標準に関する Wikipedia のエントリを参照してください。
ログを有効にする
Clientインスタンスでロガーを構成するには、 ClientOptionsオブジェクトの作成時にSetLoggerOptions()メソッドを呼び出します。 SetLoggerOptions()メソッドはLoggerOptions型をパラメーターとして受け取ります。 アプリケーションのロガーを構成するには、このLoggerOptionsタイプを設定します。
次のコードは、ログ記録を有効にしてクライアントを作成する方法を示しています。
loggerOptions := options. Logger(). SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug) clientOptions := options. Client(). ApplyURI(uri). SetLoggerOptions(loggerOptions) client, err := mongo.Connect(clientOptions)
ロガーを構成する
LoggerOptionsオブジェクトを作成するには、 options.Logger()メソッドを呼び出します。 次の表では、 LoggerOptions型のプロパティを設定してロガーを構成する方法について説明します。 最初の列にはLoggerOptionsプロパティが一覧表示され、2 番目の列にはプロパティが説明され、3 番目の列には各プロパティに対応する setter メソッドとパラメーターが一覧表示されています。
プロパティ | 説明 | セッター メソッド |
|---|---|---|
ComponentLevelsType: map[LogComponent]LogLevel | A mapping of components to log severity levels. The driver uses the
LogLevel for each LogComponent to determine if the log
message is generated.To learn more about the LogComponent and LogLevel types, see
the Log Components and Severity Levels
section of this guide. | SetComponentLevel()Parameters: LogComponent, LogLevel |
SinkType: LogSink | The logging interface that the driver uses to log messages.
The LogSink type is an interface that you can implement to
provide a custom sink or integrate a third-party
logger for the driver's logs. If you don't set this
property, the driver uses the standard logging library.To learn more, see the Use a Custom Logger and Integrate Third-Party
Loggers sections of this guide. | SetSink()Parameter: LogSink |
MaxDocumentLengthType: uintDefault: 1000 | The maximum length in bytes of each log message that the driver emits. If the
message is larger than this value, the driver
truncates it and appends ellipses to the partial log message. | SetMaxDocumentLength()Parameter: uint |
Tip
特定のファイルへのログの書き込み
デフォルトでは、標準ロガーはコンソールにメッセージを記録します( stderr )。 ロギング先を指定するには、 MONGODB_LOG_PATH環境変数をstdoutまたはファイルパスに設定します。
ログ コンポーネントと重大度レベル
ドライバーがログに記録するコンポーネントを指定するには、 LogComponentタイプを設定します。 次の表では、 LogComponentの組み込み仕様を説明しています。
設定 | 説明 | 列挙値 |
|---|---|---|
| すべてのコンポーネントのログ記録を有効にします |
|
| コマンドモニターのログ記録 を有効にします |
|
| トポロジーのログ作成 を有効にします |
|
| サーバー選択のログ記録 を有効にします |
|
| 接続サービスのログ記録を有効にします |
|
設定名またはその列挙値を使用して、ログ コンポーネントを指定できます。 次のコードは、コマンド監視を有効にする同等の方法を示しています。
// Using named value comp := options.LogComponentCommand // Using enumeration comp := options.LogComponent(1)
ログ重大度レベルを指定するには、 LogLevelタイプを設定します。 次のコードは、 LevelDebugレベルでロギングを有効にする方法を示しています。
lvl := options.LogLevelDebug
重要
Goドライバーは現在、LevelDebug レベルのメッセージのみを発行していますが、LogLevel の他の仕様をサポートしています。詳しくは、LogLevel APIドキュメント を参照してください。
例
この例では、次の仕様で標準ロガーを構成する方法を示します。
ドキュメントの最大長は
25バイトです。ログ コンポーネントは
LogComponentCommandです。ロギングの重大度レベルは
LevelDebugです。
loggerOptions := options. Logger(). SetMaxDocumentLength(25). SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug) // Creates options that include the logger specification clientOptions := options. Client(). ApplyURI(uri). SetLoggerOptions(loggerOptions)
次のコードは挿入操作を実行し、ログ メッセージを生成します。
type Item struct { Name string } coll := client.Database("db").Collection("testColl") _, err = coll.InsertOne(context.TODO(), Item{Name: "grapefruit"})
{"command":"{\"insert\": \"testColl\",\"or...","commandName":"insert","databaseName":"db","driverConnectionId":1,"message":"Command started","operationId":0,"requestId":13,"serverConnectionId":97377,"serverHost":"...","serverPort":27017,"timestamp":...} {"commandName":"insert","driverConnectionId":1,"durationMS":19,"message":"Command succeeded","operationId":0,"reply":"{\"n\": {\"$numberInt\":\"1\"},...","requestId":13,"serverConnectionId":97377,"serverHost":"...","serverPort":27017,"timestamp":...}
カスタム ロガーの使用
標準のログ ライブラリがニーズに合わない場合は、カスタム ロガーを実装できます。 ロギング構成をカスタマイズすることで、ログ メッセージの内容、形式、頻度をより詳細に制御できます。
カスタムInfo() Error()ロガーを使用するには、ロガー構造体を定義し、その構造体に メソッドと メソッドを実装します。次に、 LoggerOptionsインスタンスでSetSink()メソッドを呼び出して、ロガーをClientのLogSinkとして設定します。
例
この例では、カスタム ロガーを定義して実装する方法を示します。
Info()Error()カスタムログメッセージ形式を使用して メソッドと メソッドを実装します。
func (logger *CustomLogger) Info(level int, msg string, _ ...interface{}) { logger.mu.Lock() defer logger.mu.Unlock() if options.LogLevel(level+1) == options.LogLevelDebug { fmt.Fprintf(logger, "level: %d DEBUG, message: %s\n", level, msg) } else { fmt.Fprintf(logger, "level: %d INFO, message: %s\n", level, msg) } } func (logger *CustomLogger) Error(err error, msg string, _ ...interface{}) { logger.mu.Lock() defer logger.mu.Unlock() fmt.Fprintf(logger, "error: %v, message: %s\n", err, msg) }
Writerロガーに を割り当て、それをSink のClient として設定します。
この例では、ロガーは コマンドと接続イベントをLevelDebugレベルでログに記録します。
buf := bytes.NewBuffer(nil) sink := &CustomLogger{Writer: buf} loggerOptions := options. Logger(). SetSink(sink). SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug). SetComponentLevel(options.LogComponentConnection, options.LogLevelDebug) // Creates options that include the logger specification clientOptions := options. Client(). ApplyURI(uri). SetLoggerOptions(loggerOptions)
操作を実行します。
次のコードは挿入操作を実行し、ログ メッセージを生成します。
type Item struct { Name string } coll := client.Database("db").Collection("testColl") _, err = coll.InsertOne(context.TODO(), Item{Name: "grapefruit"})
level: 1 DEBUG, message: Connection pool created level: 1 DEBUG, message: Connection pool ready level: 1 DEBUG, message: Connection pool created level: 1 DEBUG, message: Connection pool ready level: 1 DEBUG, message: Connection pool created level: 1 DEBUG, message: Connection pool ready level: 1 DEBUG, message: Connection checkout started level: 1 DEBUG, message: Connection created level: 1 DEBUG, message: Connection ready level: 1 DEBUG, message: Connection checked out level: 1 DEBUG, message: Command started level: 1 DEBUG, message: Command succeeded level: 1 DEBUG, message: Connection checked in
サードパーティのロガーの統合
Go では、多くのサードパーティのログ パッケージが利用できます。 アプリケーションでサードパーティのロガーを使用するには、ロガーを作成し、それをLoggerOptionsインスタンスの Sink として割り当てます。
例
この例では、サードパーティのログ パッケージであるlogrusをアプリケーションに統合する方法を示します。
logrusロガーを定義します。
次のコードでは、これらの仕様でlogrusロガーを作成します。
ロガーはコンソールにメッセージを記録します。
ロガーは
DebugLevelレベルでメッセージをログに記録します。ロガーは
JSONFormatterフォーマッタを使用してメッセージをフォーマットします。
myLogger := &logrus.Logger{ Out: os.Stderr, Level: logrus.DebugLevel, Formatter: &logrus.JSONFormatter{ TimestampFormat: "2006-01-02 15:04:05", PrettyPrint: true, }, }
Sinkロガーを のClient として設定します。
次のコード例では、ロガーはLevelDebugレベルで コマンドをログに記録するように構成されています。
sink := logrusr.New(myLogger).GetSink() // Sets options when configuring the logrus logger loggerOptions := options. Logger(). SetSink(sink). SetComponentLevel(options.LogComponentCommand, options.LogLevelDebug) // Creates options that include the logger specification clientOptions := options. Client(). ApplyURI(uri). SetLoggerOptions(loggerOptions)
操作を実行します。
次のコードはいくつかの CRUD 操作を実行し、ログ メッセージを生成します。
type Item struct { Name string } coll := client.Database("db").Collection("testColl") docs := []interface{}{ Item{Name: "starfruit"}, Item{Name: "kiwi"}, Item{Name: "cantaloupe"}, } _, err = coll.InsertMany(context.TODO(), docs) if err != nil { panic(err) } _, err = coll.DeleteOne(context.TODO(), Item{Name: "kiwi"}) if err != nil { panic(err) }
{ "command": "{\"insert\": \"testColl\", ...}", "commandName": "insert", "databaseName": "db", ... "level": "debug", "message": "Command started", "msg": "Command started", ... "time": "2023-07-06 10:23:42" } { "commandName": "insert", ... "level": "debug", "message": "Command succeeded", "msg": "Command succeeded", ... "time": "2023-07-06 10:23:42" } { "command": "{\"delete\": \"testColl\", ...}", "commandName": "delete", "databaseName": "db", ... "level": "debug", "message": "Command started", "msg": "Command started", ... "time": "2023-07-06 10:23:42" } { "commandName": "delete", ... "level": "debug", "message": "Command succeeded", "msg": "Command succeeded", ... "time": "2023-07-06 10:23:42" }
Tip
ログ記録 パッケージ
サードパーティのログ パッケージの詳細については、それぞれのGithubリポジトリを参照してください。
これらのロガーを統合する完全なコード例については、 GoドライバーGithubリポジトリの ログ テスト を参照してください。
詳細情報
クライアントオプション設定の詳細については、「MongoClient の作成」ガイドを参照してください。
Tip
モニタリング
ロギングに加えて、アプリケーションでサーバー選択とトポロジーのモニタリング を有効にすることができます。詳細については、アプリケーション イベントの監視 の基礎ガイドを参照してください。
API ドキュメント
このガイドで説明した型やメソッドの詳細については、次の API ドキュメントを参照してください。