#include // Tracking the time when the log function is called #include #include #include "LoggerService.hpp" #include #include #include #include #include namespace fs = std::filesystem; LoggerService::LoggerService(ConfigService* config, const std::string& loggerId) { if(!(config->getConfig("Logger", loggerId, &configuration_))) { std::cout << "Failed to get logger configuration from config service" << std::endl; return; } for(std::string& flag : configuration_.flagsEnabled) { bool found = false; for(const char* validFlag : LogFlagStrings) { if(flag == std::string(validFlag)) { found = true; for(int i = 0; i < LogFlag::Count; i++) { if(LogFlagStrings[i] == flag) { activeFlags_.emplace_back(static_cast(i)); break; } } } } if(!found) { std::cout << "Log flag '" << flag << "' in configuration file is not a valid log flag" << std::endl; } } const auto now = std::chrono::system_clock::now(); const std::time_t t_c = std::chrono::system_clock::to_time_t(now); std::string finaltime = std::ctime(&t_c); finaltime.pop_back(); // removing the newline std::replace(finaltime.begin(),finaltime.end(), ':' , '-'); // filenames cant have dashes std::replace(finaltime.begin(),finaltime.end(), ' ' , '_'); fs::create_directories(configuration_.filePath + "/" + finaltime); std::string logPath = configuration_.filePath + "/" + finaltime + "/" + configuration_.fileName; if(configuration_.fileEnabled) outfile_.open(logPath); log("Logger", LogFlag::Info, "Logger initialized."); } LoggerService::~LoggerService() { if(outfile_) outfile_.close(); } void LoggerService::log(std::string component, LogFlag flag, std::string message, std::source_location Source) { // check if flag is in the list of active flags bool culled = true; for(LogFlag& testFlag : activeFlags_) { if(flag == testFlag) { culled = false; break; } } if(culled) return; std::string finalmessage = ""; if(configuration_.showTime) { finalmessage = finalmessage + "[" + "Not Implemented" + "] "; } std::string componentTrace = "[" + configuration_.id + ": " + component + "] "; finalmessage += componentTrace; // component is the section of the program (For example Mesh or Engine) that is calling the logger std::string level = ""; level = LogFlagStrings[flag]; // level.append(7 - level.length(), ' ') pads out the level string with whitespace so every line is aligned the same // it looked weird though finalmessage = finalmessage + "[" + level + "] "; finalmessage = finalmessage + message + " "; if (configuration_.showSourceTrace) { finalmessage = finalmessage + "[Function: " + Source.function_name() + "]" + " " + "[Line: " + std::to_string(Source.line()) + "]" + " " + "[File: " + Source.file_name() + "]"; } if(configuration_.coutEnabled) { std::cout << finalmessage << std::endl; } if(configuration_.fileEnabled) { outfile_ << finalmessage << std::endl; } return; }