/
Shymer123
/
Messenger
Обзор
Документация
Войти
/
Shymer123
/
Messenger
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Server/SourceFiles/Logger/Logger.cpp
111 строк
3 KB
Shymer123
added support for chunk acceptance of files on the server
23 мар 2025, 15:25
23 мар 2025, 15:25
36381b9
Код
Авторство
О чём код?
#include "Logger.h" #include <iostream> #include <nlohmann/json.hpp> #include <filesystem> #include <fstream> using json = nlohmann::json; Logger& Logger::getInstance() { static Logger instance; instance.logPath = instance.getLogsPath(); return instance; } void Logger::logError(const std::string& message, Logger::logLevel level) { std::lock_guard<std::mutex> lock(logMutex); if(isDirectoryCreate()) { std::ofstream logFile(logPath, std::ios::app); if(logFile.is_open()) { std::string levelStr; if(level == 0) { levelStr = "ERROR"; } else if(level == 1) { levelStr = "INFO"; } logFile << getCurrentTime() + " " + levelStr + ": " << message << std::endl; logFile.close(); } else { std::cerr << "Error: Failed to open log file for writing" << std::endl; } } } std::string Logger::getCurrentTime() { auto now = std::chrono::system_clock::now(); auto timePoint = std::chrono::system_clock::to_time_t(now); std::tm localTime = *std::localtime(&timePoint); std::ostringstream timeStream; timeStream << std::put_time(&localTime, "[%H:%M:%S]"); return timeStream.str(); } std::string Logger::getLogsPath() { try { std::ifstream inputFile("config.json"); if(!inputFile.is_open()) { throw std::runtime_error("Unable to open config.json file"); } json config; inputFile >> config; if(config.contains("logs")) { const json& logsConfig = config["logs"]; std::string logsPath = logsConfig.value("log_path", "logs"); return logsPath; } else { throw std::runtime_error("Logs section not found in config file"); } } catch(const std::exception& ex) { std::cerr << "Error reading config: " << ex.what() << std::endl; } return "-1"; } bool Logger::isDirectoryCreate() { std::filesystem::path logDir = std::filesystem::path(logPath).parent_path(); if(!std::filesystem::exists(logDir)) { try { std::filesystem::create_directories(logDir); } catch(const std::exception& ex) { std::cerr << "Failed to create directory: " << ex.what() << std::endl; return false; } } return true; } void Logger::clearFile() { std::ofstream outFile(logPath, std::ios::trunc); if(outFile.is_open()) { outFile.close(); } }