1 C++以可变参数格式化带颜色输出日志信息

使用Unity时,它的日志系统做的就比较好,不同类型的日志信息在底下面板以不同的颜色输出出来,简单明了,所以仿照这个做了一个简陋的,不过也够用了,代码如下:

#include <iostream>
#include <Windows.h>

template <typename... Args>
void LogError(const char* fmt, Args... args) {
    size_t strsize = snprintf(nullptr, 0, fmt, args...) + 1;

    char* outstr = (char*)malloc(strsize);
    snprintf(outstr, strsize, fmt, args...);

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED);
    std::cout << outstr << std::endl;

    free(outstr);
}

template <typename... Args>
void LogWarning(const char* fmt, Args... args) {
    size_t strsize = snprintf(nullptr, 0, fmt, args...) + 1;

    char* outstr = (char*)malloc(strsize);
    snprintf(outstr, strsize, fmt, args...);

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN);
    std::cout << outstr << std::endl;

    free(outstr);
}

template <typename... Args>
void Log(const char* fmt, Args... args) {
    size_t strsize = snprintf(nullptr, 0, fmt, args...) + 1;

    char* outstr = (char*)malloc(strsize);
    snprintf(outstr, strsize, fmt, args...);

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
    std::cout << outstr << std::endl;

    free(outstr);
}


int main(int argn, char **argv)
{
    LogError("%s", "LogError");
    LogWarning("%s", "LogWarning");
    Log("%s", "Log");

    getchar();
    return 0;
}

效果:
C++ - 控制台程序在控制台窗口可变参数格式化带颜色输出日志信息-StubbornHuang Blog