lg2: reduce stdout and allow customization
It was reported by users that the information logged to the TTY was too
much in many cases, which limited the usability of lg2. Allow users to
customize the output by setting the "LG2_FORMAT" environment variable
and limit the default output to just "<level> message".
Tested:
Added a simple log to the beginning of an existing daemon and tested
format strings:
```
$ ./health-monitor
<6> Here I am!
$ LG2_FORMAT="{%l} %m %% [%f:%L:%F]|%" ./health-monitor
{6} Here I am! % [int main():511:../healthMonitor.cpp]|%
```
Resolves openbmc/phosphor-logging#26.
Signed-off-by: Patrick Williams <patrick@stwcx.xyz>
Change-Id: Ie50c90f073539812c0693d05fc04ce7ad2b3fbcd
diff --git a/docs/structured-logging.md b/docs/structured-logging.md
index 6801279..b7a4178 100644
--- a/docs/structured-logging.md
+++ b/docs/structured-logging.md
@@ -154,8 +154,20 @@
When running an application or daemon on a console or SSH session, it might
not be obvious that the application is writing to the journal. The `lg2` APIs
-detect if the application is running on a TTY and additionally mirror the
-information sent to the journal to the TTY.
+detect if the application is running on a TTY and additionally log to the TTY.
+
+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:
+
+- `%%` : a `'%'` literal
+- `%f` : the logging function's name
+- `%F` : the logging function's file
+- `%l` : the log level as an integer
+- `%L` : the logging function's line number
+- `%m` : the lg2 message
+
+The default format is `"<%l> %m"`.
### Why a new API?
diff --git a/lib/lg2_logger.cpp b/lib/lg2_logger.cpp
index c8a0d7f..bd1e89d 100644
--- a/lib/lg2_logger.cpp
+++ b/lib/lg2_logger.cpp
@@ -134,8 +134,64 @@
static void cerr_extra_output(level l, const lg2::source_location& s,
const std::string& m)
{
- std::cerr << s.file_name() << ":" << s.line() << ":" << s.function_name()
- << "|<" << static_cast<uint64_t>(l) << "> " << m << std::endl;
+ static const char* format = []() {
+ const char* f = getenv("LG2_FORMAT");
+ if (nullptr == f)
+ {
+ f = "<%l> %m";
+ }
+ return f;
+ }();
+
+ while (*format)
+ {
+ if (*format != '%')
+ {
+ std::cerr << *format;
+ ++format;
+ continue;
+ }
+
+ ++format;
+ switch (*format)
+ {
+ case '%':
+ case '\0':
+ std::cerr << '%';
+ break;
+
+ case 'f':
+ std::cerr << s.function_name();
+ break;
+
+ case 'F':
+ std::cerr << s.file_name();
+ break;
+
+ case 'l':
+ std::cerr << static_cast<uint64_t>(l);
+ break;
+
+ case 'L':
+ std::cerr << s.line();
+ break;
+
+ case 'm':
+ std::cerr << m;
+ break;
+
+ default:
+ std::cerr << '%' << *format;
+ break;
+ }
+
+ if (*format != '\0')
+ {
+ ++format;
+ }
+ }
+
+ std::cerr << std::endl;
}
// Use the cerr output method if we are on a TTY.