编程win linux兼容,兼容Windows与Linux的写日志代码

以下代码可在Windows与Linux上正确编译和执行。

日志按照QQ号和日期为单位分类进行存放,可防止不同QQ号的日志混放在一起,以及日志随着时间逐渐变大等问题。

#include

#include

#include

#ifdef WIN32

#include

#include

#else

#include

#include

#include

#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;

}

0b1331709591d260c1c78e86d0c51c18.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值