现代C++日志库

English
简体中文

设计目标

当前存在不少 C++ 的日志工具库,很多都功能丰富,配置也较为繁重,以共享库的方式提供。工具最主要的目标是: 满足条件,易于使用。 我们使用现代 C++ 编程能力,旨在实现一个尽可能满足条件的日志工具库。

支持的编译器

直到 2018 年,当前 C++ 已经发展到 C++17,新的版本尚末广泛普及。而 C++11 是发展过程中的一个重大变化的版本,支持了很多新的特性,到目前为止,已被普遍接受。我们目前在以下编译环境进行了验证:

整合

只需要让你的工程可以搜索到 include 目录下的头文件 tinylog.hpp 即可。这个库没有任何依赖,所有你需要做的就是添加以下代码到你需要输出日志的地方。

#include "tinylog.hpp"

// 引入命名空间 tinylog
using namespace tinylog;

另外,别忘记设置启用 C++11 的开关(比如:对于 GCC 设置 -std=c++11)。

示例

#include <locale>
#include <map>
#include <string>

#include "tinylog.hpp"

int main(int argc, char* argv[])
{
    using namespace tinylog;

    //--------------|
    // 设置         |
    //--------------|
    std::locale loc("");
    std::locale::global(loc);

    // 注册一个日志记录器
    auto inst = registry::create_logger();

    // 安装输出槽: @see std::make_shared<>
    inst->create_sink<sink::console_sink>();

    constexpr auto max_file_size = 5 * 1024 * 1024; // 5MB
    inst->create_sink<sink::u8_file_sink>("default.log", max_file_size);

    // 过滤日志级别
    inst->set_level(debug);

    // [可选] 输出日志边界
    dlout(inst, debug) << logger::title();

    //--------------|
    // 输出日志     |
    //--------------|
    // 普通文本
    lout(info) << "Weclome to TinyLog !!!" << std::endl;

    // STL容器
    std::map<std::string, size_t> const ages = { {"tl", 1}, {"json", 5} };
    lout(warn) << "ages: " << ages << std::endl;

    // 十六进制
    constexpr auto text = "Bravo! The job has been done well.";
    lout(error) << "hexdump: " << text << "\n" << hexdump(text);

    return 0;
}

上述例子存在 example_narrow 宽字符版本见 example_unicode

example_narrow

联系

如果你有关于这个库的问题或建议,请在 Github 上打开一个 Issue,便于大家分享观点,协同解决问题。