MongoDB C++ Driver mongocxx-4.0.0
Loading...
Searching...
No Matches
Logger

How to use a custom logger with a MongoDB C++ Driver instance.

Basic Usage

class example_logger : public mongocxx::logger {
private:
int* counter_ptr;
public:
explicit example_logger(int* ptr) : counter_ptr(ptr) {}
void operator()(mongocxx::log_level level,
bsoncxx::stdx::string_view domain,
bsoncxx::stdx::string_view message) noexcept override {
EXPECT(level == mongocxx::log_level::k_info);
EXPECT(domain == "mongocxx");
EXPECT(message == "libmongoc logging callback enabled");
*counter_ptr += 1;
}
};
void example() {
int counter = 0;
// Use `std::make_unique` with C++14 or newer.
auto logger = std::unique_ptr<mongocxx::logger>(new example_logger{&counter});
// Emit the informational mongocxx log message: "libmongoc logging callback enabled".
mongocxx::instance instance{std::move(logger)};
EXPECT(counter == 1);
}

Convert a Log Level to a String

void example() {
bsoncxx::stdx::string_view error = mongocxx::to_string(mongocxx::log_level::k_error);
bsoncxx::stdx::string_view critical = mongocxx::to_string(mongocxx::log_level::k_critical);
bsoncxx::stdx::string_view warning = mongocxx::to_string(mongocxx::log_level::k_warning);
bsoncxx::stdx::string_view message = mongocxx::to_string(mongocxx::log_level::k_message);
bsoncxx::stdx::string_view info = mongocxx::to_string(mongocxx::log_level::k_info);
bsoncxx::stdx::string_view debug = mongocxx::to_string(mongocxx::log_level::k_debug);
bsoncxx::stdx::string_view trace = mongocxx::to_string(mongocxx::log_level::k_trace);
EXPECT(error == "error");
EXPECT(critical == "critical");
EXPECT(warning == "warning");
EXPECT(message == "message");
EXPECT(info == "info");
EXPECT(debug == "debug");
EXPECT(trace == "trace");
}