[[Feature Request] Proposal for new logging macros: `SPDLOG_LOGGER_CONDITIONAL`, `SPDLOG_LOGGER_EVERY_N`, and `SPDLOG_LOGGER_THROTTLE`
Body:
Hi @gabime and the spdlog team,
First of all, thank you for maintaining such a high-performance and easy-to-use logging library. I use spdlog extensively in my projects.
I am writing to propose adding three new macros to the library to handle common logging patterns (conditional logging, rate limiting by count, and rate limiting by time) more efficiently. Currently, achieving these behaviors often requires writing manual wrapper logic or helper classes in user code, which can be verbose and prone to thread-safety issues if not handled carefully.
I suggest adding the following macros to spdlog/common.h (or a dedicated header):
1. SPDLOG_LOGGER_CONDITIONAL
Description: Logs a message only if a specific boolean condition is met. This avoids unnecessary string formatting overhead when the condition is false.
Proposed Signature:
SPDLOG_LOGGER_CONDITIONAL(logger, condition, level, fmt, ...)
Parameters:
logger:std::shared_ptr<spdlog::logger>condition:boolexpressionlevel: Log level (e.g.,info,error)fmt, ...: Format string and arguments
Usage Example:
int error_count = 5;
// Only logs if error_count > 0
SPDLOG_LOGGER_CONDITIONAL(lg, error_count > 0, error, "Found {} errors", error_count);2. SPDLOG_LOGGER_EVERY_N
Description: Logs a message only once every N calls. This is extremely useful for tracking progress in tight loops without flooding the log file.
Proposed Signature:
SPDLOG_LOGGER_EVERY_N(logger, level, N, fmt, ...)
Parameters:
logger: Target loggerlevel: Log levelN:int, the interval count (log 1 out of every N times)fmt, ...: Format string and arguments
Usage Example:
for (int i = 0; i < 100; ++i) {
// Logs when i = 0, 10, 20, ...
SPDLOG_LOGGER_EVERY_N(lg, info, 10, "Progress: {}", i);
}3. SPDLOG_LOGGER_THROTTLE
Description: Logs a message at most once per specified time interval (in seconds). This prevents log flooding during high-frequency events.
Proposed Signature:
SPDLOG_LOGGER_THROTTLE(logger, level, interval_sec, fmt, ...)
Parameters:
logger: Target loggerlevel: Log levelinterval_sec:double, minimum interval in secondsfmt, ...: Format string and arguments
Usage Example:
for (int i = 0; i < 100; ++i) {
// Logs at most once per second
SPDLOG_LOGGER_THROTTLE(lg, warn, 1.0, "High frequency event: {}", i);
}Summary
Implementing these macros directly in spdlog would provide a standardized, thread-safe, and zero-overhead (when disabled) way to handle these common scenarios.
I would love to hear your thoughts on this proposal. If you are open to it, I can try to contribute a PR with the implementation.
Thanks for your time!
Source: gabime/spdlog