diff options
| author | ilotterytea <iltsu@alright.party> | 2024-05-18 14:48:12 +0500 |
|---|---|---|
| committer | ilotterytea <iltsu@alright.party> | 2024-05-18 14:48:12 +0500 |
| commit | d1793df1eda463b10107d41785ad1d7f055ed476 (patch) | |
| tree | fd3e41c3b4a05924748ae4b762e1ae55a0bc815c /bot/src/logger.cpp | |
| parent | d7a2de17e9b7931f68b5b4079b1c36866a19d343 (diff) | |
upd: moved the bot part to a relative subfolder
Diffstat (limited to 'bot/src/logger.cpp')
| -rw-r--r-- | bot/src/logger.cpp | 96 |
1 files changed, 96 insertions, 0 deletions
diff --git a/bot/src/logger.cpp b/bot/src/logger.cpp new file mode 100644 index 0000000..3d142a2 --- /dev/null +++ b/bot/src/logger.cpp @@ -0,0 +1,96 @@ +#include "logger.hpp" + +#include <ctime> +#include <filesystem> +#include <fstream> +#include <iomanip> +#include <iostream> +#include <sstream> +#include <stdexcept> + +namespace bot::log { + void log(const LogLevel &level, const std::string &source, + const std::string &message) { + std::string dir_name = "logs"; + if (!std::filesystem::exists(dir_name)) { + std::filesystem::create_directory(dir_name); + } + + if (std::filesystem::exists(dir_name) && + !std::filesystem::is_directory(dir_name)) { + throw std::runtime_error("The path '" + dir_name + + "' is not a directory!"); + return; + } + + std::ostringstream line; + + // getting time + std::time_t current_time = std::time(nullptr); + std::tm *local_time = std::localtime(¤t_time); + + line << "[" << std::put_time(local_time, "%H:%M:%S") << "] "; + + std::string level_str; + + switch (level) { + case DEBUG: + level_str = "DEBUG"; + break; + case WARN: + level_str = "WARN"; + break; + case ERROR: + level_str = "ERROR"; + break; + default: + level_str = "INFO"; + break; + } + + line << level_str << " - "; + + line << source << ": " << message << "\n"; + +#ifdef DEBUG_MODE + std::cout << line.str(); +#else + if (level != LogLevel::DEBUG) { + std::cout << line.str(); + } +#endif + + // saving into the log file + std::ostringstream file_name_oss; + file_name_oss << dir_name << "/"; + file_name_oss << "log_"; + file_name_oss << std::put_time(local_time, "%Y-%m-%d"); + file_name_oss << ".log"; + + std::ofstream ofs; + ofs.open(file_name_oss.str(), std::ios::app); + + if (ofs.is_open()) { + ofs << line.str(); + ofs.close(); + } else { + std::cerr << "Failed to write to the log file!\n"; + } + } + + void info(const std::string &source, const std::string &message) { + log(LogLevel::INFO, source, message); + } + + void debug(const std::string &source, const std::string &message) { + log(LogLevel::DEBUG, source, message); + } + + void warn(const std::string &source, const std::string &message) { + log(LogLevel::WARN, source, message); + } + + void error(const std::string &source, const std::string &message) { + log(LogLevel::ERROR, source, message); + } +} |
