Docs Menu
Docs Home
/ /

ドライバー イベントのログ

このガイドでは、 C++ドライバーを使用してアプリケーションのログを構成する方法を学習できます。ログ記録 を使用すると、ドライバー アクティビティの個別のイベントベースのログを表示できます。

ロガーは、指定可能な 重大度 または冗長 のレベルでメッセージをログ。ドライバーは、ログメッセージを次のレベルで分類します。重大度の高い順に並べられています。

  • error

  • critical

  • warning

  • message

  • info

  • debug

  • trace

重大度レベルを指定すると、ドライバーはより高い重大度レベルを持つすべてのメッセージもログに記録します。例、ログレベルを warning に設定すると、ドライバーは errorcritical の重大度レベルを持つメッセージもログします。

指定する重大度レベルが低いほど、ドライバーがログする情報が多くなり、アプリケーションのパフォーマンスに影響可能性があります。

ユーザー定義のロガー実装を作成して、ロガー出力を処理できます。

ドライバー イベントに関するメッセージを受信するようにアプリケーションを構成するには、logger()クラスの実装を定義します。

次の例では、次のアクションを実行して、ログメッセージを INFO の重大度レベルでフィルタリングするロガーを作成します。

  • 一定レベル以上のログメッセージを処理するためにフィルタリングされたロガークラスを定義します。

  • ログ レベルが info 以上の新しいフィルタリングされたロガーをクライアント用に作成します。

  • 挿入操作でロガーをテストします。

// Creates a filtered logger that only logs messages at or above a specified level
class filtered_logger : public mongocxx::logger {
public:
// Sets the default minimum log level to WARNING
explicit filtered_logger(mongocxx::log_level min_level = mongocxx::log_level::k_warning)
: min_level_(min_level) {}
void operator()(mongocxx::log_level level,
std::string_view domain,
std::string_view message) noexcept override {
// Only log messages at or above the minimum level
if (level <= min_level_) {
std::cout << "[" << level_to_string(level) << "] "
<< domain << ": " << message << std::endl;
}
}
private:
mongocxx::log_level min_level_;
std::string level_to_string(mongocxx::log_level level) const {
switch (level) {
case mongocxx::log_level::k_error: return "ERROR";
case mongocxx::log_level::k_critical: return "CRITICAL";
case mongocxx::log_level::k_warning: return "WARNING";
case mongocxx::log_level::k_message: return "MESSAGE";
case mongocxx::log_level::k_info: return "INFO";
case mongocxx::log_level::k_debug: return "DEBUG";
case mongocxx::log_level::k_trace: return "TRACE";
default: return "UNKNOWN";
}
}
};
// Creates a new logger for the client
void example_filtered_logger() {
std::cout << "\n=== Filtered Logger (INFO and above) ===" << std::endl;
// Logs INFO, MESSAGE, WARNING, CRITICAL, and ERROR messages
auto logger = std::make_unique<filtered_logger>(mongocxx::log_level::k_info);
mongocxx::instance instance{std::move(logger)};
mongocxx::uri uri("mongodb://127.0.0.1:27017");
mongocxx::client client(uri);
auto collection = client["test"]["example3"];
bsoncxx::builder::stream::document doc{};
doc << "name" << "Filtered Test";
collection.insert_one(doc.view());
std::cout << "Operation completed! (Debug and Trace messages were filtered out)" << std::endl;
}
=== Filtered Logger (INFO and above) ===
[INFO] mongocxx: libmongoc logging callback enabled
Operation completed! (Debug and Trace messages were filtered out)

ロガーの出力には、操作の時間、メッセージの重大度レベル、およびログメッセージが含まれます。

C++ドライバーのロガー オプションの詳細については、次のAPIドキュメントを参照してください。

  • mongocx::logger

戻る

MongoDB ベクトル検索

項目一覧