Docs 菜单
Docs 主页
/ /

记录驱动程序事件

在本指南中,您可以学习;了解如何使用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文档:

  • mongocxx::logger

后退

MongoDB Vector Search

在此页面上