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.
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:
1
| g++ main.cc -Wall -o main && ./main
|
Expected output: