Skip to content

Commit

Permalink
feat(Logger): implemented basic logger
Browse files Browse the repository at this point in the history
  • Loading branch information
Taanviir committed Apr 21, 2024
1 parent 2582d50 commit ab26e46
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions sources/server/Logger.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#ifndef LOGGER_HPP
#define LOGGER_HPP

#include "webserv.hpp"

enum LogLevel {
INFO = 0,
DEBUG,
ERROR
};

#define LOG_FILE "logfile.txt"

class Logger {
public:
static void log_message(const string& message, LogLevel level, bool toFile = false)
{
string logMessage =
"[" + _get_current_time() + "]" + _level_to_string(level) + ": " + message;
if (toFile) {
ofstream _logFile;
_logFile.open(LOG_FILE, std::ios_base::app);
if (!_logFile.is_open())
THROW_EXCEPTION_WITH_INFO("Log: could not open log file");

_logFile << logMessage << endl;
_logFile.close();
}
else
cout << logMessage << endl;
}

private:
static LogLevel _level;

static string _get_current_time()
{
time_t rawtime;
struct tm* timeInfo;
char buffer[80];

time(&rawtime);
timeInfo = localtime(&rawtime);

strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeInfo);
return string(buffer);
}
static string _level_to_string(LogLevel level)
{
switch (level) {
case INFO: return "INFO";
case DEBUG: return "DEBUG";
case ERROR: return "ERROR";
}
}

Logger();
~Logger();
};

#endif // LOGGER_HPP

0 comments on commit ab26e46

Please sign in to comment.