Add configurable log level for cerr output
When directly running an executable which utilizes lg2, all logs are
shown by default. Currently, we can only disable them entirely without
any filtering options.
This commit adds the LG2_LOG_LEVEL environment variable for log
filtering. It allows runtime control of log verbosity by setting
LG2_LOG_LEVEL to desired maximum log level (0-7). Messages above this
level are filtered out. Defaults to 7 (all levels) if not set.
Tested:
Logs are properly filtered when the env variable is set
Change-Id: Ibe44d9971550d3b74ef818a00f7d6b364eb0212c
Signed-off-by: Piotr Sulewski <piotrx.sulewski@intel.com>
diff --git a/docs/structured-logging.md b/docs/structured-logging.md
index 93db30c..cb208ef 100644
--- a/docs/structured-logging.md
+++ b/docs/structured-logging.md
@@ -128,6 +128,9 @@
- Missing a message yields:
- `error: use of deleted function ‘lg2::debug<>::debug()’`
+Debug-level messages are only sent to journald if the `DEBUG_INVOCATION`
+environment variable is set, as suggested by the `systemd.exec` manpage.
+
### LOG2_FMTMSG key
The API adds an extra journald key to represent the original message prior to
@@ -162,6 +165,11 @@
environment variable to any value. This is especially useful to see log output
in OpenBMC CI test verfication.
+The verbosity of this output can be filtered by setting `LG2_LOG_LEVEL`
+environment variable to the desired maximum log level (0-7). Messages with a
+priority value greater than this setting will be supressed. If `LG2_LOG_LEVEL`
+is not set, it defaults to 7, showing all messages.
+
The format of information sent to the TTY can be adjusted by setting the desired
format string in the `LG2_FORMAT` environment variable. Supported fields are:
diff --git a/lib/lg2_logger.cpp b/lib/lg2_logger.cpp
index 3d28daf..5a80b41 100644
--- a/lib/lg2_logger.cpp
+++ b/lib/lg2_logger.cpp
@@ -13,6 +13,7 @@
#include <mutex>
#include <source_location>
#include <sstream>
+#include <utility>
#include <vector>
namespace lg2::details
@@ -137,6 +138,30 @@
static void cerr_extra_output(level l, const std::source_location& s,
const std::string& m)
{
+ static const int maxLogLevel = []() {
+ const char* logLevel = getenv("LG2_LOG_LEVEL");
+ if (logLevel == nullptr)
+ {
+ // Default to logging all levels if not set
+ return std::to_underlying(level::debug);
+ }
+ try
+ {
+ int level = std::stoi(logLevel);
+ return std::clamp(level, std::to_underlying(level::emergency),
+ std::to_underlying(level::debug));
+ }
+ catch (const std::exception&)
+ {
+ return std::to_underlying(level::debug);
+ }
+ }();
+
+ if (std::to_underlying(l) > maxLogLevel)
+ {
+ return;
+ }
+
static const char* const defaultFormat = []() {
const char* f = getenv("LG2_FORMAT");
if (nullptr == f)