0
点赞
收藏
分享

微信扫一扫

VC把日志保存在内存中的例子

elvinyang 2022-07-27 阅读 78


李国帅 于2009-07-08

代码说明:

1、使用map容器防止日志。

2、使用静态函数进行调用

3、在外部循环删除过多日志。

4、使用临界区保护日志读写

5、日志中包含了部分函数,搜索部分没有填。

调用


CNetLog::AddLog((100, "%s socket=%u\n", __FUNCTION__, fFileDesc);
CNetLog::RemoveLog(100);


头文件


#include <map>
#include <string>
using namespace std;

private:
static using m_pInstance;//使用单件
#ifdef _DEBUG
std::map<INT_PTR, string> m_mapLog;
char m_strDescribe[LOG_LENGTH];//日志前缀
#endif

static void AddLog(int index, const CHAR *format_str, ...);
static void RemoveLog(int


日志删减定义

void CNetLog::AddLog(int index, const CHAR *format_str, ...)
{
#ifdef _DEBUG
_ASSERT(m_pInstance != NULL);
if (m_pInstance == NULL) return;

EnterCriticalSection(&m_pInstance->m_CritSec);

map<INT_PTR, string>& mapLog = m_pInstance->m_mapLog;
char* strDescribe = m_pInstance->m_strDescribe;

int lenMsg = 0;
va_list args;
va_start(args, format_str);
int len = _vscprintf(format_str, args) + 2;
if (len < LOG_LENGTH)
{
lenMsg = vsprintf_s(strDescribe, len, format_str, args);
}
va_end(args);

//sprintf_s(strDescribe,256,"file:%s\t line:%d",pFile,nLine);
mapLog[index] = strDescribe;//

LeaveCriticalSection(&m_pInstance->m_CritSec);
#endif // _DEBUG

}

void CNetLog::RemoveLog(int index)
{
#ifdef _DEBUG
_ASSERT(m_pInstance != NULL);
if (m_pInstance == NULL) return;

EnterCriticalSection(&m_pInstance->m_CritSec);

map<INT_PTR, string>& mapLog = m_pInstance->m_mapLog;

if (mapLog.find(index) != mapLog.end())
{
OutputDebugStringA(mapLog[index].c_str());
mapLog.erase(index);
}
LeaveCriticalSection(&m_pInstance->m_CritSec);

#endif // _DEBUG
}

举报

相关推荐

0 条评论