前言:
C/C++提供了四个宏__FUNCTION__ ,__TIME__ ,__LINE__ ,__FILE__定位程序运行时的错误。程序预编译时预编译器将用所在的函数名,文件名和行号替换。当运行时错误产生后这三个宏分别能返回错误所在的函数,所在的文件名和所在的行号。
_FUNCTION__ :函数名
__TIME__ :文件运行的时间 (显示编译的时间)
__LINE__ :所在行数
__FILE__:文件的名字
如
#include <stdio.h>
int main(int, char**)
{
char str3[256] = { 0 };
sprintf_s(str3, "This fake error is on %s in %s in func %s on line %d.", __TIME__, __FILE__, __FUNCTION__, __LINE__);
printf("%s", str3);
PrintLog(str3);
return 0;
}
This fake error is on 14:30:56 in f:\test\stdtest\test\test.cpp in func main on line 18.
printf 和sprintf 见:CSDNhttps://mp.csdn.net/mp_blog/creation/editor/121746323
1.日志打印函数,在日志里添加上C++的编译宏,如上面的4个宏
void PrintLog(string str)
{
SYSTEMTIME sys;
::GetLocalTime(&sys);
std::ofstream ofs;
ofs.open("driver.log", std::ios_base::in | std::ios_base::app);
ofs << "[" << sys.wHour << ":" << sys.wMinute << ":" << sys.wSecond << "." << sys.wMilliseconds << "]\t" << str << std::endl;
ofs.close();
}
2.日志管理
对于日志文件,一般有两种处理方式,一种就是每次启动软件,清空之前的文件;另一种就是累增。前一种的缺点是,长跑测试中,软件崩溃,后来者不小心重启了软件,导致历史日志丢失;后一种的缺陷是,长跑测试,日志文件累增过大,导致磁盘空间不足。
针对上面两种情况的优缺点,我设计了一种循环记录的方法,类似“行车记录仪”。
bool CreateLogFile()
{
long fileSize = 0;
HANDLE handle = CreateFile(L"driver.log", FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
if (handle != INVALID_HANDLE_VALUE)
{
fileSize = GetFileSize(handle, NULL);
cout << fileSize << endl;
CloseHandle(handle);
}
if (fileSize < 200 * 1024 * 1024) // filesize的单位是byte,设定门限是200M
{
PrintLog("---reboot----");
}
else
DeleteFile(L"driver.log");
return true;
}