C++日志库_spdlog

来源:互联网 发布:图形旋转矩阵 编辑:程序博客网 时间:2024/06/05 04:37

日志库?

我需要这个干什么?

除了可以记录产品的错误信息, 以供反馈debug之用; 还不失为一种更方便的文件IO库. 而且像spdlog, 可以同时向文件及Windows Debugger输出信息.

Windows Debugger 是指 Visual Studio 的 Output 窗口, 或者可以用工具 Dbgview 查看; 输出信息时使用的是OutputDebugString Windows API.


spdlog可以限定文件的个数与大小的上限, 避免了挤爆硬盘的情况. MIT license. 


为了实现上面所说的功能, 下面是对它的封装:

template<const char file_name[]>class CLog{    CLog() = delete;    static std::shared_ptr<spdlog::logger> combined_logger;public:    static void init_log()    {        if (combined_logger) combined_logger = nullptr;        try        {            std::vector<spdlog::sink_ptr> sinks;            sinks.push_back(std::make_shared<spdlog::sinks::msvc_sink_mt>());            sinks.push_back(std::make_shared<spdlog::sinks::rotating_file_sink_mt>(file_name, 1024 * 1024 * 4, 1));            combined_logger = std::make_shared<spdlog::logger>(file_name, begin(sinks), end(sinks));            combined_logger->set_pattern("[%Y-%m-%d %H:%M:%S] %v");            combined_logger->set_level(spdlog::level::trace);            combined_logger->info("======== init_log ========");        }        catch (...)        {            combined_logger = nullptr;        }    }    template <typename... Args>    static inline void log(const char* fmt, const Args&... args)    {        if (combined_logger) combined_logger->info(fmt, args...);    }    static void flush()    {        if (combined_logger) combined_logger->flush();    }    static void cease_log()    {        flush();        combined_logger = nullptr;    }};template<const char file_name[]>std::shared_ptr<spdlog::logger> CLog<file_name>::combined_logger = nullptr;

用法:

char your_log_file_name[] = "Example.log";typedef CLog<your_log_file_name> tlog;