Base: Add default tag manipulation
Allow the default tag (the program name) to be overwritten.
Bug: 34867873
Test: m
Test: logging_test
Test: manual
Change-Id: I4ef32bad413a7cc82e46ce16a2f26212925964b1
diff --git a/base/logging_test.cpp b/base/logging_test.cpp
index 6f05d9b..5f689fa 100644
--- a/base/logging_test.cpp
+++ b/base/logging_test.cpp
@@ -206,8 +206,8 @@
}
#endif
-static void CheckMessage(const CapturedStderr& cap,
- android::base::LogSeverity severity, const char* expected) {
+static void CheckMessage(const CapturedStderr& cap, android::base::LogSeverity severity,
+ const char* expected, const char* expected_tag = nullptr) {
std::string output;
ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
android::base::ReadFdToString(cap.fd(), &output);
@@ -217,9 +217,18 @@
// many characters are in the log message.
ASSERT_GT(output.length(), strlen(expected));
ASSERT_NE(nullptr, strstr(output.c_str(), expected)) << output;
+ if (expected_tag != nullptr) {
+ ASSERT_NE(nullptr, strstr(output.c_str(), expected_tag)) << output;
+ }
#if !defined(_WIN32)
- std::regex message_regex(make_log_pattern(severity, expected));
+ std::string regex_str;
+ if (expected_tag != nullptr) {
+ regex_str.append(expected_tag);
+ regex_str.append(" ");
+ }
+ regex_str.append(make_log_pattern(severity, expected));
+ std::regex message_regex(regex_str);
ASSERT_TRUE(std::regex_search(output, message_regex)) << output;
#endif
}
@@ -600,3 +609,17 @@
__attribute__((constructor)) void TestLoggingInConstructor() {
LOG(ERROR) << "foobar";
}
+
+TEST(logging, SetDefaultTag) {
+ constexpr const char* expected_tag = "test_tag";
+ constexpr const char* expected_msg = "foobar";
+ CapturedStderr cap;
+ {
+ std::string old_default_tag = android::base::GetDefaultTag();
+ android::base::SetDefaultTag(expected_tag);
+ android::base::ScopedLogSeverity sls(android::base::LogSeverity::INFO);
+ LOG(INFO) << expected_msg;
+ android::base::SetDefaultTag(old_default_tag);
+ }
+ CheckMessage(cap, android::base::LogSeverity::INFO, expected_msg, expected_tag);
+}