兼容Windows与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;
}

本文永久更新链接地址:

相关内容