ASW Lib
A.D.S. Games SDL Wrapper Library. A library targeted at Allegro4 users who want to switch to SDL3 and use modern c++.
Loading...
Searching...
No Matches
log.cpp
Go to the documentation of this file.
1#include "./asw/modules/log.h"
2
3#include <chrono>
4#include <ctime>
5
6#ifdef __EMSCRIPTEN__
7#include <emscripten.h>
8#endif
9
10namespace {
12 std::ostream* output = &std::cerr;
13
14 const char* levelToString(asw::log::Level level) {
15 switch (level) {
17 return "DEBUG";
19 return "INFO ";
21 return "WARN ";
23 return "ERROR";
24 }
25 return "?????";
26 }
27
28 std::string getTimestamp() {
29 auto now = std::chrono::system_clock::now();
30 auto time = std::chrono::system_clock::to_time_t(now);
31 std::tm tm{};
32#ifdef _WIN32
33 localtime_s(&tm, &time);
34#else
35 localtime_r(&time, &tm);
36#endif
37 char buf[9];
38 std::strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
39 return buf;
40 }
41
42 void logMessage(asw::log::Level level, const std::string& message) {
43 if (level < currentLevel) {
44 return;
45 }
46
47#ifdef __EMSCRIPTEN__
48 int emLevel = EM_LOG_CONSOLE;
49 switch (level) {
51 emLevel = EM_LOG_CONSOLE;
52 break;
54 emLevel = EM_LOG_CONSOLE;
55 break;
57 emLevel = EM_LOG_WARN;
58 break;
60 emLevel = EM_LOG_ERROR;
61 break;
62 }
63 emscripten_log(emLevel, "[%s] [%s] %s", levelToString(level),
64 getTimestamp().c_str(), message.c_str());
65#else
66 *output << "[" << levelToString(level) << "] "
67 << "[" << getTimestamp() << "] " << message << "\n";
68#endif
69 }
70} // namespace
71
73 currentLevel = level;
74}
75
76void asw::log::setOutput(std::ostream& stream) {
77 output = &stream;
78}
79
80void asw::log::debug(const std::string& message) {
81 logMessage(Level::DEBUG, message);
82}
83
84void asw::log::info(const std::string& message) {
85 logMessage(Level::INFO, message);
86}
87
88void asw::log::warn(const std::string& message) {
89 logMessage(Level::WARN, message);
90}
91
92void asw::log::error(const std::string& message) {
93 logMessage(Level::ERROR, message);
94}
Structured logging system.
const char * levelToString(asw::log::Level level)
Definition log.cpp:14
asw::log::Level currentLevel
Definition log.cpp:11
std::string getTimestamp()
Definition log.cpp:28
void logMessage(asw::log::Level level, const std::string &message)
Definition log.cpp:42
std::ostream * output
Definition log.cpp:12
void info(const std::string &message)
Log an info message.
Definition log.cpp:84
void debug(const std::string &message)
Log a debug message.
Definition log.cpp:80
void setLevel(Level level)
Set the minimum log level (messages below this are ignored).
Definition log.cpp:72
void error(const std::string &message)
Log an error message.
Definition log.cpp:92
void warn(const std::string &message)
Log a warning message.
Definition log.cpp:88
void setOutput(std::ostream &stream)
Set the output stream (default: std::cerr).
Definition log.cpp:76
Level
Log severity levels.
Definition log.h:18