开发产品中都会用到日志记录,但是又会碰到日志文件大小有所限制,针对这样的功能,本人写了一个日志文件操作类,实现功能:
1. 记录日志到可写目录,可以按照不同参数保存到不同目录
2. 日志目前限制512K,超过这个大小后,会截取原来一半,较早的一半日志丢弃,这个限制只要修改一下那个宏即可
3.每次运行日志用特殊符号分开,方便查看
4.考虑到日志上传时,需要一次完整的运行记录,所以在截取时会做下判断,至少会保存一次完整日志,所以如果是那种进程
一直不退出的就不太适用了(需要自己改下),因为上传时,由于要保留完整记录,所以不能对未满一次的日志进行截取。以下是实现代码。
5.支持多线程并发调用
cpp实现
#include "stdafx.h"
#include "ComLogToFile.h"
#define LOG_MAXLEN 2048
#define PROCESS_LOG_BEG "**********************************InitLogFile**********************************\n"
#define PROCESS_LOG_END "**********************************EndLogFile***********************************\n\n"
//最大512K
#define MAX_LOG_FILESIZE 512 * 1024
static HANDLE g_hDALogEvent = NULL;
static TCHAR g_szLogFilePath[MAX_PATH] = {0};
static BOOL g_bLogInit = FALSE;
CDALogFile::CDALogFile()
{
}
CDALogFile::~CDALogFile()
{
}
void CDALogFile::vFileFlat(const char *pContent, int nLen)
{
if(NULL == pContent || nLen < 0)
return ;
int nHalf = nLen >> 1;//取一半大小为判断依据
int nMoveLen = strlen(PROCESS_LOG_BEG);
const char *pSearch = pContent;
while(pSearch != NULL)
{
pSearch = strstr(pSearch, PROCESS_LOG_BEG);
if(pSearch != NULL)
{
int OffsetSize = (int)(pSearch - pContent);
if(OffsetSize >= nHalf)
{
//由于找的是BEG,所以至少还留有一条
FILE *filelog = NULL;
//w+用于清空文件,并以写方式打开
if(_tfopen_s(&filelog, g_szLogFilePath, _T("w+")) == 0)
{
//写留下的最新一半日志
fwrite(pSearch, sizeof(char), nLen - OffsetSize, filelog);
fflush(filelog);
fclose(filelog);
}
break;
}
//Search前进
pSearch += nMoveLen;
}
}
}
void CDALogFile::vCheckFileSize()
{
if(WaitForSingleObject(g_hDALogEvent, 2000) == WAIT_TIMEOUT)
{
return;
}
FILE *filelog = NULL;
//只读打开,仅用来获取大小和文件内容
if(_tfopen_s(&filelog, g_szLogFilePath, _T("r")) == 0)
{
if(fseek(filelog, 0, SEEK_END) == 0)
{
//获取文件大小
long nfsize = ftell(filelog);
if(nfsize >= MAX_LOG_FILESIZE)
{
//超过最大限制,减少内容
char *pStr = new char[nfsize];
if(pStr)
{
fseek(filelog, 0, SEEK_SET);
int nReaded = fread(pStr, sizeof(char), nfsize, filelog);
//只有nReaded小于bufSize时才可置结束符
//代替ZeroMemory pStr, ZeroMemory比较费时
if(nReaded < nfsize)
{
pStr[nReaded] = '\0';
}
//close文件,并指针=NULL
fclose(filelog);
filelog = NULL;
//日志内容减去一半(如果超过一条记录)
vFileFlat(pStr, nReaded);
//free buffer
delete [] pStr;
}
}
}
}
//不需要压缩的这里close
if(filelog)
{
fclose(filelog);
}
SetEvent(g_hDALogEvent);
}
string CDALogFile::ts2ms(LPCTSTR szSrc, int cchWideChar /* = -1 */)
{
string strDst;
if ( NULL == szSrc || 0 == cchWideChar ){
return strDst;
}
#ifdef _UNICODE
char* pBuff = NULL;
int nLen = WideCharToMultiByte(CP_ACP, 0, szSrc, cchWideChar, NULL, 0, NULL, NULL);
if ( nLen > 0 ){
pBuff = new char[nLen + 1];
if ( pBuff ){
WideCharToMultiByte(CP_ACP, 0, szSrc, cchWideChar, pBuff, nLen, NULL, NULL);
pBuff[nLen] = 0;
strDst.assign(pBuff);
delete[] pBuff;
}
}
#else
strDst.assign(szSrc);
#endif
return strDst;
}
void CDALogFile::vFormatTime(TCHAR *szOut, int nLen)
{
SYSTEMTIME stime;
GetLocalTime(&stime);
_stprintf_s(szOut, nLen, _T("%02d-%02d %02d:%02d:%02d.%03d:"),
stime.wMonth, stime.wDay, stime.wHour, stime.wMinute, stime.wSecond, stime.wMilliseconds);
}
void CDALogFile::vWriteFile(const char *szStr, int len /* = -1 */)
{
if(WaitForSingleObject(g_hDALogEvent, 2000) == WAIT_TIMEOUT)
{
OutputDebugString(_T("!!!!!WriteLogTimeOut!!!!!"));
return;
}
if(len == -1)
{
len = strlen(szStr);
}
FILE *filelog = NULL;
if(_tfopen_s(&filelog, g_szLogFilePath, _T("a")) == 0)
{
fwrite(szStr, sizeof(char), len, filelog);
fflush(filelog);
fclose(filelog);
}
SetEvent(g_hDALogEvent);
}
void CDALogFile::InitLogFile(const TCHAR *sAppKey)
{
if(!g_bLogInit)
{
g_hDALogEvent = CreateEvent(NULL, FALSE, TRUE, NULL);
TCHAR szPath[MAX_PATH];
if(SUCCEEDED(SHGetFolderPath(NULL,
CSIDL_COMMON_APPDATA|CSIDL_FLAG_CREATE,
NULL,
0,
szPath)))
{
_tcscat_s(szPath, MAX_PATH, _T("\\TestLog"));
if(_taccess(szPath, 0x00) != 0)
{
CreateDirectory(szPath, NULL);
}
if(_tcslen(sAppKey) < 100)
{
_stprintf_s(g_szLogFilePath, MAX_PATH, _T("%s\\%s\\"), szPath, sAppKey);
}else
{
TCHAR szCopy[MAX_PATH] = {0};
_tcsnccpy_s(szCopy, MAX_PATH, sAppKey, 100);
_stprintf_s(g_szLogFilePath, MAX_PATH, _T("%s\\%s\\"), szPath, szCopy);
}
if(_taccess(g_szLogFilePath, 0x00) != 0)
{
CreateDirectory(g_szLogFilePath, NULL);
}
TCHAR LogFile[MAX_PATH] = {0};
_stprintf_s(LogFile, MAX_PATH, _T("dalog_%s.log"), sAppKey);
//SYSTEMTIME stime;
//GetLocalTime(&stime);
//_stprintf_s(LogFile, MAX_PATH, _T("%04d-%02d-%02d.log"), stime.wYear, stime.wMonth, stime.wDay);
_tcscat_s(g_szLogFilePath, MAX_PATH, LogFile);
}
g_bLogInit = TRUE;
//放在写日志之前
vCheckFileSize();
vWriteFile(PROCESS_LOG_BEG);
}
}
void CDALogFile::GetLogFile(TCHAR *szPath, int nLen)
{
if(szPath && nLen > 0)
{
_tcscpy_s(szPath, nLen, g_szLogFilePath);
}
}
//日志接口
void CDALogFile::Log(const TCHAR* ptzFormat, ...)
{
if(!g_bLogInit)
{
return ;
}
#pragma warning(disable:4996)
if(!ptzFormat)
return;
va_list vlArgs;
TCHAR tzText[LOG_MAXLEN];
TCHAR tzText2[LOG_MAXLEN + 256];
TCHAR szTimesFormat[100];
vFormatTime(szTimesFormat, 100);
va_start(vlArgs, ptzFormat);
if(_vsctprintf(ptzFormat,vlArgs) < LOG_MAXLEN)
{
#ifdef _UNICODE
vswprintf_s(tzText, LOG_MAXLEN, ptzFormat, vlArgs);
#else
_vstprintf_s(tzText, LOG_MAXLEN, ptzFormat, vlArgs);
#endif
}else
{
_tcscpy_s(tzText, LOG_MAXLEN, _T("Input va_list too long, won't show the values!!!!!!!!"));
}
_stprintf_s(tzText2, LOG_MAXLEN + 256, _T("%s[%d-%d]\t%s\n"), szTimesFormat, GetCurrentProcessId(), GetCurrentThreadId(), tzText);
#ifdef _TRACK
OutputDebugString(tzText2);
#endif
string logs = ts2ms(tzText2);
vWriteFile(logs.c_str(), logs.length());
va_end(vlArgs);
#pragma warning(default:4996)
}
void CDALogFile::Release()
{
if(g_bLogInit)
{
vWriteFile(PROCESS_LOG_END);
CloseHandle(g_hDALogEvent);
g_bLogInit = FALSE;
}
}测试代码:
int nOverNum = 0;
DWORD WINAPI LogThreadProc(
LPVOID lpParameter
)
{
srand((unsigned)time(NULL));
int times = rand() % 200;
int i = 0;
printf("Thread id %d times %d\n", GetCurrentThreadId(), times);
while( i++ < times)
{
CDALogFile::Log(_T("Thread in times %d, i = %d"), times, i);
if(i > 20)
{
CDALogFile::Log(_T("Thread in i is bigger, 测试数据,we should check this sen!!!"), times, i);
}
int sleepT = rand() % 20;
Sleep(sleepT * 100);
}
nOverNum ++;
printf("Thread id %d out, number ; %d!\n", GetCurrentThreadId(), nOverNum);
return 0;
}
void TestLogsFile()
{
OutputDebugString(_T("Before InitLogFile"));
CDALogFile::InitLogFile(_T("MyLogs"));
OutputDebugString(_T("After InitLogFile"));
CDALogFile::Log(_T("Test1"));
OutputDebugString(_T("Test1"));
CDALogFile::Log(_T("Test2"));
OutputDebugString(_T("Test2"));
CDALogFile::Log(_T("Test3"));
OutputDebugString(_T("Test3"));
for (int i = 0; i < 10; i++)
{
CreateThread(NULL, 0, LogThreadProc, NULL, 0, NULL);
Sleep(500);
}
getchar();
CDALogFile::Release();
}用上面的测试代码跑了很多遍,暂未发现问题,欢迎大家指正代码规范或者bug上面的错误。
本文介绍了一种使用C++实现的日志管理系统,该系统能够自动处理日志文件大小限制问题,支持多线程并发调用,并提供了一段测试代码来验证其功能。
1606

被折叠的 条评论
为什么被折叠?



