Enhance FileChannel constructor and logging setup: add openmode parameter to FileChannel and update setFileChannel method to support it

This commit is contained in:
whaffman 2025-09-21 21:54:03 +02:00
parent 58edbe86be
commit c509666199
5 changed files with 11 additions and 9 deletions

View File

@ -3,10 +3,11 @@
#include <webserv/log/FileChannel.hpp>
#include <chrono>
#include <ios>
#include <iostream>
FileChannel::FileChannel(const std::string &filename, LogLevel logLevel)
: Channel(logLevel), filename_(filename), fileStream_(filename, std::ios::trunc)
FileChannel::FileChannel(const std::string &filename, std::ios_base::openmode mode, LogLevel logLevel)
: Channel(logLevel), filename_(filename), fileStream_(filename, mode)
{
if (!fileStream_.is_open())
{

View File

@ -10,7 +10,7 @@
class FileChannel : public Channel
{
public:
FileChannel(const std::string &filename, LogLevel logLevel = LogLevel::LOGLVL_TRACE);
FileChannel(const std::string &filename, std::ios_base::openmode mode, LogLevel logLevel = LogLevel::LOGLVL_TRACE);
FileChannel(const FileChannel &other) = delete;
FileChannel(const FileChannel &&other) = delete;

View File

@ -30,7 +30,7 @@ void Log::setStdoutChannel(LogLevel logLevel)
}
}
void Log::setFileChannel(const std::string &filename, LogLevel logLevel)
void Log::setFileChannel(const std::string &filename, std::ios_base::openmode mode, LogLevel logLevel)
{
Log &log = getInstance();
if (log.channels_.contains("file"))
@ -39,7 +39,7 @@ void Log::setFileChannel(const std::string &filename, LogLevel logLevel)
}
try
{
log.channels_.insert({"file", std::unique_ptr<Channel>(new FileChannel(filename, logLevel))});
log.channels_.insert({"file", std::unique_ptr<Channel>(new FileChannel(filename, mode, logLevel))});
}
catch (const std::exception &e)
{

View File

@ -28,9 +28,9 @@ class Log
Log &operator=(const Log &other) = delete;
Log &&operator=(const Log &&other) = delete;
static void setFileChannel(const std::string &filename, LogLevel logLevel = LogLevel::LOGLVL_TRACE);
static void setFileChannel(const std::string &filename, std::ios_base::openmode mode = std::ios_base::app, LogLevel logLevel = LogLevel::LOGLVL_TRACE);
static void setStdoutChannel(LogLevel logLevel = LogLevel::LOGLVL_TRACE);
void log(LogLevel level, const std::string &message, const std::string &channel = "stdout",
const std::map<std::string, std::string> &context = {});

View File

@ -16,8 +16,9 @@ int main(int argc, char **argv)
std::cerr << "Usage: " << argv[0] << " <config_file_path>\n"; // NOLINT
return 1;
}
Log::setFileChannel("webserv.log", LogLevel::LOGLVL_WARN);
Log::setStdoutChannel(LogLevel::LOGLVL_TRACE);
Log::setFileChannel("webserv.log", std::ios_base::app, LogLevel::LOGLVL_TRACE);
Log::setStdoutChannel(LogLevel::LOGLVL_INFO);
LOG_INFO("\n======================\nStarting webserv...\n======================\n");
ConfigManager::getInstance().init(argv[1]); // NOLINT
Server server(ConfigManager::getInstance());
server.start();