From 78412be6fe42ddf0e98fdc05a81fb9f498d463c1 Mon Sep 17 00:00:00 2001 From: Aleksey Date: Sat, 17 Jan 2026 11:01:21 +0300 Subject: [PATCH] Add filepath and new filename of log file's --- .gitignore | 3 ++- main.cpp | 3 ++- src/logger.cpp | 27 ++++++++++++++++++++------- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/.gitignore b/.gitignore index d163863..41ae811 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -build/ \ No newline at end of file +build/ +*.log diff --git a/main.cpp b/main.cpp index 9bbb7b4..4baffd5 100644 --- a/main.cpp +++ b/main.cpp @@ -3,7 +3,8 @@ int main() { LoggerClass logger; - logger.logName = "Test"; + logger.appName = "Test"; + logger.pathToLogFiles = "/home/jam/local-gitea/CPlusPlus/logging/"; logger.logLevel=0; logger.debug("YA SMOG STROKU PEREDAT'"); diff --git a/src/logger.cpp b/src/logger.cpp index 1232bce..92f5f6d 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -14,10 +14,10 @@ enum LogLevels { class LoggerClass { public: - std::string logName; - std::string filepath = "test.log"; + std::string appName; + std::string pathToLogFiles = "/var/log/" + appName; int logLevel; - + void debug(const std::string& message) { action(LogLevels::DEBUG, message); } @@ -29,16 +29,17 @@ class LoggerClass { 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: + std::string filepath = ""; bool openLogFileFailed = false; void action(int logLevel, const std::string message) { @@ -57,7 +58,7 @@ class LoggerClass { case CRITICAL: logLevelStr = std::string("CRITICAL"); break; default: logLevelStr = std::string("UNKNOWN"); break; }; - line = std::string(str) + " - [" + logLevelStr + "] " + message + "\n"; + line = appName + " - " + std::string(str) + " - [" + logLevelStr + "] " + message + "\n"; if (logLevel > 2) { print(line); } @@ -75,6 +76,10 @@ class LoggerClass { } void addToFile(const std::string& message) { + if (filepath == "") { + filepath = pathToLogFiles + "/" + appName + " " + getDateString() + ".log"; + } + if (!openLogFileFailed) { ofstream logFile; logFile.open(filepath, std::ios_base::app); @@ -85,5 +90,13 @@ class LoggerClass { logFile.close(); } } + + const std::string getDateString() { + time_t nowTime = time(NULL); + struct tm *now = localtime(&nowTime); + char str[12]; + strftime(str, sizeof(str), "%Y-%m-%e", now); + return std::string(str); + } };