← source index

src/Log.cpp

40 lines  ·  1.1 K  ·  cpp
#include "Log.h"

void Log::init(std::string_view path, const std::string_view filename) 
{
    //Ideally, check if file has reached a max size and if so, create a new one, check if the maximum 
    // number of log files was exceeded and remove the oldest one too. Outside the scope for now.
    
    std::lock_guard<std::mutex> lock(mMtx);

    if(mLogFile.is_open()) return;

    mLogPath = path;
    mLogFileName = filename;
    mLogFile.open (mLogPath + "/" + mLogFileName, std::ofstream::out | std::ofstream::app);
}

bool Log::log(const LogStatus& status, std::string_view msg, bool flush)
{
    std::lock_guard<std::mutex> lock(mMtx);

    if(!mLogFile.is_open())
        return false;
    
    std::string timeString = Helper::time_now();
    std::stringstream logMsg("");
    logMsg << timeString << ": [" << mLogStatusStr[(int) status] << "]: " << std::string(msg) << '\n';

    mLogFile << logMsg.str();
    if(flush) mLogFile.flush();

    return true;
}

Log::~Log()
{
    std::lock_guard<std::mutex> lock(mMtx);

    if(mLogFile.is_open())
        mLogFile.close();
}