From d1793df1eda463b10107d41785ad1d7f055ed476 Mon Sep 17 00:00:00 2001 From: ilotterytea Date: Sat, 18 May 2024 14:48:12 +0500 Subject: upd: moved the bot part to a relative subfolder --- bot/src/logger.cpp | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 bot/src/logger.cpp (limited to 'bot/src/logger.cpp') 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 +#include +#include +#include +#include +#include +#include + +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); + } +} -- cgit v1.2.3