Move logger to file and adjust path string in publish contoller

This commit is contained in:
Hepatica
2024-08-11 01:59:54 +02:00
parent 4e94641571
commit 1f3086c96c
5 changed files with 204 additions and 127 deletions

View File

@@ -1,27 +1,92 @@
// ReSharper disable CppClangTidyBugproneSuspiciousInclude
// ReSharper disable CppClangTidyBugproneSuspiciousInclude
#include <filesystem>
#include <fstream>
#include <future>
#include <string>
#include <thread>
#include <sys/stat.h>
#include "CommandService.cpp"
//#include <Poco/Mutex.h>
//#include <Poco/Path.h>
//#include <Poco/FileStr*/eam.h >
class FileProcessingService
{
public:
FileProcessingService()
FileProcessingService(/*&Logger logger*/)
{
}
bool save_file(const std::string& filename, const std::string& content) {
//std::lock_guard<std::mutex> lock(file_mutex); // Блокируем мьютекс//Todo TEST STABILITY OF THIS
std::ofstream ofs(filename, std::ios::binary);
if (!ofs) return false;
ofs << content;
return ofs.good();
}
//bool save_file(const std::string& filename, const std::string& content) {
// Mutex::ScopedLock lock(file_mutex); // Блокируем мьютекс
// try {
// Poco::File file(filename);
// Poco::FileOutputStream ofs(filename, std::ios::binary | std::ios::trunc);
// if (!ofs.good()) {
// std::cerr << "Error opening file: " << filename << std::endl;
// return false;
// }
// ofs.write(content.c_str(), content.size());
// if (!ofs.good()) {
// std::cerr << "Error writing to file: " << filename << std::endl;
// return false;
// }
// ofs.close(); // Явно закрываем файл
// }
// catch (const Poco::Exception& ex) {
// std::cerr << "Poco exception: " << ex.displayText() << std::endl;
// return false;
// }
// return true;
//}
//bool save_file_with_timeout(const std::string& filename, const std::string& content, std::chrono::milliseconds timeout) {
// // Запускаем асинхронную задачу для записи файла
// auto future = std::async(std::launch::async, &FileProcessingService::save_file, this, filename, content);
// // Ожидаем завершения задачи или истечения тайм-аута
// if (future.wait_for(timeout) == std::future_status::ready) {
// return future.get(); // Возвращаем результат записи
// }
// else {
// std::cerr << "Timeout occurred while saving file: " << filename << std::endl;
// return false; // Тайм-аут
// }
//}
//bool save_file_with_retry(const std::string& filename, const std::string& content, int max_retries = 5, std::chrono::milliseconds timeout = std::chrono::milliseconds(1000)) {
// for (int i = 0; i < max_retries; ++i) {
// if (save_file_with_timeout(filename, content, timeout)) {
// return true;
// }
// std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Пауза перед повторной попыткой
// }
// std::cerr << "Failed to save file after " << max_retries << " attempts: " << filename << std::endl;
// return false;
//}
void create_directory(const std::string& path) {
std::filesystem::create_directories(path);
}
@@ -32,7 +97,6 @@ public:
//Windows version
//std::string command = R"(powershell -Command "& \"C:\Program Files\WinRAR\WinRAR.exe\" x \")" + file_path + R"(\" \")" + final_files_directory + R"(\")";
std::cout << "unzip start\n";
//Linux version
//std::string command = "unzip " + file_path + " -d " + final_files_directory;
@@ -69,4 +133,7 @@ public:
// int result = system(command.c_str());//Todo solve unsafe warning
//}
/*private:
std::mutex file_mutex; */// Мьютекс для синхронизации доступа к файлу
};

View File

@@ -0,0 +1,70 @@
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
enum LogLevel { DEBUG, INFO, WARNING, ERROR, CRITICAL };
class Logger {
public:
// Constructor: Opens the log file in append mode
Logger( std::string& filename)
{
logFile.open(filename, std::ios::app);
if (!logFile.is_open()) {
std::cerr << "Error opening log file." << '\n';
}
}
// Destructor: Closes the log file
~Logger() { logFile.close(); }
// Logs a message with a given log level
void log(LogLevel level, const std::string& message)
{
// Get current timestamp
time_t now = time(0);
tm* timeinfo = localtime(&now);
char timestamp[20];
strftime(timestamp, sizeof(timestamp),
"%Y-%m-%d %H:%M:%S", timeinfo);
// Create log entry
std::ostringstream logEntry;
logEntry << "[" << timestamp << "] "
<< levelToString(level) << ": " << message
<< std::endl;
// Output to console
std::cout << logEntry.str();
// Output to log file
if (logFile.is_open()) {
logFile << logEntry.str();
logFile.flush(); // Ensure immediate write to file
}
}
private:
std::ofstream logFile; // File stream for the log file
// Converts log level to a string for output
std::string levelToString(LogLevel level)
{
switch (level) {
case DEBUG:
return "DEBUG";
case INFO:
return "INFO";
case WARNING:
return "WARNING";
case ERROR:
return "ERROR";
case CRITICAL:
return "CRITICAL";
default:
return "UNKNOWN";
}
}
};