AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

ログ記録

このガイドでは、ドライバーを使用してアプリケーションのログを構成する方法を学習できます。 ロギングの目的は、ドライバー イベントを記録することです。

ロガーは、指定可能な重大度または冗長レベルでメッセージをログに記録します。 アプリケーションでロガーを有効にすると、アプリケーションのアクティビティに関する情報を高レベル、詳細レベル、またはその両方で受け取ることができます。

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 メソッドとパラメーターが一覧表示されています。

プロパティ
説明
セッター メソッド

ComponentLevels

タイプ: map[LogComponent]LogLevel

コンポーネントとログの重大度レベルのマッピング。ドライバーは、各 LogComponentLogLevel を使用して、ログ メッセージが生成されるかどうかを判定します。

LogComponentLogLevel の種類の詳細については、このガイドの「ログ コンポーネントと重大度レベル」セクションを参照してください。

SetComponentLevel()

パラメータ: LogComponentLogLevel

Sink

タイプ: LogSink

ドライバーがメッセージをログするために使用するログインターフェイス。LogSink 型は、カスタムシンクを提供するか、ドライバーのログに対してサードパーティロガーを統合するために実装できるインターフェイスです。このプロパティを設定しない場合、ドライバーは標準ログライブラリを使用します。

詳細については、このガイドの「カスタムロガーの使用」および「サードパーティロガーの統合の項を参照してください。

SetSink()

Parameter: LogSink

MaxDocumentLength

タイプ:uint
デフォルト:1000

ドライバーが出力する各ログ メッセージの最大長(バイト単位)。 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の組み込み仕様を説明しています。

設定
説明
列挙値

LogComponentAll

すべてのコンポーネントのログ記録を有効にします

0

LogComponentCommand

コマンドモニターのログ記録 を有効にします

1

LogComponentTopology

トポロジーのログ作成 を有効にします

2

LogComponentServerSelection

サーバー選択のログ記録 を有効にします

3

LogComponentConnection

接続サービスのログ記録を有効にします

4

設定名またはその列挙値を使用して、ログ コンポーネントを指定できます。 次のコードは、コマンド監視を有効にする同等の方法を示しています。

// 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()メソッドを呼び出して、ロガーをClientLogSinkとして設定します。

この例では、カスタム ロガーを定義して実装する方法を示します。

1
type CustomLogger struct {
io.Writer
mu sync.Mutex
}

注意

上記のコード例では、 CustomLogger構造体でMutex型を使用してアトミック書込みを保証し、競合状態を防ぎます。 Mutexを設定すると、ロガーは複数の goroutine による同時使用に対して安全になります。

2
func (logger *CustomLogger) Info(level int, msg string, _ ...any) {
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, _ ...any) {
logger.mu.Lock()
defer logger.mu.Unlock()
fmt.Fprintf(logger, "error: %v, message: %s\n", err, msg)
}
3

この例では、ロガーは コマンドと接続イベントを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)
4

次のコードは挿入操作を実行し、ログ メッセージを生成します。

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をアプリケーションに統合する方法を示します。

1

この例に必要なlogrusパッケージをダウンロードするには、ターミナルで次のgo getコマンドを実行します。

go get github.com/bombsimon/logrusr/v4
go get github.com/sirupsen/logrus
2

次のコードでは、これらの仕様でlogrusロガーを作成します。

  • ロガーはコンソールにメッセージを記録します。

  • ロガーはDebugLevelレベルでメッセージをログに記録します。

  • ロガーはJSONFormatterフォーマッタを使用してメッセージをフォーマットします。

myLogger := &logrus.Logger{
Out: os.Stderr,
Level: logrus.DebugLevel,
Formatter: &logrus.JSONFormatter{
TimestampFormat: "2006-01-02 15:04:05",
PrettyPrint: true,
},
}
3

次のコード例では、ロガーは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)
4

次のコードはいくつかの CRUD 操作を実行し、ログ メッセージを生成します。

type Item struct {
Name string
}
coll := client.Database("db").Collection("testColl")
docs := []any{
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 ドキュメントを参照してください。