AsyncLogger

#ifndef ASYNC_LOGGER_H
#define ASYNC_LOGGER_H


#include
#include "CMyCriticalSection.h"
#include "LogBlock.h"
#include "ChangeBinaryAndJson.h"
#include "FileLog.h"




class AsyncLogger
{


public:


AsyncLogger( CFileLog    * pLog, CChangeBinaryAndJson* pTool );
~AsyncLogger();


void AddMsgQueue( const char * szTitle, const char * szText, int iTextLen );
int WriteOneLog();
bool QuitLogger();


private:


void WriteBlock( LogBlock& stBlock );


private:


std::deque m_MsgQueue;


bool m_bQuitLogThread;
mylib::CMyCriticalSection m_criticalMsgQueue;


CFileLog    * m_pBusinessClearTextLog;   // 业务明文日志 
CChangeBinaryAndJson* m_pBinaryToJson; // 二进制与JSON格式互转类
};

#endif

#include "stdafx.h"
#include "AsyncLogger.h"
#include


unsigned int _stdcall  WriteLogThread(void* p);


AsyncLogger::AsyncLogger( CFileLog * pLog, CChangeBinaryAndJson* pTool  )
: m_bQuitLogThread(false),m_pBusinessClearTextLog( pLog ), 
m_pBinaryToJson( pTool )
{
unsigned int iLogThreadId;
HANDLE hLogThread = (HANDLE )_beginthreadex( NULL, 0, 
WriteLogThread, this, 0, &iLogThreadId );
if ( hLogThread == INVALID_HANDLE_VALUE )
{
printf( "error!!!!!!WriteLogThread create failed!!!\n" );
}
}


AsyncLogger::~AsyncLogger()
{
m_bQuitLogThread = true;
}


bool AsyncLogger::QuitLogger()
{
return m_bQuitLogThread;
}


void AsyncLogger::AddMsgQueue( const char * szTitle, 
const char * szText, int iTextLen )
{
LogBlock stBlock;
stBlock.sTitle = szTitle;
stBlock.sText = std::string( szText, iTextLen );
stBlock.sTime = CFileLog::FomartSystemTime();


{
mylib::CCriticalSectionGuard guard( m_criticalMsgQueue );
m_MsgQueue.push_back( stBlock );
}
}


int AsyncLogger::WriteOneLog()
{
LogBlock stBlock;
int iGot = 0;
{
mylib::CCriticalSectionGuard guard( m_criticalMsgQueue );
if ( !m_MsgQueue.empty() )
{
stBlock = m_MsgQueue.front();
m_MsgQueue.pop_front();
++iGot;
}
}
if ( iGot > 0 )
{
WriteBlock( stBlock );
}
return iGot;
}




void AsyncLogger::WriteBlock( LogBlock& stBlock )
{
if ( m_pBinaryToJson ==  NULL 
|| m_pBusinessClearTextLog == NULL )
{
return;
}

std::string strJsonText;
std::string strErrors;
if ( m_pBinaryToJson->BinaryToJson( stBlock.sText.c_str(),  
stBlock.sText.length(), strJsonText, strErrors ) )
{
stBlock.sText = strJsonText;
m_pBusinessClearTextLog->WriteLogBlock( stBlock );
}
else
{
m_pBusinessClearTextLog->WriteLog( stBlock.sTitle, 
strErrors.c_str(), strErrors.length() );
}
}






unsigned int _stdcall  WriteLogThread(void* p)
{
AsyncLogger* pThis = (AsyncLogger*)p;
while ( !pThis->QuitLogger() )
{
int iGot = 0;
iGot = pThis->WriteOneLog();


if ( !iGot )
{
//printf( "queu is empty , sleep 1s \n" );
Sleep( 1000 );
}
}
return 0;
}





你可能感兴趣的:(BinaryRecorder)