c++ 记录日志 (升个级)

/*********************************************************
/*	相关日志操作和定义
/*********************************************************/
#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]初始化

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值