mirror of
https://github.com/yawaflua/SpCloudCore.git
synced 2025-12-10 04:29:35 +02:00
Move logger to file and adjust path string in publish contoller
This commit is contained in:
@@ -10,6 +10,7 @@ add_executable(SpCloudMain
|
||||
"Service/AuthorizationService.cpp"
|
||||
"Service/FileProcessingService.cpp"
|
||||
"Service/CommandService.cpp"
|
||||
"Service/Logger.cpp"
|
||||
)
|
||||
|
||||
if (CMAKE_VERSION VERSION_GREATER 3.12)
|
||||
|
||||
@@ -14,9 +14,8 @@ private:
|
||||
|
||||
FileProcessingService file_processing;
|
||||
|
||||
//std::string publish_app_path = "/mnt/c/Users/Danil/SpCloudApp";//Todo change to linux path
|
||||
//std::string publish_app_path = "/home/danilt2000/SpCloudMain/SpCloudApp";//Todo change to linux path
|
||||
std::string publish_app_path = "/home/danilt2000/SpCloud/";//Todo change to linux path
|
||||
std::string publish_app_path = "/mnt/c/Users/Danil/SpCloudApp";
|
||||
//std::string publish_app_path = "/home/danilt2000/SpCloud/";
|
||||
//std::string publish_app_path = "C:/Temps/";// Todo delete if not needed
|
||||
|
||||
public:
|
||||
@@ -43,13 +42,15 @@ public:
|
||||
const auto& filename = this->publish_app_path + req.files.begin()->second.filename;
|
||||
|
||||
if (filename.size() >= 4 && filename.substr(filename.size() - 4) == ".rar") {
|
||||
//if (file_processing.save_file_with_retry(filename, content)) {
|
||||
if (file_processing.save_file(filename, content)) {
|
||||
|
||||
std::string random_string = generate_random_string(20);//Todo think about change
|
||||
//Todo uncommit later
|
||||
//std::string random_string = generate_random_string(20);//Todo think about change
|
||||
|
||||
file_processing.unzip(filename, this->publish_app_path + random_string);
|
||||
//file_processing.unzip(filename, this->publish_app_path + random_string);
|
||||
|
||||
this->dotnet_publish(this->publish_app_path + random_string);
|
||||
//this->dotnet_publish(this->publish_app_path + random_string);
|
||||
|
||||
res.set_content("File uploaded successfully: " + filename, "text/plain");
|
||||
}
|
||||
|
||||
@@ -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; */// Мьютекс для синхронизации доступа к файлу
|
||||
|
||||
};
|
||||
|
||||
70
SpCloudMain/Service/Logger.cpp
Normal file
70
SpCloudMain/Service/Logger.cpp
Normal 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";
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -7,77 +7,15 @@
|
||||
#include "httplib.h"
|
||||
#include "Controllers/PublishController.cpp"
|
||||
//#include "Service/AuthorizationService.cpp"
|
||||
#include "Service/Logger.cpp"
|
||||
//#include "Service/FileProcessingService.cpp"
|
||||
using namespace std;
|
||||
|
||||
enum LogLevel { DEBUG, INFO, WARNING, ERROR, CRITICAL };
|
||||
|
||||
class Logger {
|
||||
public:
|
||||
// Constructor: Opens the log file in append mode
|
||||
Logger(const string& filename)
|
||||
{
|
||||
logFile.open(filename, ios::app);
|
||||
if (!logFile.is_open()) {
|
||||
cerr << "Error opening log file." << endl;
|
||||
}
|
||||
}
|
||||
|
||||
// Destructor: Closes the log file
|
||||
~Logger() { logFile.close(); }
|
||||
|
||||
// Logs a message with a given log level
|
||||
void log(LogLevel level, const 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
|
||||
ostringstream logEntry;
|
||||
logEntry << "[" << timestamp << "] "
|
||||
<< levelToString(level) << ": " << message
|
||||
<< endl;
|
||||
|
||||
// Output to console
|
||||
cout << logEntry.str();
|
||||
|
||||
// Output to log file
|
||||
if (logFile.is_open()) {
|
||||
logFile << logEntry.str();
|
||||
logFile.flush(); // Ensure immediate write to file
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
ofstream logFile; // File stream for the log file
|
||||
|
||||
// Converts log level to a string for output
|
||||
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";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
Logger logger("logfile.txt");
|
||||
string logger_name = "logfile.txt";
|
||||
|
||||
Logger logger(logger_name);
|
||||
|
||||
std::cout << "SpCloud start\n";
|
||||
|
||||
@@ -96,8 +34,8 @@ int main()
|
||||
httplib::Headers test = req.headers;
|
||||
});
|
||||
|
||||
// Предполагается, что эти классы определены где-то еще
|
||||
AuthorizationService authorization_service;
|
||||
|
||||
FileProcessingService file_processing;
|
||||
|
||||
PublishController publish_controller(svr, authorization_service, file_processing);
|
||||
|
||||
Reference in New Issue
Block a user