diff --git a/CMakeLists.txt b/CMakeLists.txt index b11e745..2d8d0f2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ cmake_minimum_required(VERSION 3.10) -project(Hueta) +project(test_app) set(CMAKE_CXX_STANDART 17) -add_executable(Hueta main.cpp) +add_executable(test_app main.cpp) diff --git a/main.cpp b/main.cpp index 87201b8..9bbb7b4 100644 --- a/main.cpp +++ b/main.cpp @@ -5,7 +5,12 @@ int main() { LoggerClass logger; logger.logName = "Test"; logger.logLevel=0; - std::cout << "Hello World\n"; - logger.info("YA SMOG STROKU PEREDAT', AHUET'"); + + logger.debug("YA SMOG STROKU PEREDAT'"); + logger.info("YA SMOG STROKU PEREDAT'"); + logger.warn("YA SMOG STROKU PEREDAT'"); + logger.error("YA SMOG STROKU PEREDAT'"); + logger.critical("YA SMOG STROKU PEREDAT'"); + return 0; } diff --git a/src/logger.cpp b/src/logger.cpp index 33ee9e6..b16ea18 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -1,13 +1,82 @@ #include +#include +#include + +using namespace std; + +enum LogLevels { + DEBUG, + INFO, + WARN, + ERROR, + CRITICAL +}; class LoggerClass { public: std::string logName; + std::string filepath = "test.log"; int logLevel; + + void debug(const std::string& message) { + action(LogLevels::DEBUG, message); + } void info(const std::string& message) { - std::cout "" << logName << "" << message << "\n"; + action(LogLevels::INFO, message); } + + void warn(const std::string& message) { + action(LogLevels::WARN, message); + } + + void error(const std::string& message) { + action(LogLevels::ERROR, message); + } + + void critical(const std::string& message) { + action(CRITICAL, message); + } + + private: + bool openLogFileFailed = false; + + void action(int logLevel, const std::string message) { + std::string line; + time_t nowTime = time(NULL); + struct tm *now = localtime(&nowTime); + char str[20]; + strftime(str, sizeof(str), "%T", now); + std::string logLevelStr; + switch (logLevel) { + case DEBUG: logLevelStr = std::string("DEBUG"); break; + case INFO: logLevelStr = std::string("INFO"); break; + case WARN: logLevelStr = std::string("WARN"); break; + case ERROR: logLevelStr = std::string("ERROR"); break; + case CRITICAL: logLevelStr = std::string("CRITICAL"); break; + default: logLevelStr = std::string("UNKNOWN"); break; + }; + line = std::string(str) + " - [" + logLevelStr + "] " + message + "\n"; + print(line); + addToFile(line); + } + + void print(const std::string& message) { + std::cout << message; + } + + void addToFile(const std::string& message) { + if (!openLogFileFailed) { + ofstream logFile; + logFile.open(filepath, std::ios_base::app); + if (logFile.is_open()) { + logFile << message; + } + else { openLogFileFailed = true; } + logFile.close(); + } + } + };