lg2: allow type output customizations
Allow lg2 output for custom types where the type has a `to_string`
function defined per ADL lookup rules.
Tested:
Modified phosphor-health-monitor to have a `to_string` for local
enumerations.
```
<7> TYPE=CPU, NAME=CPU SUBTYPE=CPU PATH=, FREQ=1, WSIZE=120
<7> TYPE=CPU, NAME=CPU_Kernel SUBTYPE=CPU_Kernel PATH=, FREQ=1, WSIZE=120
```
Signed-off-by: Patrick Williams <patrick@stwcx.xyz>
Change-Id: I6850b0bb142f0ef5219a5fc07c2cb4e2c90d5779
diff --git a/lib/include/phosphor-logging/lg2/conversion.hpp b/lib/include/phosphor-logging/lg2/conversion.hpp
index 92265e7..d43abfc 100644
--- a/lib/include/phosphor-logging/lg2/conversion.hpp
+++ b/lib/include/phosphor-logging/lg2/conversion.hpp
@@ -59,6 +59,9 @@
concept sdbusplus_object_path =
std::derived_from<std::decay_t<T>, sdbusplus::message::object_path>;
+template <typename T>
+concept has_to_string = requires(T&& t) { to_string(t); };
+
/** Concept listing all of the types we know how to convert into a format
* for logging.
*/
@@ -67,7 +70,7 @@
!(unsigned_integral_except_bool<T> || std::signed_integral<T> ||
std::same_as<bool, T> || std::floating_point<T> || string_like_type<T> ||
pointer_type<T> || sdbusplus_enum<T> || exception_type<T> ||
- sdbusplus_object_path<T>);
+ sdbusplus_object_path<T> || has_to_string<T>);
/** Any type we do not know how to convert for logging gives a nicer
* static_assert message. */
@@ -277,6 +280,25 @@
return std::make_tuple(h, (f | str).value, v.str);
}
+template <log_flags... Fs, has_to_string V>
+static auto log_convert(const char* h, log_flag<Fs...> f, V&& v)
+{
+ // Compile-time checks for valid formatting flags.
+ prohibit(f, bin);
+ prohibit(f, dec);
+ prohibit(f, field16);
+ prohibit(f, field32);
+ prohibit(f, field64);
+ prohibit(f, field8);
+ prohibit(f, floating);
+ prohibit(f, hex);
+ prohibit(f, signed_val);
+ prohibit(f, unsigned_val);
+
+ // Treat like a string, but call to_string.
+ return std::make_tuple(h, (f | str).value, to_string(std::forward<V>(v)));
+}
+
/** Class to facilitate walking through the arguments of the `lg2::log` function
* and ensuring correct parameter types and conversion operations.
*/