Provides a singleton logger instance that writes logs to a file and optionally prints error messages to std::cerr. It also manages log files by automatically creating a log directory, rotating logs, and keeping only the most recent 10 log files.
- Thread-Safe Logging: Uses
std::mutexto ensure thread safety. - Log Levels: Supports
INFO,WARNING, andERRORlog levels. - File Logging: Logs are written to a file in the
APPDATA/brasilhook/logsdirectory (or./logsifAPPDATAis unavailable). - Log Rotation: Automatically keeps only the 10 most recent log files.
- Timestamped Logs: Each log entry includes a timestamp for easy debugging.
- Error Output:
ERRORlogs are also printed tostd::cerrfor immediate visibility.
- C++17 or later.
- A compiler with support for the
<filesystem>library (e.g., GCC 8+, Clang 7+, MSVC 2017+).
#include "logger.h"Then use the provided methods to log messages at different levels:
logger::get_instance().info("This is an informational message.");
logger::get_instance().warning("This is a warning message.");
logger::get_instance().error("This is an error message.");#include "logger.h"
#include <thread>
void worker_thread() {
for (int i = 0; i < 3; ++i) {
logger::get_instance().info("Thread is running...");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
logger::get_instance().info("Application started.");
std::thread t1(worker_thread);
std::thread t2(worker_thread);
t1.join();
t2.join();
logger::get_instance().info("Application finished.");
return 0;
}[2023-10-25 14:30:22] [INFO] Application started.
[2023-10-25 14:30:22] [INFO] Thread is running...
[2023-10-25 14:30:23] [INFO] Thread is running...
[2023-10-25 14:30:24] [INFO] Thread is running...
[2023-10-25 14:30:25] [INFO] Application finished.
[2023-10-25 14:30:22] [ERROR] This is an error message.
Each log file is named with a timestamp in the format:
log_YYYYMMDD_HHMMSS.txt
The logger automatically manages log files:
- Only the 10 most recent log files are kept.
- Older log files are deleted to save disk space.
Returns the singleton instance of the logger.
logger& logger::get_instance()Logs an informational message.
void logger::info(const std::string& message)Logs a warning message.
void logger::warning(const std::string& message)Logs an error message and prints it to std::cerr.
void logger::error(const std::string& message)std::string current_time(): Returns the current time inYYYY-MM-DD HH:MM:SSformat.std::string get_timestamp(): Returns a timestamp inYYYYMMDD_HHMMSSformat.std::string get_log_directory(): Returns the path to the log directory.void create_log_directory(): Creates the log directory if it doesn't exist.void manage_log_files(): Manages log file rotation.