-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCaveLogger.cxx
More file actions
66 lines (58 loc) · 1.6 KB
/
CaveLogger.cxx
File metadata and controls
66 lines (58 loc) · 1.6 KB
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
#include "CaveLogger.h"
CaveLogger::CaveLogger()
: logToFile(false)
{
}
CaveLogger::~CaveLogger()
{
if (logToFile && logFile.is_open())
{
logFile.close();
}
}
// Logs a message to the console and optionally to a file if file logging is enabled
void CaveLogger::Log(const std::string& message, LogLevel level)
{
// Construct the log message with a timestamp and level
std::string logMessage = "[" + GetTimestamp() + "] [" + LogLevelToString(level) + "] " + message;
// Output to the console
std::cout << logMessage << std::endl;
// Log to file if enabled
if (logToFile && logFile.is_open())
{
logFile << logMessage << std::endl;
}
}
// Enables logging to a specified file by opening it in append mode
void CaveLogger::SetLogToFile(const std::string& filename)
{
if (logFile.is_open())
{
logFile.close();
}
logFile.open(filename, std::ios::out | std::ios::app);
logToFile = logFile.is_open(); // Updates logToFile based on whether the file was successfully opened
}
// Generates and returns a string with the current timestamp in the format YYYY - MM - DD HH : MM:SS
std::string CaveLogger::GetTimestamp()
{
std::time_t now = std::time(nullptr);
char buf[20];
std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
return buf;
}
// Converts an enum `LogLevel` to a string representation for readability in log messages
std::string CaveLogger::LogLevelToString(LogLevel level)
{
switch (level)
{
case INFO:
return "INFO";
case WARNING:
return "WARNING";
case FAULT:
return "ERROR";
default:
return "UNKNOWN";
}
}