From acc60d0c3832e9b64759698f9f7a0062767c78c3 Mon Sep 17 00:00:00 2001 From: Andrei Polushin Date: Sat, 13 Aug 2022 17:21:25 +0700 Subject: [PATCH] logsink: fix multiple issues with LogSink::ToString() (#852) 1. Initializing std::ostringstream with a string makes no sense, as the string becomes an initial value of an underlying buffer; seek-to-end is not performed, so the initial value gets completely overwritten by subsequent writing. 2. Flag `log_year_in_prefix` should be considered, as if formatting a regular logging message. 3. Writing a buffer to std::ostream is better expressed with write(s,n). --- src/logging.cc | 14 +++++++++----- src/windows/port.h | 2 +- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/logging.cc b/src/logging.cc index c0ec8c9..0dd4bb7 100644 --- a/src/logging.cc +++ b/src/logging.cc @@ -2133,12 +2133,14 @@ void LogSink::WaitTillSent() { string LogSink::ToString(LogSeverity severity, const char* file, int line, const LogMessageTime& logmsgtime, const char* message, size_t message_len) { - ostringstream stream(string(message, message_len)); + ostringstream stream; stream.fill('0'); - stream << LogSeverityNames[severity][0] - << setw(4) << 1900 + logmsgtime.year() - << setw(2) << 1 + logmsgtime.month() + stream << LogSeverityNames[severity][0]; + if (FLAGS_log_year_in_prefix) { + stream << setw(4) << 1900 + logmsgtime.year(); + } + stream << setw(2) << 1 + logmsgtime.month() << setw(2) << logmsgtime.day() << ' ' << setw(2) << logmsgtime.hour() << ':' @@ -2150,7 +2152,9 @@ string LogSink::ToString(LogSeverity severity, const char* file, int line, << ' ' << file << ':' << line << "] "; - stream << string(message, message_len); + // A call to `write' is enclosed in parenthneses to prevent possible macro + // expansion. On Windows, `write' could be a macro defined for portability. + (stream.write)(message, static_cast(message_len)); return stream.str(); } diff --git a/src/windows/port.h b/src/windows/port.h index a71979f..bafb143 100755 --- a/src/windows/port.h +++ b/src/windows/port.h @@ -84,7 +84,7 @@ #define getcwd _getcwd #define open _open #define read _read -#define write _write +#define write(fd, p, n) _write(fd, p, n) #define lseek _lseek #define close _close #define popen _popen