This repository has been archived on 2025-03-15. You can view files and clone it, but cannot push or open issues or pull requests.
sparkle/libs/utils/log.hpp

64 lines
1.8 KiB
C++
Raw Normal View History

2025-01-19 04:35:20 +05:00
#ifndef UTILS_LOG_HPP
#define UTILS_LOG_HPP
2025-01-14 05:18:08 +05:00
#include <string>
#include <chrono>
#include <iostream>
#include <iomanip>
#include <ctime>
2025-01-15 13:34:41 +05:00
using std::setfill, std::setw;
2025-01-18 23:31:16 +05:00
enum level { INFO, WARNING, ERROR, CRITICAL };
enum type { WEBSOCKET, NETWORK, API };
2025-01-19 04:35:20 +05:00
class Log {
2025-01-14 05:18:08 +05:00
public:
static void create(level lvl, type t, const std::string& message) {
2025-01-19 04:35:20 +05:00
#ifdef DEBUG
2025-01-14 05:18:08 +05:00
std::string color;
switch (lvl) {
case INFO:
2025-01-19 04:35:20 +05:00
color = "\033[34;1m";
2025-01-14 05:18:08 +05:00
break;
case WARNING:
2025-01-19 04:35:20 +05:00
color = "\033[33;1m";
2025-01-14 05:18:08 +05:00
break;
case ERROR:
2025-01-18 23:31:16 +05:00
color = "\033[31;1m";
2025-01-19 04:35:20 +05:00
break;
2025-01-18 23:31:16 +05:00
case CRITICAL:
color = "\033[31;1;2m";
2025-01-14 05:18:08 +05:00
break;
default:
2025-01-19 04:35:20 +05:00
color = "\033[0m";
2025-01-14 05:18:08 +05:00
break;
}
2025-01-18 23:31:16 +05:00
std::cout << color << "[" << getCurrentTime() << "][" << str(t) << "][" << str(lvl) << "] \033[0m" << message << "\033[0m" << std::endl;
2025-01-19 04:35:20 +05:00
#endif
2025-01-14 05:18:08 +05:00
}
private:
static std::string getCurrentTime() {
std::time_t now_c = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::tm* timer = std::localtime(&now_c);
std::ostringstream oss;
oss << setfill('0') << setw(2) << timer->tm_hour << ":" << setfill('0') << setw(2) << timer->tm_min << ":" << setfill('0') << setw(2) << timer->tm_sec;
return oss.str();
}
2025-01-18 23:31:16 +05:00
static std::string str(const level& lvl) {
2025-01-14 05:18:08 +05:00
switch (lvl) {
case INFO: return "INFO";
case WARNING: return "WARNING";
case ERROR: return "ERROR";
2025-01-18 23:31:16 +05:00
case CRITICAL: return "CRITICAL";
2025-01-14 05:18:08 +05:00
default: return "UNKNOWN";
}
}
2025-01-18 23:31:16 +05:00
static std::string str(const type& t) {
2025-01-14 05:18:08 +05:00
switch (t) {
case WEBSOCKET: return "WEBSOCKET";
case NETWORK: return "NETWORK";
2025-01-18 23:31:16 +05:00
case API: return "API";
2025-01-14 05:18:08 +05:00
default: return "UNKNOWN";
}
}
};
#endif