321 lines
12 KiB
C++
321 lines
12 KiB
C++
#pragma once
|
|
|
|
#include <iostream>
|
|
#include <fstream>
|
|
#include <filesystem>
|
|
#include <format>
|
|
#include <print>
|
|
#include <chrono>
|
|
#include <source_location>
|
|
#include <mutex>
|
|
#include <thread>
|
|
#include <string>
|
|
#include <deque>
|
|
#include <condition_variable>
|
|
#include <atomic>
|
|
#include <unordered_map>
|
|
|
|
#include <ts6bot/Config.hpp>
|
|
|
|
#include "Singleton.hpp"
|
|
|
|
class Logger : public Singleton<Logger> {
|
|
friend class Singleton<Logger>;
|
|
|
|
// ANSI Color codes
|
|
struct Colors {
|
|
static constexpr auto RESET = "\033[0m";
|
|
static constexpr auto TRACE = "\033[37m"; // White
|
|
static constexpr auto DEBUG = "\033[36m"; // Cyan
|
|
static constexpr auto INFO = "\033[32m"; // Green
|
|
static constexpr auto WARNING = "\033[33m"; // Yellow
|
|
static constexpr auto ERROR = "\033[31m"; // Red
|
|
static constexpr auto CRITICAL = "\033[1;31m"; // Bold Red
|
|
};
|
|
|
|
// Internal structure to hold log data in the queue
|
|
struct LogEntry {
|
|
std::chrono::system_clock::time_point timestamp;
|
|
std::thread::id threadId;
|
|
std::source_location sourceLoc;
|
|
ts6bot::LogLevel level;
|
|
std::string message; // Pre-formatted user message
|
|
};
|
|
|
|
public:
|
|
explicit Logger(const ts6bot::LogLevel logLevel = ts6bot::LogLevel::Info)
|
|
: m_minLevel(logLevel), m_exit(false)
|
|
{
|
|
// 1. Setup File Sinks (Synchronous init)
|
|
try {
|
|
namespace fs = std::filesystem;
|
|
const fs::path logDir = "logs";
|
|
if (!fs::exists(logDir)) fs::create_directories(logDir);
|
|
|
|
// Time for filename (UTC)
|
|
const auto now = std::chrono::system_clock::now();
|
|
auto now_utc = std::chrono::zoned_time{std::chrono::locate_zone("UTC"), now};
|
|
std::string timestamp = std::format("{:%Y-%m-%d_%H-%M-%S}", now_utc);
|
|
|
|
// Open trace file (all logs)
|
|
std::string traceFilename = std::format("trace_{}.log", timestamp);
|
|
m_logFiles[ts6bot::LogLevel::Trace].open(logDir / traceFilename, std::ios::out | std::ios::app);
|
|
|
|
// Open error file
|
|
std::string errorFilename = std::format("error_{}.log", timestamp);
|
|
m_logFiles[ts6bot::LogLevel::Error].open(logDir / errorFilename, std::ios::out | std::ios::app);
|
|
|
|
// Open warning file
|
|
std::string warningFilename = std::format("warning_{}.log", timestamp);
|
|
m_logFiles[ts6bot::LogLevel::Warning].open(logDir / warningFilename, std::ios::out | std::ios::app);
|
|
|
|
// Open critical file
|
|
std::string criticalFilename = std::format("critical_{}.log", timestamp);
|
|
m_logFiles[ts6bot::LogLevel::Critical].open(logDir / criticalFilename, std::ios::out | std::ios::app);
|
|
|
|
// Check if files opened successfully
|
|
for (const auto& [level, file] : m_logFiles) {
|
|
if (!file.is_open()) {
|
|
std::println(std::cerr, "Logger Error: Failed to open log file for level: {}", levelToString(level));
|
|
}
|
|
}
|
|
} catch (const std::exception& e) {
|
|
std::println(std::cerr, "Logger Initialization Error: {}", e.what());
|
|
}
|
|
|
|
// 2. Start Worker Thread
|
|
m_workerThread = std::jthread([this](const std::stop_token &st) {
|
|
this->workerLoop(st);
|
|
});
|
|
}
|
|
|
|
~Logger() override {
|
|
// Signal exit and wake up worker
|
|
m_exit = true;
|
|
m_cv.notify_one();
|
|
// m_workerThread destructor will wait for join automatically
|
|
|
|
// Close all log files
|
|
for (auto &file: m_logFiles | std::views::values) {
|
|
if (file.is_open()) {
|
|
file.close();
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- Public Logging API ---
|
|
|
|
// Generic log function
|
|
template <typename... Args>
|
|
void log(const ts6bot::LogLevel level, const std::source_location& loc, std::format_string<Args...> fmt, Args&&... args) {
|
|
if (level < m_minLevel || level == ts6bot::LogLevel::None) return;
|
|
|
|
try {
|
|
// 1. Capture context immediately
|
|
|
|
// 3. Push to Queue
|
|
{
|
|
LogEntry entry{
|
|
.timestamp = std::chrono::system_clock::now(),
|
|
.threadId = std::this_thread::get_id(),
|
|
.sourceLoc = loc,
|
|
.level = level,
|
|
// 2. Format message immediately (capture by value) to avoid dangling references
|
|
.message = std::format(fmt, std::forward<Args>(args)...)
|
|
};
|
|
std::lock_guard lock(m_queueMutex);
|
|
m_logQueue.push_back(std::move(entry));
|
|
}
|
|
m_cv.notify_one();
|
|
|
|
} catch (const std::exception& e) {
|
|
// Fallback if formatting fails
|
|
std::println(std::cerr, "Logging Error: {}", e.what());
|
|
}
|
|
}
|
|
|
|
// Convenience Wrappers
|
|
template <typename... Args>
|
|
void trace(std::format_string<Args...> fmt, Args&&... args) {
|
|
log(ts6bot::LogLevel::Trace, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
|
}
|
|
|
|
template <typename... Args>
|
|
void info(std::format_string<Args...> fmt, Args&&... args) {
|
|
log(ts6bot::LogLevel::Info, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
|
}
|
|
|
|
template <typename... Args>
|
|
void error(std::format_string<Args...> fmt, Args&&... args) {
|
|
log(ts6bot::LogLevel::Error, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
|
}
|
|
|
|
template <typename... Args>
|
|
void warn(std::format_string<Args...> fmt, Args&&... args) {
|
|
log(ts6bot::LogLevel::Warning, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
|
}
|
|
|
|
template <typename... Args>
|
|
void debug(std::format_string<Args...> fmt, Args&&... args) {
|
|
log(ts6bot::LogLevel::Debug, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
|
}
|
|
|
|
template <typename... Args>
|
|
void critical(std::format_string<Args...> fmt, Args&&... args) {
|
|
log(ts6bot::LogLevel::Critical, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
|
}
|
|
|
|
void SetLogLevel(const ts6bot::LogLevel level) { m_minLevel = level; }
|
|
|
|
private:
|
|
// --- Backend Worker ---
|
|
void workerLoop(std::stop_token st) {
|
|
while (!st.stop_requested() || !isQueueEmpty()) {
|
|
std::unique_lock lock(m_queueMutex);
|
|
|
|
// Wait until data is available or stop is requested
|
|
m_cv.wait(lock, [this, &st] {
|
|
return !m_logQueue.empty() || st.stop_requested() || m_exit;
|
|
});
|
|
|
|
if (m_logQueue.empty()) {
|
|
if (st.stop_requested() || m_exit) break;
|
|
continue;
|
|
}
|
|
|
|
// Swap queue to local buffer to minimize lock time
|
|
std::deque<LogEntry> localQueue;
|
|
std::swap(localQueue, m_logQueue);
|
|
lock.unlock();
|
|
|
|
// Process Batch
|
|
for (const auto& entry : localQueue) {
|
|
writeLog(entry);
|
|
}
|
|
}
|
|
}
|
|
|
|
bool isQueueEmpty() {
|
|
std::lock_guard lock(m_queueMutex);
|
|
return m_logQueue.empty();
|
|
}
|
|
|
|
void writeLog(const LogEntry& entry) {
|
|
// Format: "HH:MM:SS.nanoseconds [thread_id] /path/to/file.cpp:line LOG_LEVEL message"
|
|
|
|
auto utc_time = std::chrono::zoned_time{std::chrono::locate_zone("UTC"), entry.timestamp};
|
|
|
|
// Extract nanoseconds
|
|
const auto duration = entry.timestamp.time_since_epoch();
|
|
const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
|
|
const auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(duration - seconds);
|
|
|
|
// Format source location
|
|
std::string sourceLocation = std::format("{}:{}",
|
|
entry.sourceLoc.file_name(),
|
|
entry.sourceLoc.line());
|
|
|
|
// Get thread ID as integer
|
|
std::ostringstream threadIdStream;
|
|
threadIdStream << entry.threadId;
|
|
std::string threadIdStr = threadIdStream.str();
|
|
|
|
// Construct log without colors (for file)
|
|
const std::string fileLog = std::format("{:%H:%M:%S}.{:09} [{}] {:<28} {:<9} {}\n",
|
|
utc_time,
|
|
nanoseconds.count(),
|
|
threadIdStr,
|
|
sourceLocation,
|
|
levelToString(entry.level),
|
|
entry.message
|
|
);
|
|
|
|
// Construct colored log (for console)
|
|
const char* color = getColorForLevel(entry.level);
|
|
std::string consoleLog = std::format("{}{:%H:%M:%S}.{:09}{} [{}] {:<28} {}{:<9}{} {}\n",
|
|
color,
|
|
utc_time,
|
|
nanoseconds.count(),
|
|
Colors::RESET,
|
|
threadIdStr,
|
|
sourceLocation,
|
|
color,
|
|
levelToString(entry.level),
|
|
Colors::RESET,
|
|
entry.message
|
|
);
|
|
|
|
// Print to Console with colors
|
|
std::print(std::cout, "{}", consoleLog);
|
|
|
|
// Write to trace file (all logs) - no colors
|
|
if (m_logFiles.at(ts6bot::LogLevel::Trace).is_open()) {
|
|
m_logFiles.at(ts6bot::LogLevel::Trace) << fileLog;
|
|
m_logFiles.at(ts6bot::LogLevel::Trace).flush();
|
|
}
|
|
|
|
// Write to specific level files - no colors
|
|
if (entry.level == ts6bot::LogLevel::Error && m_logFiles.at(ts6bot::LogLevel::Error).is_open()) {
|
|
m_logFiles.at(ts6bot::LogLevel::Error) << fileLog;
|
|
m_logFiles.at(ts6bot::LogLevel::Error).flush();
|
|
}
|
|
else if (entry.level == ts6bot::LogLevel::Warning && m_logFiles.at(ts6bot::LogLevel::Warning).is_open()) {
|
|
m_logFiles.at(ts6bot::LogLevel::Warning) << fileLog;
|
|
m_logFiles.at(ts6bot::LogLevel::Warning).flush();
|
|
}
|
|
else if (entry.level == ts6bot::LogLevel::Critical && m_logFiles.at(ts6bot::LogLevel::Critical).is_open()) {
|
|
m_logFiles.at(ts6bot::LogLevel::Critical) << fileLog;
|
|
m_logFiles.at(ts6bot::LogLevel::Critical).flush();
|
|
}
|
|
}
|
|
|
|
static const char* getColorForLevel(const ts6bot::LogLevel level) {
|
|
switch (level) {
|
|
case ts6bot::LogLevel::Trace: return Colors::TRACE;
|
|
case ts6bot::LogLevel::Debug: return Colors::DEBUG;
|
|
case ts6bot::LogLevel::Info: return Colors::INFO;
|
|
case ts6bot::LogLevel::Warning: return Colors::WARNING;
|
|
case ts6bot::LogLevel::Error: return Colors::ERROR;
|
|
case ts6bot::LogLevel::Critical: return Colors::CRITICAL;
|
|
default: return Colors::RESET;
|
|
}
|
|
}
|
|
|
|
static std::string_view levelToString(const ts6bot::LogLevel level) {
|
|
switch (level) {
|
|
case ts6bot::LogLevel::Trace: return "TRACE";
|
|
case ts6bot::LogLevel::Debug: return "DEBUG";
|
|
case ts6bot::LogLevel::Info: return "INFO";
|
|
case ts6bot::LogLevel::Warning: return "WARNING";
|
|
case ts6bot::LogLevel::Error: return "ERROR";
|
|
case ts6bot::LogLevel::Critical: return "CRITICAL";
|
|
default: return "UNKNOWN";
|
|
}
|
|
}
|
|
|
|
private:
|
|
ts6bot::LogLevel m_minLevel;
|
|
std::unordered_map<ts6bot::LogLevel, std::ofstream> m_logFiles;
|
|
|
|
// Concurrency
|
|
std::deque<LogEntry> m_logQueue;
|
|
std::mutex m_queueMutex;
|
|
std::condition_variable m_cv;
|
|
std::jthread m_workerThread;
|
|
std::atomic<bool> m_exit;
|
|
};
|
|
|
|
#define LOG_IF_ALIVE(level, fmt, ...) \
|
|
do { \
|
|
if (Logger::isAlive()) { \
|
|
Logger::getInstance()->log(level, std::source_location::current(), fmt __VA_OPT__(,) __VA_ARGS__); \
|
|
} \
|
|
} while (0)
|
|
|
|
// --- Public API Macros ---
|
|
#define LOG_TRACE(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Trace, fmt __VA_OPT__(,) __VA_ARGS__)
|
|
#define LOG_DEBUG(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Debug, fmt __VA_OPT__(,) __VA_ARGS__)
|
|
#define LOG_INFO(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Info, fmt __VA_OPT__(,) __VA_ARGS__)
|
|
#define LOG_WARN(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Warning, fmt __VA_OPT__(,) __VA_ARGS__)
|
|
#define LOG_ERROR(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Error, fmt __VA_OPT__(,) __VA_ARGS__)
|
|
#define LOG_CRITICAL(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Critical, fmt __VA_OPT__(,) __VA_ARGS__) |