multithread-server/log/log.cpp

64 lines
1.6 KiB
C++
Raw Permalink Normal View History

2024-12-12 23:29:58 +03:00
#include <time.h>
#include <ctime>
2024-12-12 04:09:30 +03:00
#include <iostream>
2024-12-12 23:29:58 +03:00
#include <fstream>
#include <unistd.h>
#include <fcntl.h>
2024-12-12 04:09:30 +03:00
#include <sys/stat.h>
2024-12-12 23:29:58 +03:00
#include <sys/types.h>
2024-12-12 04:09:30 +03:00
#include <cstring>
2024-12-12 23:29:58 +03:00
#include <csignal>
const char* LOG_FIFO_NAME = "/pipe/log";
2024-12-12 04:09:30 +03:00
std::string LOG_DIR = "/log_data";
2024-12-12 23:29:58 +03:00
int pipeFd;
void handle_signal(int sig) {
if (sig == SIGTERM || sig == SIGINT) {
close(pipeFd);
unlink(LOG_FIFO_NAME);
}
2024-12-12 04:09:30 +03:00
}
int main() {
2024-12-12 23:29:58 +03:00
signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
mkdir(LOG_DIR.c_str(), 0755);
// Create or open the named pipe
mkfifo(LOG_FIFO_NAME, 0666);
// Open the pipe for reading
pipeFd = open(LOG_FIFO_NAME, O_RDONLY);
if (pipeFd == -1) {
std::cout << "Error opening pipe!" << std::endl;
return 1;
}
// Read log messages from the pipe and write them to the log file
char buffer[256];
while (true) {
ssize_t bytesRead = read(pipeFd, buffer, sizeof(buffer) - 1);
if (bytesRead > 0) {
buffer[bytesRead] = '\0';
time_t now = time(0);
struct tm tstruct;
tstruct = *localtime(&now);
char filename[12];
std::strftime(filename, 12, "%Y-%m-%d", &tstruct);
std::ofstream log_file;
log_file.open(LOG_DIR + "/" + filename + ".log", std::ios_base::app);
char timestamp[32];
std::strftime(timestamp, 32, "%Y/%m/%d %H:%M:%S ", &tstruct);
log_file << timestamp << buffer << std::endl;
log_file.close();
}
}
// Clean up
close(pipeFd);
2024-12-12 04:09:30 +03:00
return 0;
}