switch/case with enums

This commit is contained in:
Aleksey
2026-01-16 22:49:27 +03:00
parent d780dc618f
commit 77e4bec9d8
3 changed files with 79 additions and 5 deletions

View File

@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.10) cmake_minimum_required(VERSION 3.10)
project(Hueta) project(test_app)
set(CMAKE_CXX_STANDART 17) set(CMAKE_CXX_STANDART 17)
add_executable(Hueta main.cpp) add_executable(test_app main.cpp)

View File

@@ -5,7 +5,12 @@ int main() {
LoggerClass logger; LoggerClass logger;
logger.logName = "Test"; logger.logName = "Test";
logger.logLevel=0; 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; return 0;
} }

View File

@@ -1,13 +1,82 @@
#include <iostream> #include <iostream>
#include <fstream>
#include <time.h>
using namespace std;
enum LogLevels {
DEBUG,
INFO,
WARN,
ERROR,
CRITICAL
};
class LoggerClass { class LoggerClass {
public: public:
std::string logName; std::string logName;
std::string filepath = "test.log";
int logLevel; int logLevel;
void debug(const std::string& message) {
action(LogLevels::DEBUG, message);
}
void info(const std::string& 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();
}
}
}; };