简单C++ log 类

class CSimpleLog
{
public:
CSimpleLog( char * strLogFileName )
{
if ( strLogFileName && strlen(m_strLogFileName) )
{
strcpy( m_strLogFileName, strLogFileName );
}




m_fLog = fopen( strLogFileName, "w+b" );




}


~CSimpleLog()
{
if (m_fLog)
{
fclose(m_fLog);
m_fLog=NULL;
}
}


private:


char m_strLogFileName[200];


FILE * m_fLog;


public:


void writeLog( char * pstrLog )
{
if (m_fLog)
{
fwrite( pstrLog, 1, strlen(pstrLog), m_fLog );
fwrite("\r\n",1,2,m_fLog);


fflush( m_fLog );
}
}



 

};

 

 

 

 

一个简单的函数log类:

class CLOG_FUNCTION
{
public:
CLOG_FUNCTION(char * pstrFun)

n++;


for ( int i = 0; i<n-1; i++)
{
printf("-");
}


strfun = pstrFun;
printf((strfun + std::string("-------------------------In \n")).c_str());




}


~CLOG_FUNCTION()
{
n--;


for (int i = 0; i < n; i++)
{
printf("-");
}


printf((strfun + std::string("-------------------------Out \n\n\n")).c_str());




}


std::string strfun;


private:


static int n;
};

 

 

 

 

 

 

 

/

上述简单的经内容写到文件中;

再说明一个将执行代码写到文件中的方法;

直接参考 directshow中的JIF

#define JIF(x) if (FAILED(hr=(x))) \
    {RetailOutput(TEXT("FAILED(0x%x) ") TEXT(#x) TEXT("\n\0"), hr); goto CLEANUP;}

 

 

//简单修改一下:

char* UnicodeToAnsi(const wchar_t* szStr)
{
    int nLen = WideCharToMultiByte(CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL);

    if (nLen == 0)
    {
        return NULL;
    }

    char* pResult = new char[nLen + 1];

    pResult[nLen] = '\0';

    WideCharToMultiByte(CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL);

    return pResult;
}


void Log_To_file(char const* fmt, ...) //也可以作为一个简单log函数,多写介个文件名,就多些几个log文件;
{
    static FILE* fOut = fopen("D:/testLog.txt", "w");
    if (fOut == NULL)
        return;

    SYSTEMTIME st;
    GetLocalTime(&st);
    char szBuf[2048];
    sprintf(szBuf, "[%u-%02u-%02u %02u:%02u:%02u]  ",
        st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
    fwrite(szBuf, 1, strlen(szBuf), fOut);

    va_list args;
    va_start(args, fmt);
    vsnprintf(szBuf, sizeof(szBuf), fmt, args);
    va_end(args);

    fwrite(szBuf, 1, strlen(szBuf), fOut);
    fwrite("\r\n", 1, 2, fOut);
    fflush(fOut);
}


void RetailOutput(TCHAR *szFormat, ...)
{
    TCHAR szBuffer[1024];  // Large buffer for long filenames or URLs
    const size_t NUMCHARS = sizeof(szBuffer) / sizeof(szBuffer[0]);
    const int LASTCHAR = NUMCHARS - 1;

    // Format the input string
    va_list pArgs;
    va_start(pArgs, szFormat);

    // Use a bounded buffer size to prevent buffer overruns.  Limit count to
    // character size minus one to allow for a NULL terminating character.
    _vsntprintf(szBuffer, NUMCHARS - 1, szFormat, pArgs);
    va_end(pArgs);

    // Ensure that the formatted string is NULL-terminated
    szBuffer[LASTCHAR] = TEXT('\0');

    // Display a message box with the formatted string
    OutputDebugString(szBuffer);

#ifdef UNICODE

    char * pstr_szFormat = UnicodeToAnsi(szFormat);

    Log_To_file(pstr_szFormat);

    delete[] pstr_szFormat;
    pstr_szFormat = NULL;

#else
    Log_To_file(pstr_szFormat);
#endif

}


#define JIF(x) {RetailOutput(TEXT(" ") TEXT(#x) TEXT("\n\0")); x; }

#define OUTPUT_SRC(x) {RetailOutput(TEXT(" ") TEXT(#x) TEXT("\n\0")); x; }

void CMFCApplication5Dlg::OnBnClickedButton22()
{
    // TODO: 在此添加控件通知处理程序代码

    char * pstr = NULL;

    JIF(pstr);

    JIF(AfxMessageBox(L""));

    JIF(strcpy(pstr, "123"));

    JIF(if (1)
    {
        AfxMessageBox(L"1");
    });

}
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

上面已经说明了方法,下面简单封装一下:

也可以直接到CSDN下载;

 

#ifndef log_src_h__
#define log_src_h__

#if 0


static char* UnicodeToAnsi(const wchar_t* szStr)
{
    int nLen = WideCharToMultiByte(CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL);

    if (nLen == 0)
    {
        return NULL;
    }

    char* pResult = new char[nLen + 1];

    pResult[nLen] = '\0';

    WideCharToMultiByte(CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL);

    return pResult;
}


static void Log_To_file(char const* fmt, ...)
{
    static FILE* fOut = fopen("D:/testLog.txt", "w");
    if (fOut == NULL)
        return;

    SYSTEMTIME st;
    GetLocalTime(&st);
    char szBuf[2048];
    sprintf(szBuf, "[%u-%02u-%02u %02u:%02u:%02u]  ",
        st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
    fwrite(szBuf, 1, strlen(szBuf), fOut);

    va_list args;
    va_start(args, fmt);
    vsnprintf(szBuf, sizeof(szBuf), fmt, args);
    va_end(args);

    fwrite(szBuf, 1, strlen(szBuf), fOut);
    fwrite("\r\n", 1, 2, fOut);
    fflush(fOut);
}


static void RetailOutput(TCHAR *szFormat, ...)
{
    TCHAR szBuffer[1024];  // Large buffer for long filenames or URLs
    const size_t NUMCHARS = sizeof(szBuffer) / sizeof(szBuffer[0]);
    const int LASTCHAR = NUMCHARS - 1;

    // Format the input string
    va_list pArgs;
    va_start(pArgs, szFormat);

    // Use a bounded buffer size to prevent buffer overruns.  Limit count to
    // character size minus one to allow for a NULL terminating character.
    _vsntprintf(szBuffer, NUMCHARS - 1, szFormat, pArgs);
    va_end(pArgs);

    // Ensure that the formatted string is NULL-terminated
    szBuffer[LASTCHAR] = TEXT('\0');

    // Display a message box with the formatted string
    OutputDebugString(szBuffer);

#ifdef UNICODE

    char * pstr_szFormat = UnicodeToAnsi(szFormat);

    Log_To_file(pstr_szFormat);

    delete[] pstr_szFormat;
    pstr_szFormat = NULL;

#else
    Log_To_file(pstr_szFormat);
#endif

}


#define JIF(x) {RetailOutput(TEXT(" ") TEXT(#x) TEXT("\n\0")); x; }

#define LOG_SRC(x) {RetailOutput(TEXT(" ") TEXT(#x) TEXT("\n\0")); x; }

#endif

//-------------封装一下:

class CLogSrc
{
    static const int sc_nFileNameLen = 260;
    static const int sc_nfwriteLen   = 1024;

private:
    char m_strLogFileName[sc_nFileNameLen];

    FILE * fOut;

private:
    void init(char * pStrLogFileName)
    {
        memset(m_strLogFileName, 0, sc_nFileNameLen);
        fOut = NULL;

        if (pStrLogFileName == NULL)
        {
        }

        strcpy(m_strLogFileName, pStrLogFileName);


        fOut = fopen(m_strLogFileName, "w+"); //程序启动后,重新写log文件;

        if (fOut == NULL)
        {
            return;
        }

    }

public:
    CLogSrc(char * pStrLogFileName)
    {
        init(pStrLogFileName);
    }

    ~CLogSrc()
    {
        if (fOut)
        {
            fclose(fOut);
            fOut = NULL;
        }
    }
public:

    char* UnicodeToAnsi(const wchar_t* szStr)
    {
        int nLen = WideCharToMultiByte(CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL);

        if (nLen == 0)
        {
            return NULL;
        }

        char* pResult = new char[nLen + 1];

        pResult[nLen] = '\0';

        WideCharToMultiByte(CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL);

        return pResult;
    }

    void Log_To_file(char const* fmt, ...)
    {
        if (fOut == NULL)
        {
            return;
        }
     
        SYSTEMTIME st;
        GetLocalTime(&st);
        char szBuf[sc_nfwriteLen] = { 0 };
        sprintf(szBuf, "[%u-%02u-%02u %02u:%02u:%02u]  ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);

        fwrite(szBuf, 1, strlen(szBuf), fOut);

        va_list args;
        va_start(args, fmt);
        vsnprintf(szBuf, sizeof(szBuf), fmt, args);
        va_end(args);

        fwrite(szBuf, 1, strlen(szBuf), fOut);
        fwrite("\r\n", 1, 2, fOut);
        fflush(fOut);
    }


    void RetailOutput(TCHAR *szFormat, ...)
    {
        TCHAR szBuffer[sc_nfwriteLen];  // Large buffer for long filenames or URLs
        const size_t NUMCHARS = sizeof(szBuffer) / sizeof(szBuffer[0]);
        const int LASTCHAR = NUMCHARS - 1;

        // Format the input string
        va_list pArgs;
        va_start(pArgs, szFormat);

        // Use a bounded buffer size to prevent buffer overruns.  Limit count to
        // character size minus one to allow for a NULL terminating character.
        _vsntprintf(szBuffer, NUMCHARS - 1, szFormat, pArgs);
        va_end(pArgs);

        // Ensure that the formatted string is NULL-terminated
        szBuffer[LASTCHAR] = TEXT('\0');

        // Display a message box with the formatted string
        OutputDebugString(szBuffer);

#ifdef UNICODE

        char * pstr_szFormat = UnicodeToAnsi(szFormat);

        Log_To_file(pstr_szFormat);

        delete[] pstr_szFormat;
        pstr_szFormat = NULL;

#else
        Log_To_file(pstr_szFormat);
#endif

    }

};


//#define LOG_SRC(x) {RetailOutput(TEXT(" ") TEXT(#x) TEXT("\n\0")); x; }

//当声明变量的时候,x语句在{}中,后面代码无法识别;
//#define LOG_SRC_TestLog(x) { static CLogSrc CLogSrc_test("D:\\LOG_SRC_TestLog.txt"); CLogSrc_test.RetailOutput(TEXT(" ") TEXT(#x) TEXT("\n\0")); x; }

//CLogSrc的对象声明,每次在{}中,所以每次都会删除之前的log文件,重新建立log文件,所以每次只有最后一句log;
//#define LOG_SRC_TestLog(x)  {static CLogSrc CLogSrc_test("D:\\LOG_SRC_TestLog.txt"); CLogSrc_test.RetailOutput(TEXT(" ") TEXT(#x) TEXT("\n\0"));} x; 


// static void LOG_SRC_TestLog_Function(TCHAR *szFormat)
// {
//     static CLogSrc CLogSrc_test("D:\\LOG_SRC_TestLog.txt"); 
// 
//     CLogSrc_test.RetailOutput(szFormat);
// }
// 
// #define LOG_SRC_TestLog(x)  {LOG_SRC_TestLog_Function(TEXT(" ") TEXT(#x) TEXT("\n\0"));} x; 

static CLogSrc * LOG_SRC_TestLog_Function()
{
    static CLogSrc CLogSrc_test("D:\\LOG_SRC_TestLog.txt"); 

    return &CLogSrc_test;
}

#define LOG_SRC_TestLog(x)  {LOG_SRC_TestLog_Function()->RetailOutput(TEXT(" ") TEXT(#x) TEXT("\n\0"));} x; 
#define LOG_SRC_TestLog_Info(x)  {LOG_SRC_TestLog_Function()->Log_To_file(x);} //直接输出调试信息;

//test:

#if 0
#include "log_src.h"

void CMFCApplication5Dlg::OnBnClickedButton22()
{
    // TODO: 在此添加控件通知处理程序代码

    LOG_SRC_TestLog(char * pstr = NULL);

    LOG_SRC_TestLog(pstr);

    LOG_SRC_TestLog(AfxMessageBox(L""));

    // JIF(strcpy(pstr, "123"));

    LOG_SRC_TestLog(if (1)
    {
        AfxMessageBox(L"1");
    });
    
    int n = 100;

    LOG_SRC_TestLog_Info("test info string");
    LOG_SRC_TestLog_Info("test info: n = %d", n);    
}

#endif


#endif // log_src_h__
 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chinabinlang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值