歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 兼容Windows與Linux的寫日志代碼

兼容Windows與Linux的寫日志代碼

日期:2017/3/1 9:35:50   编辑:Linux編程

以下代碼可在Windows與Linux上正確編譯和執行。

日志按照QQ號和日期為單位分類進行存放,可防止不同QQ號的日志混放在一起,以及日志隨著時間逐漸變大等問題。

#include <stdio.h>
#include <stdarg.h>
#include <time.h>

#ifdef WIN32
#include <direct.h>
#include <io.h>
#else
#include <stdarg.h>
#include <sys/stat.h>
#include <unistd.h>
#endif

typedef unsigned int UINT;

void PrintDebugMsg(UINT uin, const char* msg, ...)
{
// 非debug版本,直接返回
#ifndef DEBUG
return;
#endif

char szMessage[1024] = { 0 };
va_list pArg;
va_start(pArg, msg);
#ifdef WIN32
_vsnprintf(szMessage, 1023, msg, pArg);
#else
vsnprintf(szMessage, 1023, msg, pArg);
#endif
va_end(pArg);

time_t nNowTime = time(NULL);
tm *pDate = localtime(&nNowTime);
if (pDate==NULL) return;

int nYear = 1900 + pDate->tm_year;
int nMonth = pDate->tm_mon+1;
int nDay = pDate->tm_mday;
int nHour = pDate->tm_hour;
int nMin = pDate->tm_min;
int nSec = pDate->tm_sec;

// 日志按QQ和天來存放

char* pDirPath = NULL;
char szLogPath[1024] = { 0 };
#ifdef WIN32
pDirPath = "E:\\debugLog";
_snprintf(szLogPath, 1023, "%s\\p%u_%04d-%02d-%02d.log", pDirPath, uin, nYear, nMonth, nDay);
// 目錄不存在創建目錄
if (_access(pDirPath,0)!=0)
if (_mkdir(pDirPath)!=0) return;
#else
pDirPath = "/home/game/log/debugLog";
snprintf(szLogPath, 1023, "%s/p%u_%04d-%02d-%02d.log", pDirPath, uin, nYear, nMonth, nDay);
if (access(pDirPath,0)!=0)
if (mkdir(pDirPath, 0755)!=0) return;
#endif

// 追加的方式打開日志
FILE* pLoger=fopen(szLogPath, "a");
if (pLoger==NULL) return;

// 時間
fprintf(pLoger, "[%02d:%02d:%02d] ", nHour, nMin, nSec);

// 具體日志內容
fprintf(pLoger, szMessage);

fprintf(pLoger, "\n");
fclose(pLoger);
}


int main(int argc, char* argv[])
{
char* pFunctionName = "MySQL::OnExcute";
int nLineNum = 54;
char* pMsg = "select * from Name";
while(nLineNum--) PrintDebugMsg(12345678, "%s %d %s",pFunctionName, nLineNum, pMsg);

return 0;
}

Copyright © Linux教程網 All Rights Reserved