windows 下编程实现打印日志

log.h

#pragma once  
#include <string>  
#include <Windows.h>  
#include <stdio.h>
using std::string;
using std::wstring;
extern const char* g_pLogPath ;
#define LOG_ENABLE        //打印日志启用开关

string GetTime();
string  U2A(const wstring& str);
void Write(const char* pSourcePath, const char* pFunName,const long lLine, const char* pLogText);
void  Write(const char* pSourcePath, const char* pFunName, const long lLine, const wchar_t* pLogText);

#ifdef LOG_ENABLE  
#define writeLog(x)             Write(__FILE__, __FUNCTION__, __LINE__, x)  

#else 
#define writeLog(x) 

#endif 

log.cpp

#include  "log.h"
#include "StdAfx.h"  
#include <string>  
#include <Windows.h>  
#include <stdio.h>
using std::string;
using std::wstring;

const char* g_pLogPath = "C:\\TestLog.log";

string  GetTime()
{
    SYSTEMTIME st;
    ::GetLocalTime(&st);
    char szTime[26] = { 0 };
    sprintf_s(szTime, "%04d-%02d-%02d %02d:%02d:%02d %d  ", st.wYear, st.wMonth, st.wDay, st.wHour, \
        st.wMinute, st.wSecond, st.wMilliseconds);
    return szTime;
}

string  U2A(const wstring& str)
{
    string strDes;
    if (str.empty())
        return strDes;
    int nLen = ::WideCharToMultiByte(CP_ACP, 0, str.c_str(), str.size(), NULL, 0, NULL, NULL);
    if (0 == nLen)
        return strDes;
    char* pBuffer = new char[nLen + 1];
    memset(pBuffer, 0, nLen + 1);
    ::WideCharToMultiByte(CP_ACP, 0, str.c_str(), str.size(), pBuffer, nLen, NULL, NULL);
    pBuffer[nLen] = '\0';
    strDes.append(pBuffer);
    delete[] pBuffer;

}

void Write(const char* pSourcePath, const char* pFunName, const long lLine, const char* pLogText)
{
    if (pLogText == NULL)
        return;
    int nLogLen = strlen(pLogText);
    if (nLogLen == 0)
        return;
    int nSourceLen = strlen(pSourcePath);
    int nFunLen = strlen(pFunName);
    char szLine[10] = { 0 };
    sprintf_s(szLine, "%ld", lLine);
    int nLineLen = strlen(szLine);
    int nSpaceLen = 80 - nSourceLen - nFunLen - nLineLen;
    string strTime = GetTime();
    FILE* fp = NULL;
    fopen_s(&fp, g_pLogPath, "a+");
    fwrite(strTime.c_str(), strTime.size(), 1, fp);
    fwrite(" ", 1, 1, fp);
    fwrite(pSourcePath, nSourceLen, 1, fp);
    for (int i = 0; i<nSpaceLen; ++i)
        fwrite(" ", 1, 1, fp);
    fwrite(pFunName, nFunLen, 1, fp);
    fwrite(" ", 1, 1, fp);
    fwrite(szLine, nLineLen, 1, fp);
    fwrite(": ", 2, 1, fp);
    fwrite(pLogText, nLogLen, 1, fp);
    fwrite("\n", 1, 1, fp);
    fclose(fp);
}

void  Write(const char* pSourcePath, const char* pFunName, const long lLine, const wchar_t* pLogText)
{
    string strLogText = U2A(pLogText);
    Write(pSourcePath, pFunName, lLine, strLogText.c_str());
}

猜你喜欢

转载自www.cnblogs.com/nanqiang/p/8991524.html
今日推荐