Add filepath and new filename of log file's

This commit is contained in:
Aleksey
2026-01-17 11:01:21 +03:00
parent 3311930dc4
commit 78412be6fe
3 changed files with 24 additions and 9 deletions

1
.gitignore vendored
View File

@@ -1 +1,2 @@
build/ build/
*.log

View File

@@ -3,7 +3,8 @@
int main() { int main() {
LoggerClass logger; LoggerClass logger;
logger.logName = "Test"; logger.appName = "Test";
logger.pathToLogFiles = "/home/jam/local-gitea/CPlusPlus/logging/";
logger.logLevel=0; logger.logLevel=0;
logger.debug("YA SMOG STROKU PEREDAT'"); logger.debug("YA SMOG STROKU PEREDAT'");

View File

@@ -14,8 +14,8 @@ enum LogLevels {
class LoggerClass { class LoggerClass {
public: public:
std::string logName; std::string appName;
std::string filepath = "test.log"; std::string pathToLogFiles = "/var/log/" + appName;
int logLevel; int logLevel;
void debug(const std::string& message) { void debug(const std::string& message) {
@@ -39,6 +39,7 @@ class LoggerClass {
} }
private: private:
std::string filepath = "";
bool openLogFileFailed = false; bool openLogFileFailed = false;
void action(int logLevel, const std::string message) { void action(int logLevel, const std::string message) {
@@ -57,7 +58,7 @@ class LoggerClass {
case CRITICAL: logLevelStr = std::string("CRITICAL"); break; case CRITICAL: logLevelStr = std::string("CRITICAL"); break;
default: logLevelStr = std::string("UNKNOWN"); 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) { if (logLevel > 2) {
print(line); print(line);
} }
@@ -75,6 +76,10 @@ class LoggerClass {
} }
void addToFile(const std::string& message) { void addToFile(const std::string& message) {
if (filepath == "") {
filepath = pathToLogFiles + "/" + appName + " " + getDateString() + ".log";
}
if (!openLogFileFailed) { if (!openLogFileFailed) {
ofstream logFile; ofstream logFile;
logFile.open(filepath, std::ios_base::app); logFile.open(filepath, std::ios_base::app);
@@ -86,4 +91,12 @@ class LoggerClass {
} }
} }
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);
}
}; };