Skip to content

Commit

Permalink
logsink: fix multiple issues with LogSink::ToString() (#852)
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
anpol committed Aug 13, 2022
1 parent 6d5b384 commit acc60d0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
14 changes: 9 additions & 5 deletions src/logging.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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() << ':'
Expand All @@ -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<std::streamsize>(message_len));
return stream.str();
}

Expand Down
2 changes: 1 addition & 1 deletion src/windows/port.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit acc60d0

Please sign in to comment.