Skip to content

Commit

Permalink
Adding log class
Browse files Browse the repository at this point in the history
  • Loading branch information
coderdj committed Jun 29, 2018
1 parent e881aba commit 4935258
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
53 changes: 53 additions & 0 deletions MongoLog.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include "MongoLog.hh"

MongoLog::MongoLog(){
fLogLevel = 0;

char hostname[HOST_NAME_MAX];
gethostname(hostname, HOST_NAME_MAX);
fHostname = std::string(hostname);
}
MongoLog::~MongoLog(){};

int MongoLog::Initialize(std::string connection_string,
std::string db, std::string collection, bool debug){
try{
mongocxx::uri uri{connection_string};
fMongoClient = mongocxx::client(uri);
fMongoCollection = fMongoClient[db][collection];
}
catch(const std::exception &e){
std::cout<<"Couldn't initialize the log. So gonna fail then."<<std::endl;
return -1;
}

if(debug)
fLogLevel = 1;
else
fLogLevel = 0;

return 0;
}

int MongoLog::Entry(std::string message, int priority){

if(priority >= fLogLevel){
try{
fMongoCollection.insert_one(bsoncxx::builder::stream::document{} <<
"user" << fHostname <<
"message" << message <<
"priority" << priority <<
bsoncxx::builder::stream::finalize);
std::cout<<"("<<priority<<"): "<<message<<std::endl;
}
catch(const std::exception &e){
std::cout<<"Failed to insert log message "<<message<<" ("<<
priority<<")"<<std::endl;
return -1;
}
}
return 0;
}



44 changes: 44 additions & 0 deletions MongoLog.hh
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#ifndef _MONGOLOG_HH_
#define _MONGOLOG_HH_

#include <iostream>
#include <unistd.h>
#include <limits.h>
#include <sstream>

#include <mongocxx/client.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/database.hpp>
#include <mongocxx/collection.hpp>
#include <bsoncxx/builder/stream/document.hpp>

class MongoLog{
/*
Logging class that writes to MongoDB
*/

public:
MongoLog();
~MongoLog();

int Initialize(std::string connection_string,
std::string db, std::string collection,
bool debug=false);

const static int Debug = 0; // Verbose output
const static int Message = 1; // Normal output
const static int Warning = 2; // Bad but minor operational impact
const static int Error = 3; // Major operational impact
const static int Fatal = 4; // Program gonna die

int Entry(std::string message, int priority=Message);

private:
mongocxx::client fMongoClient;
mongocxx::collection fMongoCollection;
std::string fHostname;
int fLogLevel;
};

#endif

0 comments on commit 4935258

Please sign in to comment.