File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include " MongoLog.hh"
2+
3+ MongoLog::MongoLog (){
4+ fLogLevel = 0 ;
5+
6+ char hostname[HOST_NAME_MAX];
7+ gethostname (hostname, HOST_NAME_MAX);
8+ fHostname = std::string (hostname);
9+ }
10+ MongoLog::~MongoLog (){};
11+
12+ int MongoLog::Initialize (std::string connection_string,
13+ std::string db, std::string collection, bool debug){
14+ try {
15+ mongocxx::uri uri{connection_string};
16+ fMongoClient = mongocxx::client (uri);
17+ fMongoCollection = fMongoClient [db][collection];
18+ }
19+ catch (const std::exception &e){
20+ std::cout<<" Couldn't initialize the log. So gonna fail then." <<std::endl;
21+ return -1 ;
22+ }
23+
24+ if (debug)
25+ fLogLevel = 1 ;
26+ else
27+ fLogLevel = 0 ;
28+
29+ return 0 ;
30+ }
31+
32+ int MongoLog::Entry (std::string message, int priority){
33+
34+ if (priority >= fLogLevel ){
35+ try {
36+ fMongoCollection .insert_one (bsoncxx::builder::stream::document{} <<
37+ " user" << fHostname <<
38+ " message" << message <<
39+ " priority" << priority <<
40+ bsoncxx::builder::stream::finalize);
41+ std::cout<<" (" <<priority<<" ): " <<message<<std::endl;
42+ }
43+ catch (const std::exception &e){
44+ std::cout<<" Failed to insert log message " <<message<<" (" <<
45+ priority<<" )" <<std::endl;
46+ return -1 ;
47+ }
48+ }
49+ return 0 ;
50+ }
51+
52+
53+
Original file line number Diff line number Diff line change 1+ #ifndef _MONGOLOG_HH_
2+ #define _MONGOLOG_HH_
3+
4+ #include < iostream>
5+ #include < unistd.h>
6+ #include < limits.h>
7+ #include < sstream>
8+
9+ #include < mongocxx/client.hpp>
10+ #include < mongocxx/uri.hpp>
11+ #include < mongocxx/instance.hpp>
12+ #include < mongocxx/database.hpp>
13+ #include < mongocxx/collection.hpp>
14+ #include < bsoncxx/builder/stream/document.hpp>
15+
16+ class MongoLog {
17+ /*
18+ Logging class that writes to MongoDB
19+ */
20+
21+ public:
22+ MongoLog ();
23+ ~MongoLog ();
24+
25+ int Initialize (std::string connection_string,
26+ std::string db, std::string collection,
27+ bool debug=false );
28+
29+ const static int Debug = 0 ; // Verbose output
30+ const static int Message = 1 ; // Normal output
31+ const static int Warning = 2 ; // Bad but minor operational impact
32+ const static int Error = 3 ; // Major operational impact
33+ const static int Fatal = 4 ; // Program gonna die
34+
35+ int Entry (std::string message, int priority=Message);
36+
37+ private:
38+ mongocxx::client fMongoClient ;
39+ mongocxx::collection fMongoCollection ;
40+ std::string fHostname ;
41+ int fLogLevel ;
42+ };
43+
44+ #endif
You can’t perform that action at this time.
0 commit comments