相容windows與linux的寫日誌代碼

來源:互聯網
上載者:User

以下代碼可在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 }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.