Format and .clang-format
This commit is contained in:
1 parent
6aed7b0027
commit
b94b634a87
47 files changed
+42341
-39711
No files matched your search
+321
-261
@@ -1,321 +1,381 @@
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <print>
|
||||
#include <chrono>
|
||||
#include <source_location>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <print>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <deque>
|
||||
#include <condition_variable>
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
|
||||
#include <ts6bot/Config.hpp>
|
||||
|
||||
#include "Singleton.hpp"
|
||||
|
||||
class Logger : public Singleton<Logger> {
|
||||
friend class Singleton<Logger>;
|
||||
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
|
||||
};
|
||||
// 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
|
||||
};
|
||||
// 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);
|
||||
public:
|
||||
|
||||
// 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);
|
||||
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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
// 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 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 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 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 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 critical file
|
||||
std::string criticalFilename = std::format("critical_{}.log", timestamp);
|
||||
m_logFiles[ts6bot::LogLevel::Critical].open(logDir / criticalFilename, 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);
|
||||
|
||||
// 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());
|
||||
}
|
||||
// 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);
|
||||
|
||||
// 2. Start Worker Thread
|
||||
m_workerThread = std::jthread([this](const std::stop_token &st) {
|
||||
this->workerLoop(st);
|
||||
});
|
||||
}
|
||||
// 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());
|
||||
}
|
||||
|
||||
~Logger() override {
|
||||
// Signal exit and wake up worker
|
||||
m_exit = true;
|
||||
m_cv.notify_one();
|
||||
// m_workerThread destructor will wait for join automatically
|
||||
// 2. Start Worker Thread
|
||||
m_workerThread = std::jthread(
|
||||
[this](const std::stop_token &st) { this->workerLoop(st); });
|
||||
}
|
||||
|
||||
// Close all log files
|
||||
for (auto &file: m_logFiles | std::views::values) {
|
||||
if (file.is_open()) {
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
~Logger() override
|
||||
{
|
||||
// Signal exit and wake up worker
|
||||
m_exit = true;
|
||||
m_cv.notify_one();
|
||||
// m_workerThread destructor will wait for join automatically
|
||||
|
||||
// --- Public Logging API ---
|
||||
// Close all log files
|
||||
for (auto &file : m_logFiles | std::views::values) {
|
||||
if (file.is_open()) {
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
// --- Public Logging API ---
|
||||
|
||||
try {
|
||||
// 1. Capture context immediately
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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();
|
||||
try {
|
||||
// 1. Capture context immediately
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
// Fallback if formatting fails
|
||||
std::println(std::cerr, "Logging Error: {}", e.what());
|
||||
}
|
||||
}
|
||||
// 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();
|
||||
|
||||
// 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)...);
|
||||
}
|
||||
} catch (const std::exception &e) {
|
||||
// Fallback if formatting fails
|
||||
std::println(std::cerr, "Logging Error: {}", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
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)...);
|
||||
}
|
||||
// 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 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 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 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 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 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 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 critical(std::format_string<Args...> fmt, Args&&... args) {
|
||||
log(ts6bot::LogLevel::Critical, 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)...);
|
||||
}
|
||||
|
||||
void SetLogLevel(const ts6bot::LogLevel level) { m_minLevel = level; }
|
||||
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)...);
|
||||
}
|
||||
|
||||
private:
|
||||
// --- Backend Worker ---
|
||||
void workerLoop(std::stop_token st) {
|
||||
while (!st.stop_requested() || !isQueueEmpty()) {
|
||||
std::unique_lock lock(m_queueMutex);
|
||||
void SetLogLevel(const ts6bot::LogLevel level) { m_minLevel = level; }
|
||||
|
||||
// Wait until data is available or stop is requested
|
||||
m_cv.wait(lock, [this, &st] {
|
||||
return !m_logQueue.empty() || st.stop_requested() || m_exit;
|
||||
});
|
||||
private:
|
||||
|
||||
if (m_logQueue.empty()) {
|
||||
if (st.stop_requested() || m_exit) break;
|
||||
continue;
|
||||
}
|
||||
// --- Backend Worker ---
|
||||
void workerLoop(std::stop_token st)
|
||||
{
|
||||
while (!st.stop_requested() || !isQueueEmpty()) {
|
||||
std::unique_lock lock(m_queueMutex);
|
||||
|
||||
// Swap queue to local buffer to minimize lock time
|
||||
std::deque<LogEntry> localQueue;
|
||||
std::swap(localQueue, m_logQueue);
|
||||
lock.unlock();
|
||||
// Wait until data is available or stop is requested
|
||||
m_cv.wait(lock, [this, &st] {
|
||||
return !m_logQueue.empty() || st.stop_requested() || m_exit;
|
||||
});
|
||||
|
||||
// Process Batch
|
||||
for (const auto& entry : localQueue) {
|
||||
writeLog(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (m_logQueue.empty()) {
|
||||
if (st.stop_requested() || m_exit) {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
bool isQueueEmpty() {
|
||||
std::lock_guard lock(m_queueMutex);
|
||||
return m_logQueue.empty();
|
||||
}
|
||||
// Swap queue to local buffer to minimize lock time
|
||||
std::deque<LogEntry> localQueue;
|
||||
std::swap(localQueue, m_logQueue);
|
||||
lock.unlock();
|
||||
|
||||
void writeLog(const LogEntry& entry) {
|
||||
// Format: "HH:MM:SS.nanoseconds [thread_id] /path/to/file.cpp:line LOG_LEVEL message"
|
||||
// Process Batch
|
||||
for (const auto &entry : localQueue) {
|
||||
writeLog(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto utc_time = std::chrono::zoned_time{std::chrono::locate_zone("UTC"), entry.timestamp};
|
||||
bool isQueueEmpty()
|
||||
{
|
||||
std::lock_guard lock(m_queueMutex);
|
||||
return m_logQueue.empty();
|
||||
}
|
||||
|
||||
// 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);
|
||||
void writeLog(const LogEntry &entry)
|
||||
{
|
||||
// Format: "HH:MM:SS.nanoseconds [thread_id] /path/to/file.cpp:line
|
||||
// LOG_LEVEL message"
|
||||
|
||||
// Format source location
|
||||
std::string sourceLocation = std::format("{}:{}",
|
||||
entry.sourceLoc.file_name(),
|
||||
entry.sourceLoc.line());
|
||||
auto utc_time = std::chrono::zoned_time{
|
||||
std::chrono::locate_zone("UTC"), entry.timestamp};
|
||||
|
||||
// Get thread ID as integer
|
||||
std::ostringstream threadIdStream;
|
||||
threadIdStream << entry.threadId;
|
||||
std::string threadIdStr = threadIdStream.str();
|
||||
// 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);
|
||||
|
||||
// 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
|
||||
);
|
||||
// Format source location
|
||||
std::string sourceLocation = std::format(
|
||||
"{}:{}", entry.sourceLoc.file_name(), entry.sourceLoc.line());
|
||||
|
||||
// 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
|
||||
);
|
||||
// Get thread ID as integer
|
||||
std::ostringstream threadIdStream;
|
||||
threadIdStream << entry.threadId;
|
||||
std::string threadIdStr = threadIdStream.str();
|
||||
|
||||
// Print to Console with colors
|
||||
std::print(std::cout, "{}", consoleLog);
|
||||
// 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);
|
||||
|
||||
// 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();
|
||||
}
|
||||
// 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);
|
||||
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
// Print to Console with colors
|
||||
std::print(std::cout, "{}", consoleLog);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
// 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();
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
}
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
ts6bot::LogLevel m_minLevel;
|
||||
std::unordered_map<ts6bot::LogLevel, std::ofstream> m_logFiles;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// Concurrency
|
||||
std::deque<LogEntry> m_logQueue;
|
||||
std::mutex m_queueMutex;
|
||||
std::condition_variable m_cv;
|
||||
std::jthread m_workerThread;
|
||||
std::atomic<bool> m_exit;
|
||||
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)
|
||||
#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__)
|
||||
#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__)
|
||||
Reference in new issue
Block a user