How to use std::source_location from C 20 for better logging?
Use std::source_location::current() as the default parameter to automatically capture the file name, line number and function name of the call point; 2. You can simplify log calls through macros such as #define LOG(msg) log(msg, std::source_location::current()); 3. You can expand the log content with log level, timestamp and other information; 4. To optimize performance, function names can be omitted or location information can be disabled in the release version; 5. Details such as column() are rarely used, but are available. Using std::source_location can significantly increase the debugging value of logs with extremely low overhead, eliminating the need to manually pass FILE or __LINE__, allowing the compiler to automatically complete context capture, enabling more efficient and clear diagnostic output.
std::source_location
in C 20 is a lightweight utility that captures information about the source code's context—like file name, line number, function name, and column—at the point where it's used. It's incredibly useful for improving logging by automatically including diagnostic context without requiring manual input.

Here's how to use std::source_location
effectively for better logging.
1. Include and Capture Source Location Automatically
std::source_location
is defined in the <source_location></source_location>
header (C 20). It's a constexpr
-friendly class that captures location info at the call site when used with default arguments.

#include <iostream> #include <string_view> #include <source_location> void log(std::string_view message, std::source_location location = std::source_location::current()) { std::cout << location.file_name() << ":" << location.line() << " " << location.function_name() << "() - " << message << '\n'; }
Now when you call log("Something happened");
, the file, line, and function are captured automatically.
Example usage:

void my_function() { log("Debug message"); // Automatically prints file, line, function }
Output might look like:
main.cpp:15 my_function() - Debug message
2. Use in Macros for Cleaner Logging
To avoid passing source_location
manually every time, wrap the logging in a macro—though with C 20, you often don't need macros thanks to default parameter capture.
But if you want a clean interface (eg, LOG("msg")
), a macro helps:
#define LOG(msg) log(msg, std::source_location::current()) // Usage LOG("Error occurred");
This ensures the location is captured at the macro call site, not inside the log
function.
Note: Since
std::source_location::current()
is a built-in compiler intrinsic, the macro isn't strictly necessary, but it makes the syntax cleaner and more familiar.
3. Customize Log Format and Add Extra Context
You can extend the logger to include timestamps, log levels, or custom tags.
enum class LogLevel { Debug, Info, Warning, Error }; void log(LogLevel level, std::string_view message, std::source_location loc = std::source_location::current()) { const char* level_str[] = {"DEBUG", "INFO", "WARNING", "ERROR"}; std::cout << "[" << level_str[static_cast<int>(level)] << "] " << loc.file_name() << ":" << loc.line() << " " << loc.function_name() << " - " << message << '\n'; }
Usage:
log(LogLevel::Warning, "Value out of range");
Output:
[WARNING] config.cpp:42 parse_config() - Value out of range
4. Optimize for Performance
std::source_location
is lightweight, but capturing function names (which may include full signatures and templates) can be expensive in terms of binary size or performance.
If you don't need the function name, skip it:
std::cout << loc.file_name() << ":" << loc.line();
Or, use conditional compilation to disable location info in release builds:
#ifdef DEBUG auto loc = std::source_location::current(); std::cout << loc.file_name() << ":" << loc.line() << " "; #else std::cout << "[debug info disabled] "; #endif
Alternatively, design your logging system so that debug-level logs (with full location) are compiled out when not needed.
5. Capture Column and Other Details (Rarely Used)
std::source_location
also provides column()
and file_name()
/ function_name()
as const char*
. Column is rarely useful but available.
std::cout << "Column: " << loc.column() << '\n'; // Usually 1 or not very meaningful
Most compilers set column to the start of the statement, so it's not commonly used.
Summary
- Use
std::source_location::current()
as a default function parameter to auto-capture location. - Avoid macros if you're OK with plain function calls; otherwise, use them for cleaner syntax.
- Include file, line, and function in logs to speed up debugging.
- Be mindful of performance and binary bloat from long function names.
- Combine with log levels and formatting for production-ready logging.
Using std::source_location
makes logging more informative with almost zero effort—no more manually writing __FILE__
or __LINE__
. It's a small feature with a big impact on debuggability.
Basically, just add it to your logging function and let the compiler do the rest.
The above is the detailed content of How to use std::source_location from C 20 for better logging?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are many initialization methods in C, which are suitable for different scenarios. 1. Basic variable initialization includes assignment initialization (inta=5;), construction initialization (inta(5);) and list initialization (inta{5};), where list initialization is more stringent and recommended; 2. Class member initialization can be assigned through constructor body or member initialization list (MyClass(intval):x(val){}), which is more efficient and suitable for const and reference members. C 11 also supports direct initialization within the class; 3. Array and container initialization can be used in traditional mode or C 11's std::array and std::vector, support list initialization and improve security; 4. Default initialization

Object slice refers to the phenomenon that only part of the base class data is copied when assigning or passing a derived class object to a base class object, resulting in the loss of new members of the derived class. 1. Object slices occur in containers that directly assign values, pass parameters by value, or store polymorphic objects in storage base classes; 2. The consequences include data loss, abnormal behavior and difficult to debug; 3. Avoiding methods include passing polymorphic objects using pointers or references, or using smart pointers to manage the object life cycle.

To determine whether std::optional has a value, you can use the has_value() method or directly judge in the if statement; when returning a result that may be empty, it is recommended to use std::optional to avoid null pointers and exceptions; it should not be abused, and Boolean return values or independent bool variables are more suitable in some scenarios; the initialization methods are diverse, but you need to pay attention to using reset() to clear the value, and pay attention to the life cycle and construction behavior.

RAII is an important technology used in resource management in C. Its core lies in automatically managing resources through the object life cycle. Its core idea is: resources are acquired at construction time and released at destruction, thereby avoiding leakage problems caused by manual release. For example, when there is no RAII, the file operation requires manually calling fclose. If there is an error in the middle or return in advance, you may forget to close the file; and after using RAII, such as the FileHandle class encapsulates the file operation, the destructor will be automatically called after leaving the scope to release the resource. 1.RAII is used in lock management (such as std::lock_guard), 2. Memory management (such as std::unique_ptr), 3. Database and network connection management, etc.

There are four common methods to obtain the first element of std::vector: 1. Use the front() method to ensure that the vector is not empty, has clear semantics and is recommended for daily use; 2. Use the subscript [0], and it also needs to be judged empty, with the performance comparable to front() but slightly weaker semantics; 3. Use *begin(), which is suitable for generic programming and STL algorithms; 4. Use at(0), without manually null judgment, but low performance, and throw exceptions when crossing the boundary, which is suitable for debugging or exception handling; the best practice is to call empty() first to check whether it is empty, and then use the front() method to obtain the first element to avoid undefined behavior.

The C standard library helps developers improve code quality by providing efficient tools. 1. STL containers should be selected according to the scene, such as vector suitable for continuous storage, list suitable for frequent insertion and deletion, and unordered_map is suitable for fast search; 2. Standard library algorithms such as sort, find, and transform can improve efficiency and reduce errors; 3. Intelligent pointers unique_ptr and shared_ptr effectively manage memory to avoid leakage; 4. Other tools such as optional, variant, and function enhance code security and expressiveness. Mastering these core functions can significantly optimize development efficiency and code quality.

The destructor in C is a special member function that is automatically called when an object is out of scope or is explicitly deleted. Its main purpose is to clean up resources that an object may acquire during its life cycle, such as memory, file handles, or network connections. The destructor is automatically called in the following cases: when a local variable leaves scope, when a delete is called on the pointer, and when an external object containing the object is destructed. When defining the destructor, you need to add ~ before the class name, and there are no parameters and return values. If undefined, the compiler generates a default destructor, but does not handle dynamic memory releases. Notes include: Each class can only have one destructor and does not support overloading; it is recommended to set the destructor of the inherited class to virtual; the destructor of the derived class will be executed first and then automatically called.

Bit operation can efficiently implement the underlying operation of integers, 1. Check whether the i-th bit is 1: Use n&(1
