-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Log.cpp
70 lines (57 loc) · 1.63 KB
/
Log.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "Log.h"
#include "OSCompatibilityLayer.h"
#include <ctime>
#include <fstream>
#include <iostream>
#include <map>
Log::Log(LogLevel level): logLevel(level)
{
static bool log_file_created = false;
if (!log_file_created)
{
std::ofstream logFile("log.txt", std::ofstream::trunc);
log_file_created = true;
logFile.close();
}
}
Log::~Log()
{
logMessageStream << std::endl;
const auto logMessage = logMessageStream.str();
WriteToConsole(logLevel, logMessage); // write to the console for the sake of tests and Frontend
WriteToFile(logLevel, logMessage);
}
static const std::map<LogLevel, std::string> logLevelStrings = {{LogLevel::Error, " [ERROR] "},
{LogLevel::Warning, " [WARNING] "},
{LogLevel::Info, " [INFO] "},
{LogLevel::Debug, " [DEBUG] "},
{LogLevel::Progress, "[PROGRESS] "},
{LogLevel::Notice, " [NOTICE] "}};
void Log::WriteToFile(LogLevel level, const std::string& logMessage)
{
std::ofstream logFile("log.txt", std::ofstream::app);
WriteTheTime(logFile);
logFile << logLevelStrings.find(level)->second;
logFile << logMessage;
}
void Log::WriteToConsole(LogLevel level, const std::string& logMessage)
{
WriteTheTime(std::cout);
std::cout << logLevelStrings.find(level)->second;
std::cout << logMessage;
}
void Log::WriteTheTime(std::ostream& logFile)
{
time_t rawTime;
time(&rawTime);
tm timeInfo{};
#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
localtime_s(&timeInfo, &rawTime);
#else
localtime_r(&rawTime, &timeInfo); // POSIX
#endif
if (char timeBuffer[64]; strftime(timeBuffer, sizeof timeBuffer, "%Y-%m-%d %H:%M:%S ", &timeInfo) != 0)
{
logFile << timeBuffer;
}
}