用到前文中的循环队列模板
/*
** File name: LogWriter.h
** Author:
** Date: 2024-11-4
** Brief: 日志写入类
** Note: 日志写入类,负责将日志写入文件和连接客户端。
** Copyright (C) 1392019713@qq.com All rights reserved.
*/
#pragma once
#include "../../Algorithm/Include/LoopQueue.h"
#include "../../System/Include/Singleton.h"
#include "LogStream.h"
#include <string>
#include <thread>
class CByteArray
{
public:
CByteArray();
~CByteArray();
public:
std::string m_strMsg;
};
class CLogWriter
{
DECLARE_UNMANGED_SINGLETON_X(CLogWriter)
private:
CLogWriter();
public:
~CLogWriter();
bool WriteLog(const CByteArray& rByteArray);
void SetRunning(bool bIsRunning);
bool IsRunning() const;
void StartWriteFileThread();
void StartWriteRemoteThread();
static void WriteFileThreadFunc(CLogWriter* pLogWriter);
static void WriteRemoteThreadFunc(CLogWriter* pLogWriter);
private:
std::unique_ptr<std::thread> m_pWriteFileThread;
CLoopQueue<CByteArray> m_writeFileloopQueue;
std::unique_ptr<std::thread> m_pWriteRemoteThread;
CLoopQueue<CByteArray> m_writeRemoteloopQueue;
bool m_bIsRunning;
};
#include "../Include/LogWriter.h"
#include <fstream>
IMPLEMENT_UNMANED_SINGLETON_X(CLogWriter)
CByteArray::CByteArray()
{
}
CByteArray::~CByteArray()
{
}
/// /
CLogWriter::CLogWriter()
{
m_bIsRunning = true;
m_writeFileloopQueue.Create(100);
}
CLogWriter::~CLogWriter()
{
m_bIsRunning = false;
m_pWriteFileThread->join();
//m_pWriteRemoteThread->join();
}
bool CLogWriter::WriteLog(const CByteArray& rByteArray)
{
bool bRet = m_writeFileloopQueue.EnQueue(rByteArray);
if (!bRet)
{
return false;
}
bRet = m_writeRemoteloopQueue.EnQueue(rByteArray);
if (!bRet)
{
return false;
}
return true;
}
void CLogWriter::SetRunning(bool bIsRunning)
{
m_bIsRunning = bIsRunning;
}
bool CLogWriter::IsRunning() const
{
return m_bIsRunning;
}
void CLogWriter::StartWriteFileThread()
{
m_pWriteFileThread = std::make_unique<std::thread>(&CLogWriter::WriteFileThreadFunc, this);
}
void CLogWriter::StartWriteRemoteThread()
{
}
void CLogWriter::WriteFileThreadFunc(CLogWriter* pLogWriter)
{
while (pLogWriter->IsRunning())
{
if(pLogWriter->m_writeFileloopQueue.GetSize() <= 0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
continue;
}
CByteArray byteArray;
if(!pLogWriter->m_writeFileloopQueue.DeQueue(byteArray))
{
continue;
}
if (!CLogSystem::Instance().IsSaveToFile())
{
continue;
}
//if (std::filesystem::exists(logfilepath))
//{
// auto fileSize = GetFileSize(logfilepath);
// if (fileSize > static_cast<size_t>(5 * 1024) * 1024)
// {
// strftime(tdatetime, sizeof(tdatetime), "%Y%m%d%H%M%S", &now_tm);
// auto newlogfilepath = "test.log" + std::string(tdatetime)).u8string();
// std::filesystem::rename(logfilepath, newlogfilepath);
// }
//}
std::ofstream file(CLogSystem::Instance().GetFileName(), std::ios::app);
if (!file.is_open())
{
pLogWriter->SetRunning(false);
break;
}
file << byteArray.m_strMsg;
}
}
void CLogWriter::WriteRemoteThreadFunc(CLogWriter* pLogWriter)
{
while (pLogWriter->IsRunning())
{
}
}