1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include <string>
#include <iostream>
#include "logger.hpp"
void Log::print(int logLevel, std::string msg) {
/**
* Writes the message to the log file
*
* @param logLevel The log type, must be one of the following "DEBUG", "INFO", "ERROR", "FATAL"
* @param msg The message to print to the log files
*/
assert(logLevel >= MIN_LEVEL && logLevel <= MAX_LEVEL);
//static std::mutex io_mutex;
//std::lock(_m_, _x_); // if more than one
std::lock_guard<std::mutex> lk1(_m_, std::adopt_lock);
//std::lock_guard<std::mutex> lk2(_x_, std::adopt_lock);
if (_loggingLevel_ > logLevel || msg.empty()) {
return;
}
std::string combinedMsg = get_current_time_and_date() + " " + _getLogLevelDesc_(logLevel) + " " +msg + "\n";
{
//std::lock_guard<std::mutex> lk(io_mutex);
SDL_RWwrite( _file_, combinedMsg.c_str(), 1, combinedMsg.size() );
}
}
std::string Log::_getLogLevelDesc_(int LogLevel) {
switch(LogLevel) {
case DEBUG : return "DEBUG";
case INFO : return "INFO";
case ERROR: return "ERROR";
case FATAL: return "FATAL";
default: return "UNKNOWN";
};
}
void Log::_initFile_(){
// clear the log file
_file_ = SDL_RWFromFile(_fileName_.c_str(), "w");
if(_file_==NULL) {
std::cout << "Error creating log file " << _fileName_ <<". Program terminated abnormally.";
exit(EXIT_FAILURE);
} else {
//Close file handler
SDL_RWclose(_file_);
}
_file_ = SDL_RWFromFile(_fileName_.c_str(), _mode_.c_str());
if(_file_==NULL) {
std::cout << "Error creating log file " << _fileName_ <<". Program terminated abnormally.";
exit(EXIT_FAILURE);
}
}
void Log::_closeFile_() {
SDL_RWclose(_file_);
}
void Logger::log(int logLevel, std::string msg, std::string fileName, std::string mode, int loggingLevel) {
if (!Logger::_logs_[fileName]) {
Logger::_logs_[fileName] = std::make_unique<Log>(fileName, mode, loggingLevel);
}
Logger::_logs_[fileName]->print(logLevel, msg);
}
|