Add c++-style conditional logs
These could be used like this:
notify = !connection->monitor && stillHaveWindowHandle;
LOGI_IF(notify) << "consume closed input channel";
Previously, this was only possible to do with the c-style logs like
ALOGI_IF.
Bug: 270573445
Flag: EXEMPT refactor
Test: added some LOGI statements to InputDispatcher_test and checked
that the logs are printed on the console on host.
Change-Id: I80a2ee90ed680a2a2193f4c316aa5f94633982ba
diff --git a/include/android-base/logging.h b/include/android-base/logging.h
index 9b52391..42b2538 100644
--- a/include/android-base/logging.h
+++ b/include/android-base/logging.h
@@ -224,6 +224,25 @@
// LOG(FATAL) << "We didn't expect to reach here";
#define LOG(severity) LOGGING_PREAMBLE(severity) && LOG_STREAM(severity)
+// Conditionally logs a message based on a specified severity level and a boolean condition.
+// Logs to logcat on Android, or to stderr on host. See also LOG(severity) above.
+//
+// The message will only be logged if:
+// 1. The provided 'cond' evaluates to true.
+// 2. The 'severity' level is enabled for the current log tag (as determined by the logging
+// configuration).
+//
+// Usage:
+//
+// LOG_IF(INFO, some_condition) << "This message will be logged if 'some_condition' is true" <<
+// " and INFO level is enabled.";
+//
+// @param severity The severity level of the log message (e.g., VERBOSE, DEBUG, INFO, WARNING,
+// ERROR, FATAL).
+// @param cond The boolean condition that determines whether to log the message.
+#define LOG_IF(severity, cond) \
+ if (UNLIKELY(cond) && WOULD_LOG(severity)) LOG(severity)
+
// Checks if we want to log something, and sets up appropriate RAII objects if
// so.
// Note: DO NOT USE DIRECTLY. This is an implementation detail.