/*********************************************************
/* 相关日志操作和定义
/*********************************************************/
#define Log_Info L"Info"
#define Log_Error L"Error"
#define Log_Warning L"Warning"
void WriteLog(CString strLog, CString strType, const char* chFun, const int nLine);
void DeleteLog(); //删除日志记录
//宏定义 写日志用这个
#define Writelog(strLog, strType) WriteLog(strLog, strType, __FUNCTION__, __LINE__);
/***********************************************/
/* 函数:用于写日志
/* 参数:strLog:日志内容
/* strType:日志类型 如 Info(信息) Error(错误) Warning(警告)
/***********************************************/
void WriteLog(CString strLog, CString strType, const char* chFun, const int nLine)
{
CString strPath = g_strPath + L"\\Log.txt"; //log路径
CString strTime = CTime::GetCurrentTime().Format(L"[%Y-%m-%d %H:%M:%S]");
USES_CONVERSION;
char szStr[MAX_PATH] = { 0 };
strcpy_s(szStr, sizeof(szStr), W2A(strPath));
char *sPath = szStr;
CString strLine(L"");
strLine.Format(L"[%d]", nLine);
CString strFun(L"");
strFun = chFun;
CString strText;
strText = L"[" + strType + L"]" + strTime + L"[" + strFun + L"]" + strLine + strLog + L"\r\n";
FILE *fp = NULL;
fopen_s(&fp, sPath, "at+"); //以文本形式追加
if (NULL == fp)
{
return;
}
int nCnt = fp->_cnt;
char Text[MAX_PATH] = { 0 };
strcpy_s(Text, sizeof(Text), W2A(strText));
fprintf(fp, "%s", Text);
fflush(fp); //除读写缓冲区,需要立即把输出缓冲区的数据进行物理写入时
fclose(fp);
}
/***********************************************/
/* 函数:每月的2号,12号,22号清空日记记录
/***********************************************/
void DeleteLog()
{
char chDay = '2';
CString strPath = g_strPath + L"\\Log.txt"; //log路径
CTime ct = CTime::GetCurrentTime();
CFile file;
if (file.Open(strPath, CFile::modeReadWrite| CFile::modeNoTruncate))
{
file.Seek(0, CFile::begin);
//结构体格式读取
file.Read(&chDay, sizeof(chDay));
if (chDay == ct.GetDay())
{
chDay += 10;
if (chDay > 30)
{
chDay = 2;
}
file.SetLength(0);
file.Seek(0, CFile::begin);
file.Write(&chDay, sizeof(chDay));
file.Write("\r\n", sizeof("\r\n"));
}
file.Close();
}
else
{
//如果不存在则创建Log
if (ct.GetDay() >= 22)
{
chDay = 2;
}
else if (ct.GetDay() >= 12)
{
chDay = 22;
}
else
{
chDay = 12;
}
CFile file;
if (file.Open(strPath, CFile::modeCreate | CFile::modeReadWrite
| CFile::modeNoTruncate))
{
file.Seek(0, CFile::begin);
file.Write(&chDay, sizeof(chDay));
file.Write("\r\n", sizeof("\r\n"));
file.Close();
}
}
}
Writelog(L"初始化", Log_Info);
结果:
[Info][2018-12-27 17:12:52][CXXDlg::OnInitDialog][502]初始化