C++20中无宏定义日志的一种实现

文章字数:234

通常来说,在打印日志时为了获取调用处的相关信息,传统做法都需要定义一个宏来收集相关信息。

但是借由C++20的std::source_location,我们可以实现一个无宏定义的日志打印函数。

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <format>
#include <source_location>
#include <string_view>

namespace Logger {

struct FormatWithLocation {
    std::string_view value;
    std::source_location loc;

    template <typename String>
    FormatWithLocation(const String& s, const std::source_location& l = std::source_location::current())
        : value{s}, loc{l}
    {}
};

template <typename... Args>
void Debug(FormatWithLocation fmt, Args &&...args)
{
    std::string formattedMessage = std::vformat(fmt.value, std::make_format_args(std::forward<Args>(args)...));
    std::cout << "[" << fmt.loc.file_name() << ":" << fmt.loc.line() << "] " << formattedMessage << std::endl;
}

} // namespace Logger

int main()
{
    int num = 123;
    Logger::Debug("test {}", num);
    return 0;
}

编译运行:

bash
1
g++ main.cc -Wall -o main && ./main

预期输出:

bash
1
[main.cc:30] test 123
本文采用 CC BY-NC-SA 4.0协议,如果对您有帮助或存在意见建议,欢迎在下方评论交流。
本页面浏览次数 加载中...
本页面访客数 加载中...

加载中...