Logging in C++20 Without a Macro

Words: 174

Normally, to capture information about the call site when printing a log, the traditional approach is to define a macro that collects that information.

But with C++20’s std::source_location we can write a logging function that needs no macro at all.

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;
}

Compile and run:

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

Expected output:

bash
1
[main.cc:30] test 123
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...