Skip to content

Commit 9d4eebc

Browse files
committed
CXX-85 Add an example of how to inject a custom logger
1 parent 4cf5b8d commit 9d4eebc

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/mongo/client/examples/clientTest.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
#include "mongo/client/dbclient.h"
2424

2525
#include <iostream>
26+
#include <boost/thread/mutex.hpp>
2627

2728
#ifndef verify
2829
# define verify(x) MONGO_verify(x)
@@ -31,6 +32,35 @@
3132
using namespace std;
3233
using namespace mongo;
3334

35+
namespace {
36+
37+
// A demonstration of how to inject a custom logger into the client driver.
38+
// This class logs events from the driver to the given ostream. Note that
39+
// the appender is responsible for its own synchronization.
40+
class OstreamAppender : public logger::MessageLogDomain::EventAppender {
41+
public:
42+
using logger::MessageLogDomain::EventAppender::Event;
43+
44+
OstreamAppender(std::ostream& stream)
45+
: _stream(stream) {}
46+
47+
virtual Status append(const Event& event) {
48+
boost::unique_lock<boost::mutex> lock(_mutex);
49+
_stream << dateToISOStringUTC(Date_t(event.getDate())) << ' ';
50+
_stream << '[' << event.getSeverity() << "] ";
51+
_stream << event.getMessage();
52+
return Status::OK();
53+
}
54+
55+
private:
56+
// Synchronizes appender access to _stream. Note that if there are other writers to the
57+
// stream that they will not be synchronized with us.
58+
boost::mutex _mutex;
59+
std::ostream& _stream;
60+
};
61+
62+
} // namespace
63+
3464
int main( int argc, const char **argv ) {
3565

3666
const char *port = "27017";
@@ -42,6 +72,21 @@ int main( int argc, const char **argv ) {
4272
port = argv[ 2 ];
4373
}
4474

75+
// Logging setup example:
76+
77+
// Acquire the global log domain from the global log manager.
78+
logger::MessageLogDomain* globalLogDomain = logger::globalLogManager()->getGlobalDomain();
79+
80+
// Create a new OstreamAppender that logs to std::clog, and inject it into the global log
81+
// manager. Since the manager, by default, does not have any appenders we don't normally
82+
// log. Adding an appender like this will enable logging.
83+
std::auto_ptr<logger::MessageLogDomain::EventAppender> appender(
84+
new OstreamAppender(std::clog));
85+
globalLogDomain->attachAppender(appender);
86+
87+
// Set the logging verbosity to a high level of debugging.
88+
globalLogDomain->setMinimumLoggedSeverity(logger::LogSeverity::Debug(3));
89+
4590
Status status = client::initialize();
4691
if ( !status.isOK() ) {
4792
std::cout << "failed to initialize the client driver: " << status.toString() << endl;

0 commit comments

Comments
 (0)