Fix logging when absl::SourceLocation is an alias of std::source_location

Prior to this change logging absl::SourceLocation sometimes worked
when //absl/strings/internal/stringify_sink.h was in the transitive
includes, usually through str_cat.h.

This change adds native support to logging, to avoid dependency issues.

PiperOrigin-RevId: 922782911
Change-Id: I599390a062c6f8828985d6475a6dbd324d3e52c9
This commit is contained in:
Derek Mauro
2026-05-28 08:16:59 -07:00
committed by Copybara-Service
parent 917befffa2
commit e7a10c8ec2
4 changed files with 25 additions and 0 deletions

View File

@@ -502,6 +502,7 @@ cc_test(
"//absl/log/internal:test_matchers",
"//absl/strings",
"//absl/strings:str_format",
"//absl/types:source_location",
"@googletest//:gtest",
"@googletest//:gtest_main",
],

View File

@@ -1017,6 +1017,7 @@ absl_cc_test(
absl::log
absl::log_internal_test_matchers
absl::scoped_mock_log
absl::source_location
absl::str_format
absl::strings
GTest::gmock_main

View File

@@ -179,6 +179,13 @@ class LogMessage {
LogMessage& operator<<(wchar_t* absl_nullable v);
LogMessage& operator<<(wchar_t v);
// Overload for absl::SourceLocation or the std::source_location alias.
LogMessage& operator<<(const absl::SourceLocation& loc) {
OstreamView view(*data_);
view.stream() << loc.file_name() << ':' << loc.line();
return *this;
}
// Handle stream manipulators e.g. std::endl.
LogMessage& operator<<(std::ostream& (*absl_nonnull m)(std::ostream& os));
LogMessage& operator<<(std::ios_base& (*absl_nonnull m)(std::ios_base& os));

View File

@@ -41,6 +41,7 @@
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/source_location.h"
namespace {
using ::absl::log_internal::AsString;
@@ -291,6 +292,21 @@ TYPED_TEST(SignedIntLogFormatTest, BitfieldNegative) {
LOG(INFO) << value.bits;
}
TEST(SourceLocationTest, Format) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(test_sink, Send).Times(0);
absl::SourceLocation loc = absl::SourceLocation::current();
std::string expected = absl::StrCat(__FILE__, ":", __LINE__ - 1);
EXPECT_CALL(test_sink, Send(AllOf(TextMessage(Eq(expected)),
ENCODED_MESSAGE(HasValues(ElementsAre(
ValueWithStr(Eq(expected))))))));
test_sink.StartCapturingLogs();
LOG(INFO) << loc;
}
// Ignore these test cases on GCC due to "is too small to hold all values ..."
// warning.
#if !defined(__GNUC__) || defined(__clang__)