11#include " Logger.h"
2- #include < iostream>
3- #include < fstream>
42#include < ctime>
3+ #include < fcntl.h>
4+ #include < unistd.h>
5+ #include < mutex>
6+ #include < string.h>
57
68/*
79 * Simple logging utility with:
1214
1315// global
1416std::string log_path;
15- std::fstream logFile;
1617std::time_t epochTimestamp;
18+ int logFileDescriptor;
19+ std::mutex mutex;
1720
1821// Po co jest LoggerBase?
1922
@@ -30,35 +33,47 @@ Logger::Logger(std::string name) {
3033}
3134
3235Logger::Logger (std::string path, std::string name) : LoggerBase(path) {
33- this -> class_name = name ;
34- logFile. open ( " ./log " , std::fstream::out | std::fstream::app) ;
36+ std::string loggerStatus ;
37+ const char * cLoggerStatus ;
3538
36- if (logFile.is_open ()){
37- std::cout <<" [" << this ->class_name << " ]" << " Logfile is open, logging to file enabled" << std::endl;
38- } else {
39- std::cout <<" [" << this ->class_name << " ]" << " Error opening logfile, disabling logging to file" <<std::endl;
39+ this ->class_name = name;
40+ logFileDescriptor = open (log_path.c_str (), O_WRONLY | O_APPEND);
41+
42+ if (logFileDescriptor < 0 ){
43+ loggerStatus = " [" + this ->class_name + " ]" + " Error opening logfile, disabling logging to file\n Error: " + strerror (errno);
44+ cLoggerStatus = loggerStatus.c_str ();
45+ write (2 , cLoggerStatus, strlen (cLoggerStatus));
4046 isLoggingToFileEnabled = false ;
47+ } else {
48+ loggerStatus = " [" + this ->class_name + " ]" + " Logfile is open, logging to file enabled\n " ;
49+ cLoggerStatus = loggerStatus.c_str ();
50+ write (1 , cLoggerStatus, strlen (cLoggerStatus));
4151 }
4252}
4353
4454Logger::~Logger () {
45- // Otaczać ifami?
46- logFile.close ();
55+ close (logFileDescriptor);
4756}
4857
4958void Logger::_log (std::string msg, int level) {
50- epochTimestamp = std::time (nullptr );
51- fullDateTimestamp = std::asctime (std::localtime (&epochTimestamp));
52- fullMessage = " [" +
53- this ->class_name + " " +
54- fullDateTimestamp.substr (0 , fullDateTimestamp.size ()-1 ) + " ] " +
55- msg + " \n " ;
59+ if (this ->current_log_level >= level) {
60+ mutex.lock ();
61+ epochTimestamp = std::time (nullptr );
62+ fullDateTimestamp = std::asctime (std::localtime (&epochTimestamp));
63+ fullMessage = " [" +
64+ this ->class_name + " " +
65+ fullDateTimestamp.substr (0 , fullDateTimestamp.size () - 1 ) + " ] " +
66+ msg + " \n " ;
67+ if (!isLoggingToFileEnabled){
68+ fullMessage = " WARNING: Logging to file disabled " + fullMessage;
69+ }
70+
71+ const char * cFullMessage = fullMessage.c_str ();
5672
57- if (this ->current_log_level >= level) {
58- std::cout << fullMessage;
73+ write (1 , cFullMessage, strlen (cFullMessage));
5974 if (isLoggingToFileEnabled) {
60- logFile << fullMessage ;
61- logFile. flush ();
62- }
75+ write (logFileDescriptor, cFullMessage, strlen (cFullMessage)) ;
76+ }
77+ mutex. unlock ();
6378 }
6479}
0 commit comments