15 return _outputFilePath + _logFilename +
".log";
20 if (_logFile.is_open())
22 _writer << std::flush;
33 _currentLevel = level;
39 if (!getcwd(buffer, 1024))
40 throw std::runtime_error(
"Current path for Output file could not be determined try to "
41 "increase filename buffer size" +
42 std::to_string(errno));
44 _logFilename = getCurrentTime();
46 _logFilename = filename;
48 if (_outputFilePath.empty())
49 _outputFilePath = std::string(buffer) +
"/logs/";
51 std::string dirPath = _outputFilePath;
52 if (!dirPath.empty() && dirPath.back() ==
'/')
56 if (stat(dirPath.c_str(), &st) != 0)
58 if (mkdir(dirPath.c_str(), 0755) != 0 && errno != EEXIST)
60 throw std::runtime_error(std::string(
"Could not create log directory: ") +
61 std::to_string(errno));
64 else if (!S_ISDIR(st.st_mode))
66 throw std::runtime_error(
"Log path exists but is not a directory");
69 if (_logFile.is_open())
74 _logFile.open(_outputFilePath + _logFilename +
".log", std::ios::out | std::ios::app);
75 if (!_logFile.is_open())
76 throw std::runtime_error(
"Could not open log file: " + _logFilename +
".log");
79 std::string Logger::getCurrentTime()
const
81 auto now = std::chrono::system_clock::now();
82 std::time_t clock = std::chrono::system_clock::to_time_t(now);
85 localtime_r(&clock, &localTime);
86 std::ostringstream oss;
87 oss << std::put_time(&localTime,
"%Y-%m-%d | %H:%M:%S");
91 std::string Logger::logLevelToString(
LogLevel level)
const
115 if (level < _currentLevel)
117 std::lock_guard<std::mutex> lock(_fileMutex);
118 _logFile <<
"[" << logLevelToString(level) <<
"]" <<
"[" << getCurrentTime() <<
"] " << message
129 if (level < _currentLevel)
131 _writer <<
"[" << logLevelToString(level) <<
"]" <<
"[" << getCurrentTime() <<
"] " << message
Logger class for logging messages to console and file with different log levels. This class is implem...
void setLogLevel(LogLevel level)
void logConsole(LogLevel level, const std::string &message)
Log a message to the console if the log level is sufficient.
void log(LogLevel level, const std::string &message)
Log a message to the log file if the log level is sufficient.
static Logger & instance()
const std::string getOutputPathFile() const
void setOutputFile(const std::string &filename)