0

Use string_view in logging and trace_event location

Changes the LogMessage class to use a string_view for file names. This
required a matching change in trace_event: a const char* string was
passed from logging code, but there is no safe way to get a const
char* from a string_view since the latter may not be null-terminated.

Many clients of base/logging.h are updated to use string_view as well.

Code which attempts to pass a string_view to a LogMessage by its data
pointer already exists:
https://source.chromium.org/chromium/chromium/src/+/main:ash/quick_pair/common/logging.cc;l=49;drc=c6c99d03b1d2f4fab91d6be8665f81b540690c73
https://source.chromium.org/chromium/chromium/src/+/main:components/cross_device/logging/logging.cc;l=30;drc=00704dbac4f63b2476aac319572ffc42c9b71fc2

Desire for Rust logging support prompted this change. In principle a
Rust log facility can be a thin wrapper around the base logging
implementation, but Rust has almost no support for null-terminated
strings. Instead, Rust provides a string_view equivalent built in to
the language. This change enables Rust code to pass file names
obtained by language-specific macros to the C++ implementation.

Bug: None
Change-Id: I21b4f1c945b70d54f66d80adf3dcda1fe5a39f71
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5765705
Reviewed-by: Peter Boström <pbos@chromium.org>
Auto-Submit: Collin Baker <collinbaker@chromium.org>
Commit-Queue: Collin Baker <collinbaker@chromium.org>
Reviewed-by: Stephen Nusko <nuskos@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Owners-Override: Daniel Cheng <dcheng@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1436283}
This commit is contained in:
Collin Baker
2025-03-21 14:15:44 -07:00
committed by Chromium LUCI CQ
parent e926e958bb
commit 5439f8eb1e
53 changed files with 246 additions and 203 deletions
ash
base
chrome
chromeos/ash/components
components
cross_device
openscreen_platform
peripherals
policy
viz
content/public/test
net
remoting/host/native_messaging
sandbox/linux/tests
third_party
crashpad
webrtc_overrides
rtc_base
tools/accessibility/inspect

@@ -34,19 +34,20 @@ ScopedLogMessage::~ScopedLogMessage() {
return; return;
const std::string string_from_stream = stream_.str(); const std::string string_from_stream = stream_.str();
LogBuffer::GetInstance()->AddLogMessage(LogBuffer::LogMessage( LogBuffer::GetInstance()->AddLogMessage(
string_from_stream, base::Time::Now(), file_.data(), line_, severity_)); LogBuffer::LogMessage(string_from_stream, base::Time::Now(),
std::string(file_), line_, severity_));
// Don't emit VERBOSE-level logging to the standard logging system unless // Don't emit VERBOSE-level logging to the standard logging system unless
// verbose logging is enabled for the source file. // verbose logging is enabled for the source file.
if (severity_ <= logging::LOGGING_VERBOSE && if (severity_ <= logging::LOGGING_VERBOSE &&
logging::GetVlogLevelHelper(file_.data(), file_.size()) <= 0) { logging::GetVlogLevelHelper(file_) <= 0) {
return; return;
} }
// The destructor of |log_message| also creates a log for the standard logging // The destructor of |log_message| also creates a log for the standard logging
// system. // system.
logging::LogMessage log_message(file_.data(), line_, severity_); logging::LogMessage log_message(file_, line_, severity_);
log_message.stream() << string_from_stream; log_message.stream() << string_from_stream;
} }

@@ -23,10 +23,10 @@ namespace quick_pair {
// Examples: // Examples:
// QP_LOG(INFO) << "Waiting for " << x << " pending requests."; // QP_LOG(INFO) << "Waiting for " << x << " pending requests.";
// QP_LOG(ERROR) << "Request failed: " << error_string; // QP_LOG(ERROR) << "Request failed: " << error_string;
#define QP_LOG(severity) \ #define QP_LOG(severity) \
ash::quick_pair::ScopedLogMessage( \ ash::quick_pair::ScopedLogMessage( \
std::string_view(__FILE__, std::size(__FILE__)), __LINE__, \ std::string_view(__FILE__, std::size(__FILE__) - 1), __LINE__, \
logging::LOGGING_##severity) \ logging::LOGGING_##severity) \
.stream() .stream()
// Disables all logging while in scope. Intended to be called only from test // Disables all logging while in scope. Intended to be called only from test

@@ -27,7 +27,7 @@ const char kLog4[] = "Unremarkable maple";
base::LazyInstance<std::vector<std::string>>::DestructorAtExit g_standard_logs = base::LazyInstance<std::vector<std::string>>::DestructorAtExit g_standard_logs =
LAZY_INSTANCE_INITIALIZER; LAZY_INSTANCE_INITIALIZER;
bool HandleStandardLogMessage(int severity, bool HandleStandardLogMessage(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -6,6 +6,8 @@
#include <stddef.h> #include <stddef.h>
#include <string_view>
#include "ash/constants/ash_features.h" #include "ash/constants/ash_features.h"
#include "base/no_destructor.h" #include "base/no_destructor.h"
#include "base/test/scoped_feature_list.h" #include "base/test/scoped_feature_list.h"
@@ -26,7 +28,7 @@ std::vector<std::string>& GetStandardLogs() {
} }
bool HandleStandardLogMessage(int severity, bool HandleStandardLogMessage(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -112,45 +112,43 @@ MATCHER_P2(LogErrorMatches, line, expected_msg, "") {
} \ } \
} while (0) } while (0)
#define EXPECT_LOG_ERROR_WITH_FILENAME(expected_file, expected_line, expr, \ #define EXPECT_LOG_ERROR_WITH_FILENAME(expected_file, expected_line, expr, \
msg) \ msg) \
do { \ do { \
static bool got_log_message = false; \ static bool got_log_message = false; \
ASSERT_EQ(logging::GetLogMessageHandler(), nullptr); \ ASSERT_EQ(logging::GetLogMessageHandler(), nullptr); \
logging::SetLogMessageHandler([](int severity, const char* file, int line, \ logging::SetLogMessageHandler([](int severity, std::string_view file, \
size_t message_start, \ int line, size_t message_start, \
const std::string& str) { \ const std::string& str) { \
EXPECT_FALSE(got_log_message); \ EXPECT_FALSE(got_log_message); \
got_log_message = true; \ got_log_message = true; \
EXPECT_EQ(severity, logging::LOGGING_ERROR); \ EXPECT_EQ(severity, logging::LOGGING_ERROR); \
EXPECT_EQ(str.substr(message_start), (msg)); \ EXPECT_EQ(str.substr(message_start), (msg)); \
if (std::string_view(expected_file) != "") { \ EXPECT_EQ(std::string_view(expected_file), file); \
EXPECT_STREQ(expected_file, file); \ if (expected_line != -1) { \
} \ EXPECT_EQ(expected_line, line); \
if (expected_line != -1) { \ } \
EXPECT_EQ(expected_line, line); \ return true; \
} \ }); \
return true; \ expr; \
}); \ EXPECT_TRUE(got_log_message); \
expr; \ logging::SetLogMessageHandler(nullptr); \
EXPECT_TRUE(got_log_message); \
logging::SetLogMessageHandler(nullptr); \
} while (0) } while (0)
#define EXPECT_LOG_ERROR(expected_line, expr, msg) \ #define EXPECT_LOG_ERROR(expected_line, expr, msg) \
EXPECT_LOG_ERROR_WITH_FILENAME(__FILE__, expected_line, expr, msg) EXPECT_LOG_ERROR_WITH_FILENAME(__FILE__, expected_line, expr, msg)
#define EXPECT_NO_LOG(expr) \ #define EXPECT_NO_LOG(expr) \
do { \ do { \
ASSERT_EQ(logging::GetLogMessageHandler(), nullptr); \ ASSERT_EQ(logging::GetLogMessageHandler(), nullptr); \
logging::SetLogMessageHandler([](int severity, const char* file, int line, \ logging::SetLogMessageHandler([](int severity, std::string_view file, \
size_t message_start, \ int line, size_t message_start, \
const std::string& str) { \ const std::string& str) { \
EXPECT_TRUE(false) << "Unexpected log: " << str; \ EXPECT_TRUE(false) << "Unexpected log: " << str; \
return true; \ return true; \
}); \ }); \
expr; \ expr; \
logging::SetLogMessageHandler(nullptr); \ logging::SetLogMessageHandler(nullptr); \
} while (0) } while (0)
#if defined(OFFICIAL_BUILD) #if defined(OFFICIAL_BUILD)

@@ -463,33 +463,41 @@ void SetLogFatalCrashKey(LogMessage* log_message) {
#endif // !BUILDFLAG(IS_NACL) #endif // !BUILDFLAG(IS_NACL)
} }
std::string BuildCrashString(const char* file, std::string BuildCrashString(std::string_view file,
int line, int line,
const char* message_without_prefix) { std::string_view message_without_prefix) {
// Only log last path component. // Only log last path component.
if (file) { char separator =
const char* slash = UNSAFE_TODO(strrchr(file,
#if BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_WIN)
'\\' '\\';
#else #else
'/' '/';
#endif // BUILDFLAG(IS_WIN) #endif // BUILDFLAG(IS_WIN)
));
if (slash) { auto pos = file.rfind(separator);
file = UNSAFE_TODO(slash + 1); if (pos == std::string_view::npos) {
} pos = 0;
} else {
pos += 1;
} }
return base::StringPrintf("%s:%d: %s", file, line, message_without_prefix); file = file.substr(pos);
return base::StringPrintf("%.*s:%d: %.*s", static_cast<int>(file.length()),
file.data(), line,
static_cast<int>(message_without_prefix.length()),
message_without_prefix.data());
} }
// Invokes macro to record trace event when a log message is emitted. // Invokes macro to record trace event when a log message is emitted.
void TraceLogMessage(const char* file, int line, const std::string& message) { void TraceLogMessage(std::string_view file,
int line,
const std::string& message) {
TRACE_EVENT_INSTANT("log", "LogMessage", [&](perfetto::EventContext ctx) { TRACE_EVENT_INSTANT("log", "LogMessage", [&](perfetto::EventContext ctx) {
perfetto::protos::pbzero::LogMessage* log = ctx.event()->set_log_message(); perfetto::protos::pbzero::LogMessage* log = ctx.event()->set_log_message();
log->set_source_location_iid(base::trace_event::InternedSourceLocation::Get( log->set_source_location_iid(base::trace_event::InternedSourceLocation::Get(
&ctx, base::trace_event::TraceSourceLocation(/*function_name=*/nullptr, &ctx, base::trace_event::TraceSourceLocation(
file, line))); /*function_name=*/std::string_view(), file, line)));
log->set_body_iid( log->set_body_iid(
base::trace_event::InternedLogMessage::Get(&ctx, message)); base::trace_event::InternedLogMessage::Get(&ctx, message));
}); });
@@ -613,14 +621,11 @@ int GetVlogVerbosity() {
return std::max(-1, LOGGING_INFO - GetMinLogLevel()); return std::max(-1, LOGGING_INFO - GetMinLogLevel());
} }
int GetVlogLevelHelper(const char* file, size_t N) { int GetVlogLevelHelper(std::string_view file) {
DCHECK_GT(N, 0U);
// Note: |g_vlog_info| may change on a different thread during startup // Note: |g_vlog_info| may change on a different thread during startup
// (but will always be valid or nullptr). // (but will always be valid or nullptr).
VlogInfo* vlog_info = GetVlogInfo(); VlogInfo* vlog_info = GetVlogInfo();
return vlog_info ? vlog_info->GetVlogLevel(std::string_view(file, N - 1)) return vlog_info ? vlog_info->GetVlogLevel(file) : GetVlogVerbosity();
: GetVlogVerbosity();
} }
void SetLogItems(bool enable_process_id, void SetLogItems(bool enable_process_id,
@@ -653,7 +658,7 @@ namespace {
// This simulates a NOTREACHED() at file:line instead of here. This is used // This simulates a NOTREACHED() at file:line instead of here. This is used
// instead of base::ImmediateCrash() to give better error messages locally // instead of base::ImmediateCrash() to give better error messages locally
// (printed stack for one). // (printed stack for one).
LogMessageFatal(file, line, LOGGING_FATAL).stream() LogMessageFatal(std::string_view(file), line, LOGGING_FATAL).stream()
<< "NOTREACHED hit. " << prefix_end; << "NOTREACHED hit. " << prefix_end;
} }
@@ -712,11 +717,14 @@ void DisplayDebugMessageInDialog(const std::string& str) {
} }
#endif // !defined(NDEBUG) #endif // !defined(NDEBUG)
LogMessage::LogMessage(const char* file, int line, LogSeverity severity) LogMessage::LogMessage(std::string_view file, int line, LogSeverity severity)
: severity_(severity), file_(file), line_(line) { : severity_(severity), file_(file), line_(line) {
Init(file, line); Init(file, line);
} }
LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
: LogMessage(std::string_view(file), line, severity) {}
LogMessage::~LogMessage() { LogMessage::~LogMessage() {
Flush(); Flush();
} }
@@ -951,12 +959,12 @@ void LogMessage::Flush() {
} }
std::string LogMessage::BuildCrashString() const { std::string LogMessage::BuildCrashString() const {
return logging::BuildCrashString(file(), line(), return logging::BuildCrashString(
UNSAFE_TODO(str().c_str() + message_start_)); file(), line(), std::string_view(str()).substr(message_start_));
} }
// writes the common header info to the stream // writes the common header info to the stream
void LogMessage::Init(const char* file, int line) { void LogMessage::Init(std::string_view file, int line) {
// Don't let actions from this method affect the system error after returning. // Don't let actions from this method affect the system error after returning.
base::ScopedClearLastError scoped_clear_last_error; base::ScopedClearLastError scoped_clear_last_error;
@@ -971,15 +979,14 @@ void LogMessage::Init(const char* file, int line) {
// TODO(pbos): Consider migrating LogMessage and the LOG() macros to use // TODO(pbos): Consider migrating LogMessage and the LOG() macros to use
// base::Location directly. See base/check.h for inspiration. // base::Location directly. See base/check.h for inspiration.
const std::string_view filename = const std::string_view filename =
file[0] == '.' ? std::string_view(file).substr( file[0] == '.' ? file.substr(std::min(std::size_t{6}, file.length()))
std::min(std::size_t{6}, strlen(file)))
: file; : file;
#if BUILDFLAG(IS_CHROMEOS) #if BUILDFLAG(IS_CHROMEOS)
if (g_log_format == LogFormat::LOG_FORMAT_SYSLOG) { if (g_log_format == LogFormat::LOG_FORMAT_SYSLOG) {
InitWithSyslogPrefix( InitWithSyslogPrefix(file, line, TickCount(), log_severity_name(severity_),
filename, line, TickCount(), log_severity_name(severity_), g_log_prefix, g_log_prefix, g_log_process_id, g_log_thread_id,
g_log_process_id, g_log_thread_id, g_log_timestamp, g_log_tickcount); g_log_timestamp, g_log_tickcount);
} else } else
#endif // BUILDFLAG(IS_CHROMEOS) #endif // BUILDFLAG(IS_CHROMEOS)
{ {
@@ -1117,7 +1124,7 @@ BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
} }
#if BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_WIN)
Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file, Win32ErrorLogMessage::Win32ErrorLogMessage(std::string_view file,
int line, int line,
LogSeverity severity, LogSeverity severity,
SystemErrorCode err) SystemErrorCode err)
@@ -1145,7 +1152,7 @@ Win32ErrorLogMessageFatal::~Win32ErrorLogMessageFatal() {
} }
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
ErrnoLogMessage::ErrnoLogMessage(const char* file, ErrnoLogMessage::ErrnoLogMessage(std::string_view file,
int line, int line,
LogSeverity severity, LogSeverity severity,
SystemErrorCode err) SystemErrorCode err)

@@ -310,8 +310,7 @@ BASE_EXPORT bool ShouldCreateLogMessage(int severity);
// Gets the VLOG default verbosity level. // Gets the VLOG default verbosity level.
BASE_EXPORT int GetVlogVerbosity(); BASE_EXPORT int GetVlogVerbosity();
// Note that |N| is the size *with* the null terminator. BASE_EXPORT int GetVlogLevelHelper(std::string_view file);
BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
// Gets the current vlog level for the given file (usually taken from __FILE__). // Gets the current vlog level for the given file (usually taken from __FILE__).
template <size_t N> template <size_t N>
@@ -327,7 +326,7 @@ int GetVlogLevel(const char (&file)[N]) {
#if defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_CHROMEOS) #if defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_CHROMEOS)
return -1; return -1;
#else #else
return GetVlogLevelHelper(file, N); return GetVlogLevelHelper(std::string_view(file, N - 1));
#endif // defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_CHROMEOS) #endif // defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_CHROMEOS)
} }
@@ -362,7 +361,7 @@ BASE_EXPORT void RegisterAbslAbortHook();
// however clients can use this function to override with their own handling // however clients can use this function to override with their own handling
// (e.g. a silent one for Unit Tests) // (e.g. a silent one for Unit Tests)
using LogAssertHandlerFunction = using LogAssertHandlerFunction =
base::RepeatingCallback<void(const char* file, base::RepeatingCallback<void(std::string_view file,
int line, int line,
std::string_view message, std::string_view message,
std::string_view stack_trace)>; std::string_view stack_trace)>;
@@ -380,7 +379,7 @@ class BASE_EXPORT ScopedLogAssertHandler {
// Returns true to signal that it handled the message and the message // Returns true to signal that it handled the message and the message
// should not be sent to other log destinations. // should not be sent to other log destinations.
typedef bool (*LogMessageHandlerFunction)(int severity, typedef bool (*LogMessageHandlerFunction)(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str); const std::string& str);
@@ -608,17 +607,21 @@ constexpr LogSeverity LOGGING_DCHECK = LOGGING_FATAL;
// above. // above.
class BASE_EXPORT LogMessage { class BASE_EXPORT LogMessage {
public: public:
// file must be a static string, such as one obtained from the __FILE__ macro.
LogMessage(std::string_view file LIFETIME_BOUND,
int line,
LogSeverity severity);
LogMessage(const char* file, int line, LogSeverity severity); LogMessage(const char* file, int line, LogSeverity severity);
LogMessage(const LogMessage&) = delete; LogMessage(const LogMessage&) = delete;
LogMessage& operator=(const LogMessage&) = delete;
virtual ~LogMessage(); virtual ~LogMessage();
std::ostream& stream() { return stream_; } std::ostream& stream() { return stream_; }
LogSeverity severity() const { return severity_; } LogSeverity severity() const { return severity_; }
std::string str() const { return stream_.str(); } std::string str() const { return stream_.str(); }
const char* file() const { return file_; } std::string_view file() const { return file_; }
int line() const { return line_; } int line() const { return line_; }
// Gets file:line: message in a format suitable for crash reporting. // Gets file:line: message in a format suitable for crash reporting.
@@ -628,7 +631,7 @@ class BASE_EXPORT LogMessage {
void Flush(); void Flush();
private: private:
void Init(const char* file, int line); void Init(std::string_view file, int line);
void HandleFatal(size_t stack_start, const std::string& str_newline) const; void HandleFatal(size_t stack_start, const std::string& str_newline) const;
@@ -637,7 +640,7 @@ class BASE_EXPORT LogMessage {
size_t message_start_; // Offset of the start of the message (past prefix size_t message_start_; // Offset of the start of the message (past prefix
// info). // info).
// The file and line information passed in to the constructor. // The file and line information passed in to the constructor.
const char* const file_; const std::string_view file_;
const int line_; const int line_;
#if BUILDFLAG(IS_CHROMEOS) #if BUILDFLAG(IS_CHROMEOS)
@@ -685,7 +688,7 @@ BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
// Appends a formatted system message of the GetLastError() type. // Appends a formatted system message of the GetLastError() type.
class BASE_EXPORT Win32ErrorLogMessage : public LogMessage { class BASE_EXPORT Win32ErrorLogMessage : public LogMessage {
public: public:
Win32ErrorLogMessage(const char* file, Win32ErrorLogMessage(std::string_view file LIFETIME_BOUND,
int line, int line,
LogSeverity severity, LogSeverity severity,
SystemErrorCode err); SystemErrorCode err);
@@ -712,7 +715,7 @@ class BASE_EXPORT Win32ErrorLogMessageFatal final
// Appends a formatted system message of the errno type // Appends a formatted system message of the errno type
class BASE_EXPORT ErrnoLogMessage : public LogMessage { class BASE_EXPORT ErrnoLogMessage : public LogMessage {
public: public:
ErrnoLogMessage(const char* file, ErrnoLogMessage(std::string_view file LIFETIME_BOUND,
int line, int line,
LogSeverity severity, LogSeverity severity,
SystemErrorCode err); SystemErrorCode err);

@@ -88,9 +88,11 @@ class MockLogSource {
class MockLogAssertHandler { class MockLogAssertHandler {
public: public:
MOCK_METHOD4( MOCK_METHOD4(HandleLogAssert,
HandleLogAssert, void(std::string_view,
void(const char*, int, const std::string_view, const std::string_view)); int,
const std::string_view,
const std::string_view));
}; };
TEST_F(LoggingTest, BasicLogging) { TEST_F(LoggingTest, BasicLogging) {
@@ -755,7 +757,7 @@ TEST_F(LoggingTest, LogPrefix) {
// Use a static because only captureless lambdas can be converted to a // Use a static because only captureless lambdas can be converted to a
// function pointer for SetLogMessageHandler(). // function pointer for SetLogMessageHandler().
static base::NoDestructor<std::string> log_string; static base::NoDestructor<std::string> log_string;
SetLogMessageHandler([](int severity, const char* file, int line, SetLogMessageHandler([](int severity, std::string_view file, int line,
size_t start, const std::string& str) -> bool { size_t start, const std::string& str) -> bool {
*log_string = str; *log_string = str;
return true; return true;
@@ -784,7 +786,7 @@ TEST_F(LoggingTest, LogCrosSyslogFormat) {
// Use a static because only captureless lambdas can be converted to a // Use a static because only captureless lambdas can be converted to a
// function pointer for SetLogMessageHandler(). // function pointer for SetLogMessageHandler().
static base::NoDestructor<std::string> log_string; static base::NoDestructor<std::string> log_string;
SetLogMessageHandler([](int severity, const char* file, int line, SetLogMessageHandler([](int severity, std::string_view file, int line,
size_t start, const std::string& str) -> bool { size_t start, const std::string& str) -> bool {
*log_string = str; *log_string = str;
return true; return true;
@@ -987,7 +989,7 @@ TEST_F(LoggingTest, CorrectSystemErrorUsed) {
// Use a static because only captureless lambdas can be converted to a // Use a static because only captureless lambdas can be converted to a
// function pointer for SetLogMessageHandler(). // function pointer for SetLogMessageHandler().
static base::NoDestructor<std::string> log_string; static base::NoDestructor<std::string> log_string;
SetLogMessageHandler([](int severity, const char* file, int line, SetLogMessageHandler([](int severity, std::string_view file, int line,
size_t start, const std::string& str) -> bool { size_t start, const std::string& str) -> bool {
*log_string = str; *log_string = str;
return true; return true;
@@ -1016,7 +1018,7 @@ TEST_F(LoggingTest, BuildTimeVLOG) {
// Use a static because only captureless lambdas can be converted to a // Use a static because only captureless lambdas can be converted to a
// function pointer for SetLogMessageHandler(). // function pointer for SetLogMessageHandler().
static base::NoDestructor<std::string> log_string; static base::NoDestructor<std::string> log_string;
SetLogMessageHandler([](int severity, const char* file, int line, SetLogMessageHandler([](int severity, std::string_view file, int line,
size_t start, const std::string& str) -> bool { size_t start, const std::string& str) -> bool {
*log_string = str; *log_string = str;
return true; return true;

@@ -11,6 +11,8 @@
#include <initguid.h> #include <initguid.h>
#include <string_view>
#include "base/memory/singleton.h" #include "base/memory/singleton.h"
namespace logging { namespace logging {
@@ -39,7 +41,7 @@ LogEventProvider* LogEventProvider::GetInstance() {
} }
bool LogEventProvider::LogMessage(logging::LogSeverity severity, bool LogEventProvider::LogMessage(logging::LogSeverity severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& message) { const std::string& message) {
@@ -91,9 +93,6 @@ bool LogEventProvider::LogMessage(logging::LogSeverity severity,
} }
EtwMofEvent<5> event(kLogEventId, LOG_MESSAGE_FULL, level); EtwMofEvent<5> event(kLogEventId, LOG_MESSAGE_FULL, level);
if (file == NULL) {
file = "";
}
// Add the stack trace. // Add the stack trace.
event.SetField(0, sizeof(depth), &depth); event.SetField(0, sizeof(depth), &depth);
@@ -101,7 +100,7 @@ bool LogEventProvider::LogMessage(logging::LogSeverity severity,
// The line. // The line.
event.SetField(2, sizeof(line), &line); event.SetField(2, sizeof(line), &line);
// The file. // The file.
event.SetField(3, strlen(file) + 1, file); event.SetField(3, file.length(), file.data());
// And finally the message. // And finally the message.
event.SetField(4, message.length() + 1 - message_start, event.SetField(4, message.length() + 1 - message_start,
message.c_str() + message_start); message.c_str() + message_start);

@@ -8,6 +8,7 @@
#include <stddef.h> #include <stddef.h>
#include <string> #include <string>
#include <string_view>
#include "base/base_export.h" #include "base/base_export.h"
#include "base/logging.h" #include "base/logging.h"
@@ -59,7 +60,7 @@ class BASE_EXPORT LogEventProvider : public base::win::EtwTraceProvider {
static LogEventProvider* GetInstance(); static LogEventProvider* GetInstance();
static bool LogMessage(logging::LogSeverity severity, static bool LogMessage(logging::LogSeverity severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str); const std::string& str);

@@ -157,7 +157,7 @@ bool XmlUnitTestResultPrinter::Initialize(const FilePath& output_file_path) {
return true; return true;
} }
void XmlUnitTestResultPrinter::OnAssert(const char* file, void XmlUnitTestResultPrinter::OnAssert(std::string_view file,
int line, int line,
const std::string& summary, const std::string& summary,
const std::string& message) { const std::string& message) {
@@ -240,7 +240,7 @@ void XmlUnitTestResultPrinter::OnTestSuiteEnd(
} }
void XmlUnitTestResultPrinter::WriteTestPartResult( void XmlUnitTestResultPrinter::WriteTestPartResult(
const char* file, std::string_view file,
int line, int line,
testing::TestPartResult::Type result_type, testing::TestPartResult::Type result_type,
const std::string& summary, const std::string& summary,
@@ -268,11 +268,12 @@ void XmlUnitTestResultPrinter::WriteTestPartResult(
std::string summary_encoded = base::Base64Encode(summary); std::string summary_encoded = base::Base64Encode(summary);
std::string message_encoded = base::Base64Encode(message); std::string message_encoded = base::Base64Encode(message);
fprintf(output_file_.get(), fprintf(output_file_.get(),
" <x-test-result-part type=\"%s\" file=\"%s\" line=\"%d\">\n" " <x-test-result-part type=\"%s\" file=\"%.*s\" line=\"%d\">\n"
" <summary>%s</summary>\n" " <summary>%s</summary>\n"
" <message>%s</message>\n" " <message>%s</message>\n"
" </x-test-result-part>\n", " </x-test-result-part>\n",
type, file, line, summary_encoded.c_str(), message_encoded.c_str()); type, static_cast<int>(file.length()), file.data(), line,
summary_encoded.c_str(), message_encoded.c_str());
fflush(output_file_); fflush(output_file_);
} }

@@ -51,7 +51,7 @@ class XmlUnitTestResultPrinter : public testing::EmptyTestEventListener {
[[nodiscard]] bool Initialize(const FilePath& output_file_path); [[nodiscard]] bool Initialize(const FilePath& output_file_path);
// CHECK/DCHECK failed. Print file/line and message to the xml. // CHECK/DCHECK failed. Print file/line and message to the xml.
void OnAssert(const char* file, void OnAssert(std::string_view file,
int line, int line,
const std::string& summary, const std::string& summary,
const std::string& message); const std::string& message);
@@ -63,7 +63,7 @@ class XmlUnitTestResultPrinter : public testing::EmptyTestEventListener {
void OnTestEnd(const testing::TestInfo& test_info) override; void OnTestEnd(const testing::TestInfo& test_info) override;
void OnTestSuiteEnd(const testing::TestSuite& test_suite) override; void OnTestSuiteEnd(const testing::TestSuite& test_suite) override;
void WriteTestPartResult(const char* file, void WriteTestPartResult(std::string_view file,
int line, int line,
testing::TestPartResult::Type type, testing::TestPartResult::Type type,
const std::string& summary, const std::string& summary,

@@ -49,7 +49,7 @@ void MockLog::StopCapturingLogs() {
// static // static
bool MockLog::LogMessageHandler(int severity, bool MockLog::LogMessageHandler(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -67,7 +67,7 @@ class MockLog {
// destinations. // destinations.
MOCK_METHOD5(Log, MOCK_METHOD5(Log,
bool(int severity, bool(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str)); const std::string& str));
@@ -82,7 +82,7 @@ class MockLog {
// Static function which is set as the logging message handler. // Static function which is set as the logging message handler.
// Called once for each message. // Called once for each message.
static bool LogMessageHandler(int severity, static bool LogMessageHandler(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str); const std::string& str);

@@ -1573,7 +1573,7 @@ TEST_F(TaskEnvironmentTest, ParallelExecutionFenceNonMainThreadDeath) {
namespace { namespace {
bool FailOnTaskEnvironmentLog(int severity, bool FailOnTaskEnvironmentLog(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -444,7 +444,7 @@ void TestSuite::DisableCheckForLeakedGlobals() {
check_for_leaked_globals_ = false; check_for_leaked_globals_ = false;
} }
void TestSuite::UnitTestAssertHandler(const char* file, void TestSuite::UnitTestAssertHandler(const std::string_view file,
int line, int line,
std::string_view summary, std::string_view summary,
std::string_view stack_trace) { std::string_view stack_trace) {

@@ -71,7 +71,7 @@ class TestSuite {
// By default fatal log messages (e.g. from DCHECKs) result in error dialogs // By default fatal log messages (e.g. from DCHECKs) result in error dialogs
// which gum up buildbots. Use a minimalistic assert handler which just // which gum up buildbots. Use a minimalistic assert handler which just
// terminates the process. // terminates the process.
void UnitTestAssertHandler(const char* file, void UnitTestAssertHandler(std::string_view file,
int line, int line,
std::string_view summary, std::string_view summary,
std::string_view stack_trace); std::string_view stack_trace);

@@ -37,11 +37,12 @@ void InternedSourceLocation::Add(
const TraceSourceLocation& location) { const TraceSourceLocation& location) {
auto* msg = interned_data->add_source_locations(); auto* msg = interned_data->add_source_locations();
msg->set_iid(iid); msg->set_iid(iid);
if (location.file_name != nullptr) { if (!location.file_name.empty()) {
msg->set_file_name(location.file_name); msg->set_file_name(location.file_name.data(), location.file_name.length());
} }
if (location.function_name != nullptr) { if (!location.function_name.empty()) {
msg->set_function_name(location.function_name); msg->set_function_name(location.function_name.data(),
location.function_name.length());
} }
// TODO(ssid): Add line number once it is allowed in internal proto. // TODO(ssid): Add line number once it is allowed in internal proto.
// TODO(ssid): Add program counter to the proto fields when // TODO(ssid): Add program counter to the proto fields when

@@ -7,6 +7,7 @@
#include <optional> #include <optional>
#include <string> #include <string>
#include <string_view>
#include "base/base_export.h" #include "base/base_export.h"
#include "base/hash/hash.h" #include "base/hash/hash.h"
@@ -25,13 +26,16 @@ namespace trace_event {
// for log event's location since base::Location uses program counter based // for log event's location since base::Location uses program counter based
// location. // location.
struct BASE_EXPORT TraceSourceLocation { struct BASE_EXPORT TraceSourceLocation {
const char* function_name = nullptr; // While these are string_views, only the address is used for equality and
const char* file_name = nullptr; // hashing. The length is still needed when interning a new location since the
// strings may not be null-terminated.
std::string_view function_name;
std::string_view file_name;
int line_number = 0; int line_number = 0;
TraceSourceLocation() = default; TraceSourceLocation() = default;
TraceSourceLocation(const char* function_name, TraceSourceLocation(std::string_view function_name,
const char* file_name, std::string_view file_name,
int line_number) int line_number)
: function_name(function_name), : function_name(function_name),
file_name(file_name), file_name(file_name),
@@ -45,8 +49,8 @@ struct BASE_EXPORT TraceSourceLocation {
line_number(location.line_number()) {} line_number(location.line_number()) {}
bool operator==(const TraceSourceLocation& other) const { bool operator==(const TraceSourceLocation& other) const {
return file_name == other.file_name && return file_name.data() == other.file_name.data() &&
function_name == other.function_name && function_name.data() == other.function_name.data() &&
line_number == other.line_number; line_number == other.line_number;
} }
}; };
@@ -76,8 +80,8 @@ struct hash<base::trace_event::TraceSourceLocation> {
std::size_t operator()( std::size_t operator()(
const base::trace_event::TraceSourceLocation& loc) const { const base::trace_event::TraceSourceLocation& loc) const {
return base::HashInts( return base::HashInts(
base::HashInts(reinterpret_cast<uintptr_t>(loc.file_name), base::HashInts(reinterpret_cast<uintptr_t>(loc.file_name.data()),
reinterpret_cast<uintptr_t>(loc.function_name)), reinterpret_cast<uintptr_t>(loc.function_name.data())),
static_cast<size_t>(loc.line_number)); static_cast<size_t>(loc.line_number));
} }
}; };

@@ -20,6 +20,7 @@
#include <map> #include <map>
#include <memory> #include <memory>
#include <string> #include <string>
#include <string_view>
#include <utility> #include <utility>
#include <vector> #include <vector>
@@ -1639,7 +1640,7 @@ TEST_F(TraceEventTestFixture, ThreadOnceBlocking) {
std::string* g_log_buffer = nullptr; std::string* g_log_buffer = nullptr;
bool MockLogMessageHandler(int, bool MockLogMessageHandler(int,
const char*, std::string_view,
int, int,
size_t, size_t,
const std::string& str) { const std::string& str) {
@@ -1672,7 +1673,7 @@ TEST_F(TraceEventTestFixture, EchoToConsole) {
} }
bool LogMessageHandlerWithTraceEvent(int, bool LogMessageHandlerWithTraceEvent(int,
const char*, std::string_view,
int, int,
size_t, size_t,
const std::string&) { const std::string&) {

@@ -1150,8 +1150,8 @@ IN_PROC_BROWSER_TEST_F(ScalableIphBrowserTest, Log) {
// variable as a captureless lambda can be converted to a function pointer. // variable as a captureless lambda can be converted to a function pointer.
static base::NoDestructor<std::vector<std::string>> captured_logs; static base::NoDestructor<std::vector<std::string>> captured_logs;
CHECK_EQ(nullptr, logging::GetLogMessageHandler()); CHECK_EQ(nullptr, logging::GetLogMessageHandler());
logging::SetLogMessageHandler([](int severity, const char* file, int line, logging::SetLogMessageHandler([](int severity, std::string_view file,
size_t message_start, int line, size_t message_start,
const std::string& str) { const std::string& str) {
captured_logs->push_back(str); captured_logs->push_back(str);
return true; return true;
@@ -1193,8 +1193,8 @@ IN_PROC_BROWSER_TEST_F(ScalableIphBrowserTestDebugOff, NoLog) {
// variable as a captureless lambda can be converted to a function pointer. // variable as a captureless lambda can be converted to a function pointer.
static base::NoDestructor<std::vector<std::string>> captured_logs; static base::NoDestructor<std::vector<std::string>> captured_logs;
CHECK_EQ(nullptr, logging::GetLogMessageHandler()); CHECK_EQ(nullptr, logging::GetLogMessageHandler());
logging::SetLogMessageHandler([](int severity, const char* file, int line, logging::SetLogMessageHandler([](int severity, std::string_view file,
size_t message_start, int line, size_t message_start,
const std::string& str) { const std::string& str) {
captured_logs->push_back(str); captured_logs->push_back(str);
return true; return true;

@@ -9,6 +9,7 @@
#include "chrome/browser/dom_distiller/dom_distiller_service_factory.h" #include "chrome/browser/dom_distiller/dom_distiller_service_factory.h"
#include <string_view>
#include <utility> #include <utility>
#include "base/task/sequenced_task_runner.h" #include "base/task/sequenced_task_runner.h"
@@ -90,8 +91,7 @@ DomDistillerServiceFactory::BuildServiceInstanceForBrowserContext(
dom_distiller::proto::DomDistillerOptions options; dom_distiller::proto::DomDistillerOptions options;
if (VLOG_IS_ON(1)) { if (VLOG_IS_ON(1)) {
options.set_debug_level(logging::GetVlogLevelHelper( options.set_debug_level(logging::GetVlogLevelHelper(FROM_HERE.file_name()));
FROM_HERE.file_name(), ::strlen(FROM_HERE.file_name())));
} }
// Options for pagination algorithm: // Options for pagination algorithm:
// - "next": detect anchors with "next" text // - "next": detect anchors with "next" text

@@ -3,6 +3,7 @@
// found in the LICENSE file. // found in the LICENSE file.
#include <memory> #include <memory>
#include <string_view>
#include "base/containers/contains.h" #include "base/containers/contains.h"
#include "base/test/scoped_feature_list.h" #include "base/test/scoped_feature_list.h"
@@ -107,7 +108,7 @@ class ScopedLogMessageWatcher {
private: private:
static bool MessageHandler(int severity, static bool MessageHandler(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -7,6 +7,7 @@
#include <stddef.h> #include <stddef.h>
#include <limits> #include <limits>
#include <string_view>
#include <tuple> #include <tuple>
#include "base/json/json_reader.h" #include "base/json/json_reader.h"
@@ -79,12 +80,13 @@ base::LazyInstance<bool>::DestructorAtExit hit_javascript_errors_ =
// WebrtcTestBase-inheriting test cases do not run in parallel (if they did they // WebrtcTestBase-inheriting test cases do not run in parallel (if they did they
// would race to look at the log, which is global to all tests). // would race to look at the log, which is global to all tests).
bool JavascriptErrorDetectingLogHandler(int severity, bool JavascriptErrorDetectingLogHandler(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {
if (file == nullptr || std::string("CONSOLE") != file) if (file != "CONSOLE") {
return false; return false;
}
// TODO(crbug.com/40608140): Fix AppRTC and stop ignoring this error. // TODO(crbug.com/40608140): Fix AppRTC and stop ignoring this error.
if (str.find("Synchronous XHR in page dismissal") != std::string::npos) if (str.find("Synchronous XHR in page dismissal") != std::string::npos)

@@ -4,6 +4,8 @@
#include <stddef.h> #include <stddef.h>
#include <string_view>
#include "base/command_line.h" #include "base/command_line.h"
#include "base/logging.h" #include "base/logging.h"
#include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser.h"
@@ -30,12 +32,11 @@ namespace {
static bool had_console_errors = false; static bool had_console_errors = false;
bool HandleMessage(int severity, bool HandleMessage(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {
if (severity == logging::LOGGING_ERROR && file && if (severity == logging::LOGGING_ERROR && file == "CONSOLE") {
file == std::string("CONSOLE")) {
had_console_errors = true; had_console_errors = true;
} }
return false; return false;

@@ -110,7 +110,7 @@ const GUID kChromeTraceProviderName = {
// Assertion handler for logging errors that occur when dialogs are // Assertion handler for logging errors that occur when dialogs are
// silenced. To record a new error, pass the log string associated // silenced. To record a new error, pass the log string associated
// with that error in the str parameter. // with that error in the str parameter.
NOINLINE void SilentRuntimeAssertHandler(const char* file, NOINLINE void SilentRuntimeAssertHandler(std::string_view file,
int line, int line,
std::string_view message, std::string_view message,
std::string_view stack_trace) { std::string_view stack_trace) {

@@ -65,12 +65,11 @@ base::LazyInstance<std::vector<std::string>>::DestructorAtExit
// Intercepts all log messages. // Intercepts all log messages.
bool LogHandler(int severity, bool LogHandler(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {
if (severity == logging::LOGGING_ERROR && file && if (severity == logging::LOGGING_ERROR && file == "CONSOLE") {
std::string("CONSOLE") == file) {
g_error_messages.Get().push_back(str); g_error_messages.Get().push_back(str);
} }

@@ -16,6 +16,7 @@
#include <array> #include <array>
#include <cmath> #include <cmath>
#include <memory> #include <memory>
#include <string_view>
#include <utility> #include <utility>
#include "base/command_line.h" #include "base/command_line.h"
@@ -119,7 +120,7 @@ bool InternalIsVLogOn(int vlog_level) {
} }
bool HandleLogMessage(int severity, bool HandleLogMessage(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -34,19 +34,20 @@ ScopedLogMessage::~ScopedLogMessage() {
const std::string string_from_stream = stream_.str(); const std::string string_from_stream = stream_.str();
auto* log_buffer = LogBuffer::GetInstance(); auto* log_buffer = LogBuffer::GetInstance();
CHECK(log_buffer); CHECK(log_buffer);
log_buffer->AddLogMessage(LogBuffer::LogMessage( log_buffer->AddLogMessage(
string_from_stream, base::Time::Now(), file_.data(), line_, severity_)); LogBuffer::LogMessage(string_from_stream, base::Time::Now(),
std::string(file_), line_, severity_));
// Don't emit VERBOSE-level logging to the standard logging system unless // Don't emit VERBOSE-level logging to the standard logging system unless
// verbose logging is enabled for the source file. // verbose logging is enabled for the source file.
if (severity_ <= logging::LOGGING_VERBOSE && if (severity_ <= logging::LOGGING_VERBOSE &&
logging::GetVlogLevelHelper(file_.data(), file_.size()) <= 0) { logging::GetVlogLevelHelper(file_) <= 0) {
return; return;
} }
// The destructor of |log_message| also creates a log for the standard logging // The destructor of |log_message| also creates a log for the standard logging
// system. // system.
logging::LogMessage log_message(file_.data(), line_, severity_); logging::LogMessage log_message(file_, line_, severity_);
log_message.stream() << string_from_stream; log_message.stream() << string_from_stream;
} }

@@ -21,10 +21,10 @@ namespace ash::multidevice {
// Examples: // Examples:
// PA_LOG(INFO) << "Waiting for " << x << " pending requests."; // PA_LOG(INFO) << "Waiting for " << x << " pending requests.";
// PA_LOG(ERROR) << "Request failed: " << error_string; // PA_LOG(ERROR) << "Request failed: " << error_string;
#define PA_LOG(severity) \ #define PA_LOG(severity) \
ash::multidevice::ScopedLogMessage( \ ash::multidevice::ScopedLogMessage( \
std::string_view(__FILE__, std::size(__FILE__)), __LINE__, \ std::string_view(__FILE__, std::size(__FILE__) - 1), __LINE__, \
logging::LOGGING_##severity) \ logging::LOGGING_##severity) \
.stream() .stream()
// Disables all logging while in scope. Intended to be called only from test // Disables all logging while in scope. Intended to be called only from test

@@ -6,6 +6,8 @@
#include <stddef.h> #include <stddef.h>
#include <string_view>
#include "base/lazy_instance.h" #include "base/lazy_instance.h"
#include "base/numerics/safe_conversions.h" #include "base/numerics/safe_conversions.h"
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
@@ -26,7 +28,7 @@ const char kLog4[] = "Unremarkable maple";
base::LazyInstance<std::vector<std::string>>::DestructorAtExit g_standard_logs = base::LazyInstance<std::vector<std::string>>::DestructorAtExit g_standard_logs =
LAZY_INSTANCE_INITIALIZER; LAZY_INSTANCE_INITIALIZER;
bool HandleStandardLogMessage(int severity, bool HandleStandardLogMessage(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -26,7 +26,7 @@ ScopedLogMessage::ScopedLogMessage(std::string_view file,
ScopedLogMessage::~ScopedLogMessage() { ScopedLogMessage::~ScopedLogMessage() {
if (ShouldEmitToStandardLog()) { if (ShouldEmitToStandardLog()) {
// Create a log for the standard logging system. // Create a log for the standard logging system.
logging::LogMessage log_message(file_.data(), line_, severity_); logging::LogMessage log_message(file_, line_, severity_);
log_message.stream() << stream_.str(); log_message.stream() << stream_.str();
} }
} }
@@ -37,7 +37,7 @@ bool ScopedLogMessage::ShouldEmitToStandardLog() const {
// - The Vlog Level for |file_| is at least 1 // - The Vlog Level for |file_| is at least 1
// - The --quick-start-verbose-logging switch is enabled // - The --quick-start-verbose-logging switch is enabled
return severity_ > logging::LOGGING_VERBOSE || return severity_ > logging::LOGGING_VERBOSE ||
logging::GetVlogLevelHelper(file_.data(), file_.size()) > 0 || logging::GetVlogLevelHelper(file_) > 0 ||
base::CommandLine::ForCurrentProcess()->HasSwitch( base::CommandLine::ForCurrentProcess()->HasSwitch(
kQuickStartVerboseLoggingSwitch); kQuickStartVerboseLoggingSwitch);
} }

@@ -2,14 +2,16 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#include "chromeos/ash/components/quick_start/logging.h"
#include <stddef.h> #include <stddef.h>
#include <string_view>
#include "base/command_line.h" #include "base/command_line.h"
#include "base/no_destructor.h" #include "base/no_destructor.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
#include "chromeos/ash/components/quick_start/logging.h"
namespace ash::quick_start { namespace ash::quick_start {
namespace { namespace {
@@ -27,7 +29,7 @@ std::vector<std::string>& GetStandardLogs() {
} }
bool HandleStandardLogMessage(int severity, bool HandleStandardLogMessage(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -16,17 +16,17 @@ CrossDeviceScopedLogMessage::~CrossDeviceScopedLogMessage() {
const std::string string_from_stream = stream_.str(); const std::string string_from_stream = stream_.str();
CrossDeviceLogBuffer::GetInstance()->AddLogMessage( CrossDeviceLogBuffer::GetInstance()->AddLogMessage(
CrossDeviceLogBuffer::LogMessage(string_from_stream, feature_, CrossDeviceLogBuffer::LogMessage(string_from_stream, feature_,
base::Time::Now(), file_.data(), line_, base::Time::Now(), std::string(file_),
severity_)); line_, severity_));
// Don't emit VERBOSE-level logging to the standard logging system. // Don't emit VERBOSE-level logging to the standard logging system.
if (severity_ <= logging::LOGGING_VERBOSE && if (severity_ <= logging::LOGGING_VERBOSE &&
logging::GetVlogLevelHelper(file_.data(), file_.size()) <= 0) { logging::GetVlogLevelHelper(file_) <= 0) {
return; return;
} }
// The destructor of |log_message| also creates a log for the standard logging // The destructor of |log_message| also creates a log for the standard logging
// system. // system.
logging::LogMessage log_message(file_.data(), line_, severity_); logging::LogMessage log_message(file_, line_, severity_);
log_message.stream() << string_from_stream; log_message.stream() << string_from_stream;
} }

@@ -15,9 +15,9 @@
// Use the CD_LOG() macro for all logging related to Cross Device Features so // Use the CD_LOG() macro for all logging related to Cross Device Features so
// the debug page can reflect all logs related to this feature in the internal // the debug page can reflect all logs related to this feature in the internal
// debug WebUI (chrome://nearby-internals). // debug WebUI (chrome://nearby-internals).
#define CD_LOG(severity, feature) \ #define CD_LOG(severity, feature) \
CrossDeviceScopedLogMessage(std::string_view(__FILE__, std::size(__FILE__)), \ CrossDeviceScopedLogMessage(std::string_view(__FILE__), __LINE__, \
__LINE__, logging::LOGGING_##severity, feature) \ logging::LOGGING_##severity, feature) \
.stream() .stream()
// An intermediate object used by the CD_LOG macro, wrapping a // An intermediate object used by the CD_LOG macro, wrapping a

@@ -2,15 +2,17 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#include "components/cross_device/logging/logging.h"
#include <stddef.h> #include <stddef.h>
#include <string_view>
#include "base/no_destructor.h" #include "base/no_destructor.h"
#include "base/numerics/safe_conversions.h" #include "base/numerics/safe_conversions.h"
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "components/cross_device/logging/log_buffer.h" #include "components/cross_device/logging/log_buffer.h"
#include "components/cross_device/logging/logging.h" #include "testing/gtest/include/gtest/gtest.h"
namespace { namespace {
@@ -27,7 +29,7 @@ std::vector<std::string>& GetStandardLogs() {
} }
bool HandleStandardLogMessage(int severity, bool HandleStandardLogMessage(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -35,7 +35,7 @@ namespace {
bool IsLoggingOn(LogLevel level, std::string_view file) { bool IsLoggingOn(LogLevel level, std::string_view file) {
if (level == LogLevel::kVerbose) { if (level == LogLevel::kVerbose) {
return ::logging::GetVlogLevelHelper(file.data(), file.size()) > 0; return ::logging::GetVlogLevelHelper(file) > 0;
} }
return ::logging::ShouldCreateLogMessage(MapLogLevel(level)); return ::logging::ShouldCreateLogMessage(MapLogLevel(level));
} }

@@ -6,6 +6,8 @@
#include <stddef.h> #include <stddef.h>
#include <string_view>
#include "ash/constants/ash_features.h" #include "ash/constants/ash_features.h"
#include "base/no_destructor.h" #include "base/no_destructor.h"
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
@@ -31,7 +33,7 @@ std::vector<std::string>& GetStandardLogs() {
} }
bool HandleStandardLogMessage(int severity, bool HandleStandardLogMessage(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -145,19 +145,16 @@ void PolicyLogger::LogHelper::StreamLog() const {
// Check for verbose logging. // Check for verbose logging.
if (log_verbosity_ != policy::PolicyLogger::LogHelper::kNoVerboseLog) { if (log_verbosity_ != policy::PolicyLogger::LogHelper::kNoVerboseLog) {
LAZY_STREAM( LAZY_STREAM(::logging::LogMessage(file_, line_, -(log_verbosity_)).stream(),
::logging::LogMessage(file_.data(), line_, -(log_verbosity_)).stream(), log_verbosity_ <= ::logging::GetVlogLevelHelper(file_))
log_verbosity_ <=
::logging::GetVlogLevelHelper(file_.data(), file_.size()))
<< message_buffer_.str(); << message_buffer_.str();
return; return;
} }
int log_severity_int = GetLogSeverityInt(log_severity_); int log_severity_int = GetLogSeverityInt(log_severity_);
LAZY_STREAM( LAZY_STREAM(::logging::LogMessage(file_, line_, log_severity_int).stream(),
::logging::LogMessage(file_.data(), line_, log_severity_int).stream(), ::logging::ShouldCreateLogMessage(log_severity_int))
::logging::ShouldCreateLogMessage(log_severity_int))
<< message_buffer_.str(); << message_buffer_.str();
} }

@@ -172,12 +172,12 @@ struct LogMessage {
// Forward declare log handlers so they can be used within LogMessageManager. // Forward declare log handlers so they can be used within LogMessageManager.
bool PreInitializeLogHandler(int severity, bool PreInitializeLogHandler(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& message); const std::string& message);
bool PostInitializeLogHandler(int severity, bool PostInitializeLogHandler(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& message); const std::string& message);
@@ -269,7 +269,7 @@ LogMessageManager* GetLogMessageManager() {
} }
bool PreInitializeLogHandler(int severity, bool PreInitializeLogHandler(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& message) { const std::string& message) {
@@ -280,7 +280,7 @@ bool PreInitializeLogHandler(int severity,
} }
bool PostInitializeLogHandler(int severity, bool PostInitializeLogHandler(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& message) { const std::string& message) {

@@ -530,8 +530,8 @@ void BrowserTestBase::SetUp() {
if (base::CommandLine::ForCurrentProcess()->HasSwitch( if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableTracing)) { switches::kEnableTracing)) {
DCHECK(!logging::GetLogMessageHandler()); DCHECK(!logging::GetLogMessageHandler());
logging::SetLogMessageHandler([](int severity, const char* file, int line, logging::SetLogMessageHandler([](int severity, std::string_view file,
size_t message_start, int line, size_t message_start,
const std::string& str) { const std::string& str) {
// TODO(crbug.com/40161080): Print the message to the console before // TODO(crbug.com/40161080): Print the message to the console before
// calling this to ensure that the message is still printed if something // calling this to ensure that the message is still printed if something

@@ -17,10 +17,11 @@ ScopedDisableExitOnDFatal::ScopedDisableExitOnDFatal()
ScopedDisableExitOnDFatal::~ScopedDisableExitOnDFatal() = default; ScopedDisableExitOnDFatal::~ScopedDisableExitOnDFatal() = default;
// static // static
void ScopedDisableExitOnDFatal::LogAssertHandler(const char* file, void ScopedDisableExitOnDFatal::LogAssertHandler(
int line, std::string_view file,
std::string_view message, int line,
std::string_view stack_trace) { const std::string_view message,
const std::string_view stack_trace) {
// Simply swallow the assert. // Simply swallow the assert.
} }

@@ -30,7 +30,7 @@ class ScopedDisableExitOnDFatal {
private: private:
// Static function which is set as the logging assert handler. // Static function which is set as the logging assert handler.
// Called when there is a check failure. // Called when there is a check failure.
static void LogAssertHandler(const char* file, static void LogAssertHandler(std::string_view file,
int line, int line,
std::string_view message, std::string_view message,
std::string_view stack_trace); std::string_view stack_trace);

@@ -386,7 +386,7 @@ bool StartCrashThread() {
return true; return true;
} }
void CrashHandler(const char* file, void CrashHandler(std::string_view file,
int line, int line,
std::string_view str, std::string_view str,
std::string_view stack_trace) { std::string_view stack_trace) {

@@ -4,6 +4,8 @@
#include "remoting/host/native_messaging/log_message_handler.h" #include "remoting/host/native_messaging/log_message_handler.h"
#include <string_view>
#include "base/functional/bind.h" #include "base/functional/bind.h"
#include "base/lazy_instance.h" #include "base/lazy_instance.h"
#include "base/logging.h" #include "base/logging.h"
@@ -55,7 +57,7 @@ const char* LogMessageHandler::kDebugMessageTypeName = "_debug_log";
// static // static
bool LogMessageHandler::OnLogMessage(logging::LogSeverity severity, bool LogMessageHandler::OnLogMessage(logging::LogSeverity severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {
@@ -69,7 +71,7 @@ bool LogMessageHandler::OnLogMessage(logging::LogSeverity severity,
void LogMessageHandler::PostLogMessageToCorrectThread( void LogMessageHandler::PostLogMessageToCorrectThread(
logging::LogSeverity severity, logging::LogSeverity severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {
@@ -101,7 +103,7 @@ void LogMessageHandler::PostLogMessageToCorrectThread(
} }
void LogMessageHandler::SendLogMessageToClient(logging::LogSeverity severity, void LogMessageHandler::SendLogMessageToClient(logging::LogSeverity severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -45,17 +45,17 @@ class LogMessageHandler {
// TODO(yuweih): Reimplement this class using using a message queue which is // TODO(yuweih): Reimplement this class using using a message queue which is
// protected by |g_log_message_handler_lock|. // protected by |g_log_message_handler_lock|.
static bool OnLogMessage(int severity, static bool OnLogMessage(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str); const std::string& str);
void PostLogMessageToCorrectThread(int severity, void PostLogMessageToCorrectThread(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str); const std::string& str);
void SendLogMessageToClient(int severity, void SendLogMessageToClient(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str); const std::string& str);

@@ -41,7 +41,7 @@ void RunPostTestsChecks(const base::FilePath& orig_cwd) {
} // namespace sandbox } // namespace sandbox
#if !defined(SANDBOX_USES_BASE_TEST_SUITE) #if !defined(SANDBOX_USES_BASE_TEST_SUITE)
void UnitTestAssertHandler(const char* file, void UnitTestAssertHandler(std::string_view file,
int line, int line,
std::string_view message, std::string_view message,
std::string_view stack_trace) { std::string_view stack_trace) {

@@ -59,3 +59,5 @@ Local Modifications:
"base/allocator/partition_allocator/src/partition_alloc/partition_alloc_buildflags.h", "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_buildflags.h",
https://crbug.com/1467773 https://crbug.com/1467773
- CPEPrefix for third_party/zlib is added to README.chromium - CPEPrefix for third_party/zlib is added to README.chromium
- logging::LogMessageHandler signature updated to use std::string_view in
crashpad/util/thread/thread_log_messages.cc

@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
#include <string_view>
#include <inttypes.h> #include <inttypes.h>
#include "base/logging.h" #include "base/logging.h"
@@ -45,10 +47,11 @@ class FakeProcessMemory : public ProcessMemory {
extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) { extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) {
// Swallow all logs to avoid spam. // Swallow all logs to avoid spam.
logging::SetLogMessageHandler( logging::SetLogMessageHandler([](logging::LogSeverity,
[](logging::LogSeverity, const char*, int, size_t, const std::string&) { std::string_view,
return true; int,
}); size_t,
const std::string&) { return true; });
return 0; return 0;
} }

@@ -16,6 +16,8 @@
#include <sys/types.h> #include <sys/types.h>
#include <string_view>
#include "base/check_op.h" #include "base/check_op.h"
#include "base/logging.h" #include "base/logging.h"
@@ -26,7 +28,7 @@ namespace {
thread_local std::vector<std::string>* thread_local_log_messages; thread_local std::vector<std::string>* thread_local_log_messages;
bool LogMessageHandler(logging::LogSeverity severity, bool LogMessageHandler(logging::LogSeverity severity,
const char* file_path, std::string_view file_path,
int line, int line,
size_t message_start, size_t message_start,
const std::string& string) { const std::string& string) {

@@ -14,6 +14,7 @@
#include <algorithm> #include <algorithm>
#include <atomic> #include <atomic>
#include <iomanip> #include <iomanip>
#include <string_view>
#include "base/logging.h" #include "base/logging.h"
#include "base/notreached.h" #include "base/notreached.h"
@@ -226,7 +227,7 @@ bool CheckVlogIsOnHelper(LoggingSeverity severity,
const char* file, const char* file,
size_t N) { size_t N) {
return WebRtcVerbosityLevel(severity) <= return WebRtcVerbosityLevel(severity) <=
::logging::GetVlogLevelHelper(file, N); ::logging::GetVlogLevelHelper(std::string_view(file, N - 1));
} }
} // namespace webrtc } // namespace webrtc

@@ -5,6 +5,7 @@
#include <iostream> #include <iostream>
#include <memory> #include <memory>
#include <string> #include <string>
#include <string_view>
#include "base/at_exit.h" #include "base/at_exit.h"
#include "base/command_line.h" #include "base/command_line.h"
@@ -24,7 +25,7 @@ namespace {
constexpr char kHelpSwitch[] = "help"; constexpr char kHelpSwitch[] = "help";
bool AXDumpEventsLogMessageHandler(int severity, bool AXDumpEventsLogMessageHandler(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {

@@ -6,6 +6,7 @@
#include <iostream> #include <iostream>
#include <numeric> #include <numeric>
#include <string> #include <string>
#include <string_view>
#include "base/at_exit.h" #include "base/at_exit.h"
#include "base/command_line.h" #include "base/command_line.h"
@@ -22,7 +23,7 @@ constexpr char kApiSwitch[] = "api";
constexpr char kHelpSwitch[] = "help"; constexpr char kHelpSwitch[] = "help";
bool AXDumpTreeLogMessageHandler(int severity, bool AXDumpTreeLogMessageHandler(int severity,
const char* file, std::string_view file,
int line, int line,
size_t message_start, size_t message_start,
const std::string& str) { const std::string& str) {