Printf宏定义日志

xingyun86 2023-4-9 470

Printf宏定义日志

#if (defined(DEBUG) || defined(_DEBUG))
#define DEBUG_PRINT(format,...) printf("File: " __FILE__ ", Line: %05d: " format "/n", __LINE__, ##__VA_ARGS__)  
#else
#define DEBUG_PRINT(format,...)
#endif
void LogDbg(const char* fmt, ...)
{
    static FILE* gfp = NULL;
    va_list va = nullptr;
    va_start(va, fmt);
    if (gfp == NULL)gfp = fopen("run.log", "w");
    if (gfp != NULL)::vfprintf(gfp, fmt, va), ::fflush(gfp);
    va_end(va);
}

打印日志

class ConsoleManager
{
    FILE* pStdIn = NULL;
    FILE* pStdOut = NULL;
    FILE* pStdErr = NULL;
public:
    static ConsoleManager* CM()
    {
        static ConsoleManager ConsoleManagerInstance = {};
        return &ConsoleManagerInstance;
    }
public:
    void FormatPrintf(const char* format, ...)
    {
        va_list va = nullptr;
        va_start(va, format);
        if (pStdOut != NULL)
        {
            ::vfprintf(pStdOut, format, va);
            ::fflush(pStdOut);
        }
        else
        {
            ::vfprintf(stdout, format, va);
        }
        va_end(va);
    }
    void FormatPrintfW(const wchar_t* format, ...)
    {
        va_list va = nullptr;
        va_start(va, format); 
        if (pStdOut != NULL)
        {
            ::vfwprintf(pStdOut, format, va);
            ::fflush(pStdOut);
        }
        else
        {
            ::vfwprintf(stdout, format, va);
        }
        va_end(va);
    }
    void StartConsole()
    {
        ::setlocale(LC_ALL, ("chs"));
        if (::AllocConsole() == TRUE)
        {
            ::freopen_s(&pStdIn, ("CONIN$"), ("r"), stdin);
            ::freopen_s(&pStdOut, ("CONOUT$"), ("w"), stdout);
            ::freopen_s(&pStdErr, ("CONOUT$"), ("w"), stderr);
        }
    }
    void CloseConsole()
    {
        if (pStdIn != NULL)
        {
            ::fclose(pStdIn);
            pStdIn = NULL;
        }
        if (pStdOut != NULL)
        {
            ::fclose(pStdOut);
            pStdOut = NULL;
        }
        if (pStdErr != NULL)
        {
            ::fclose(pStdErr);
            pStdErr = NULL;
        }
        ::FreeConsole();
    }
public:
    ConsoleManager()
    {
#if defined(_DEBUG) || defined(DEBUG)
        StartConsole();
#endif
    }
    virtual ~ConsoleManager()
    {
#if defined(_DEBUG) || defined(DEBUG)
        CloseConsole();
#endif
    }
};


×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回