-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.cc
More file actions
executable file
·69 lines (56 loc) · 2.2 KB
/
logger.cc
File metadata and controls
executable file
·69 lines (56 loc) · 2.2 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
67
68
69
#include "logger.h"
Logger::Logger(std::ostream& output) : outputStream(output) {}
void Logger::trace(const char* format, ...) {
#if defined(LOG_LEVEL_TRACE)
va_list args;
va_start(args, format);
log("[TRACE] ", format, args);
va_end(args);
#endif
}
void Logger::info(const char* format, ...) {
#if defined(LOG_LEVEL_TRACE) || defined(LOG_LEVEL_INFO)
va_list args;
va_start(args, format);
log("[INFO] ", format, args);
va_end(args);
#endif
}
void Logger::error(const char* format, ...) {
#if defined(LOG_LEVEL_TRACE) || defined(LOG_LEVEL_INFO) || defined(LOG_LEVEL_ERROR)
va_list args;
va_start(args, format);
log("[ERROR] ", format, args);
va_end(args);
#endif
}
void Logger::log(const char* levelString, const char* format, va_list args) {
// Get current time including milliseconds
auto now = std::chrono::system_clock::now();
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
auto value = now_ms.time_since_epoch();
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(value).count();
// Convert milliseconds to seconds and milliseconds
auto seconds = millis / 1000;
auto milliseconds = millis % 1000;
// Get local time
std::time_t now_time = std::chrono::system_clock::to_time_t(now);
std::tm* localTime = std::localtime(&now_time);
// Format date and time with milliseconds
char timeBuffer[80];
std::strftime(timeBuffer, sizeof(timeBuffer), "[%Y-%m-%d %H:%M:%S:", localTime);
// Append milliseconds to the formatted time
char milliBuffer[4]; // Buffer for milliseconds
std::sprintf(milliBuffer, "%03d", static_cast<int>(milliseconds));
std::strcat(timeBuffer, milliBuffer);
std::strcat(timeBuffer, "] "); // Add closing bracket and space
// Write date and time with milliseconds to output stream
outputStream << timeBuffer;
// Write log level to output stream
outputStream << levelString;
// Format additional arguments
char messageBuffer[1024]; // Adjust buffer size as needed
std::vsprintf(messageBuffer, format, args);
// Write formatted message to output stream
outputStream << messageBuffer << std::endl;
}