|
void WriteLog(int Priority,const char* Fmt,...){
if (Priority < LOG_EMERG || Priority >= LOG_LAST_PRIORITY) {
return;
}
__time64_t ltime;
_time64(<ime);
|
|
//if (!(pLogFile = fopen(pszLogFileName,"a+"))) {
// return ;
//}
|
|
char szDateBuf[MAX_PATH];
strcpy(szDateBuf,_ctime64(<ime));
szDateBuf[strlen(szDateBuf)-1]='/0'; //remove the
va_list vaa;
va_start(vaa,Fmt);
fprintf(pLogFile,"[%s][%08ld]",szDateBuf,GetCurrentThreadId());
vfprintf(pLogFile,Fmt,vaa);
fprintf(pLogFile,"/n");
fflush(pLogFile);
va_end(vaa);
|
|
//fclose(pLogFile);
|
|
}
|
|
注意表格中注释部分,若用此注释部分,便可将下面的OpenLog和CloseLog省去,但这样将导致明显的效率下降,可以从本文提供的事例中看出。
此函数中记录了日志生成的日期时间和调用的线程ID值。若要查看其它变量或函数值可以通过本函数的第三个函数实现(见本文事例)。
|
|
FILE* OpenLog(char* pszLogFileName){
if (!(pLogFile = fopen(pszLogFileName,"a+"))){
return NULL;
}
return pLogFile;
}
|
|
此函数仅调用C语言的文件打开函数,若成功则返回文件指针
|
|
int CloseLog(){
int nErr = 0;
if (nErr = fclose(pLogFile)) {
return nErr;
}
return 0;
}
|
|
此函数调用C语言的文件关闭函数,成功时返回0,否则非0值。
|
|
#include "stdafx.h"
#include "zCommon.h"
#include <iostream>
using namespace std;
void myfunc(int var,char* ch){
WriteLog(2,"[0x%08x][%s][%s][var = %d][ch = %s]",(long)myfunc,"myfunc",__FILE__,var,ch);
}
int _tmain(int argc, _TCHAR* argv[])
{
struct tm tmNow;
//gettimeofday(tmNow);
char* str = "This is test";
//Open log
OpenLog("c://zLog.log");
//get the start of log
DWORD dwStart = GetTickCount();
for(int i = 0; i < 50000; i++){
//Write log
WriteLog(2,"[0x%08x][%s]",(long)_tmain,"_tmain");
myfunc(10,"char");
}
//time consuming
cout << GetTickCount() - dwStart <<endl; //4884
//Close log
CloseLog();
system("pause");
return 0;
}
|
|
函数的调用顺序为OpenLog,WriteLog,CloseLog,一定不能弄错。此外还调用了函数GetTickCount,用此函数可以比较一下有无OpenLog/CloseLog的效率。
|
2325



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



