以下代碼可在windows與linux上正確編譯和執行。
日誌按照QQ號和日期為單位分類進行存放,可防止不同QQ號的日誌混放在一起,以及日誌隨著時間逐漸層大等問題。
1 #include <stdio.h> 2 #include <stdarg.h> 3 #include <time.h> 4 5 #ifdef WIN32 6 #include <direct.h> 7 #include <io.h> 8 #else 9 #include <stdarg.h>10 #include <sys/stat.h>11 #include <unistd.h>12 #endif13 14 typedef unsigned int UINT;15 16 void PrintDebugMsg(UINT uin, const char* msg, ...)17 {18 // 非debug版本,直接返回19 #ifndef DEBUG20 return;21 #endif22 23 char szMessage[1024] = { 0 };24 va_list pArg;25 va_start(pArg, msg);26 #ifdef WIN3227 _vsnprintf(szMessage, 1023, msg, pArg);28 #else29 vsnprintf(szMessage, 1023, msg, pArg);30 #endif 31 va_end(pArg);32 33 time_t nNowTime = time(NULL); 34 tm *pDate = localtime(&nNowTime);35 if (pDate==NULL) return;36 37 int nYear = 1900 + pDate->tm_year;38 int nMonth = pDate->tm_mon+1;39 int nDay = pDate->tm_mday;40 int nHour = pDate->tm_hour;41 int nMin = pDate->tm_min;42 int nSec = pDate->tm_sec;43 44 // 日誌按QQ和天來存放45 46 char* pDirPath = NULL;47 char szLogPath[1024] = { 0 };48 #ifdef WIN3249 pDirPath = "E:\\debugLog";50 _snprintf(szLogPath, 1023, "%s\\p%u_%04d-%02d-%02d.log", pDirPath, uin, nYear, nMonth, nDay);51 // 目錄不存在建立目錄52 if (_access(pDirPath,0)!=0)53 if (_mkdir(pDirPath)!=0) return;54 #else55 pDirPath = "/home/game/log/debugLog";56 snprintf(szLogPath, 1023, "%s/p%u_%04d-%02d-%02d.log", pDirPath, uin, nYear, nMonth, nDay);57 if (access(pDirPath,0)!=0)58 if (mkdir(pDirPath, 0755)!=0) return;59 #endif60 61 // 追加的方式開啟日誌62 FILE* pLoger=fopen(szLogPath, "a");63 if (pLoger==NULL) return;64 65 // 時間 66 fprintf(pLoger, "[%02d:%02d:%02d] ", nHour, nMin, nSec);67 68 // 具體日誌內容69 fprintf(pLoger, szMessage);70 71 fprintf(pLoger, "\n"); 72 fclose(pLoger);73 }74 75 76 int main(int argc, char* argv[])77 {78 char* pFunctionName = "MySQL::OnExcute";79 int nLineNum = 54;80 char* pMsg = "select * from Name";81 while(nLineNum--) PrintDebugMsg(12345678, "%s %d %s",pFunctionName, nLineNum, pMsg);82 83 return 0;84 }