Support custom environment variables for load_env_levels (#3327)

SPDLOG_LEVEL is currently supported to control log levels via
load_env_levels.

This patch adds support for other environment variable names, such as
MYAPP_LEVEL, for load_env_levels.
This commit is contained in:
Ken Matsui 2025-01-23 16:00:23 -05:00 committed by GitHub
parent 7cbf2a6967
commit ae1de0dc8c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 17 additions and 2 deletions

View File

@ -387,6 +387,9 @@ void android_example()
int main (int argc, char *argv[])
{
spdlog::cfg::load_env_levels();
// or specify the env variable name:
// MYAPP_LEVEL=info,mylogger=trace && ./example
// spdlog::cfg::load_env_levels("MYAPP_LEVEL");
// or from the command line:
// ./example SPDLOG_LEVEL=info,mylogger=trace
// #include "spdlog/cfg/argv.h" // for loading levels from argv

View File

@ -148,6 +148,9 @@ void load_levels_example() {
// Set the log level to "info" and mylogger to "trace":
// SPDLOG_LEVEL=info,mylogger=trace && ./example
spdlog::cfg::load_env_levels();
// or specify the env variable name:
// MYAPP_LEVEL=info,mylogger=trace && ./example
// spdlog::cfg::load_env_levels("MYAPP_LEVEL");
// or from command line:
// ./example SPDLOG_LEVEL=info,mylogger=trace
// #include "spdlog/cfg/argv.h" // for loading levels from argv

View File

@ -25,8 +25,8 @@
namespace spdlog {
namespace cfg {
inline void load_env_levels() {
auto env_val = details::os::getenv("SPDLOG_LEVEL");
inline void load_env_levels(const char* var = "SPDLOG_LEVEL") {
auto env_val = details::os::getenv(var);
if (!env_val.empty()) {
helpers::load_levels(env_val);
}

View File

@ -19,6 +19,15 @@ TEST_CASE("env", "[cfg]") {
#endif
load_env_levels();
REQUIRE(l1->level() == spdlog::level::warn);
#ifdef CATCH_PLATFORM_WINDOWS
_putenv_s("MYAPP_LEVEL", "l1=trace");
#else
setenv("MYAPP_LEVEL", "l1=trace", 1);
#endif
load_env_levels("MYAPP_LEVEL");
REQUIRE(l1->level() == spdlog::level::trace);
spdlog::set_default_logger(spdlog::create<test_sink_st>("cfg-default"));
REQUIRE(spdlog::default_logger()->level() == spdlog::level::info);
}