MongoDB C++ Driver current
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()(
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);
}

Temporarily Replace the Logger

Use mongocxx::v1::logger_guard to install a log message handler for a scope and automatically restore the previously-active handler on exit. Guards nest, restoring each prior handler in turn.

void example() {
// A handler may be any invocable compatible with mongocxx::log_handler.
auto handler =
std::cout << mongocxx::to_string(level) << ": " << domain << ": " << message << "\n";
};
// the default logging behavior is active here
{
// Install `handler` for the duration of this scope. Unstructured log messages emitted by
// mongoc while the guard is alive are routed to `handler` instead.
mongocxx::logger_guard guard{handler};
// ... perform operations whose log messages should be handled by `handler` ...
{
// Guards nest. Disable unstructured logging entirely for this inner scope by installing
// a null handler.
mongocxx::logger_guard quiet{nullptr};
// ... perform operations whose log messages should be suppressed ...
}
// The inner guard has been destroyed, so `handler` is active again.
}
// The outer guard has been destroyed, so the default logging behavior is active again.
}

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");
}