log_message.cc 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. //
  2. // Copyright 2022 The Abseil Authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // https://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #include "absl/log/internal/log_message.h"
  16. #include <stddef.h>
  17. #include <stdint.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #ifndef _WIN32
  21. #include <unistd.h>
  22. #endif
  23. #include <algorithm>
  24. #include <array>
  25. #include <atomic>
  26. #include <ios>
  27. #include <memory>
  28. #include <ostream>
  29. #include <string>
  30. #include <tuple>
  31. #include "absl/base/attributes.h"
  32. #include "absl/base/config.h"
  33. #include "absl/base/internal/raw_logging.h"
  34. #include "absl/base/internal/strerror.h"
  35. #include "absl/base/internal/sysinfo.h"
  36. #include "absl/base/log_severity.h"
  37. #include "absl/container/inlined_vector.h"
  38. #include "absl/debugging/internal/examine_stack.h"
  39. #include "absl/log/globals.h"
  40. #include "absl/log/internal/append_truncated.h"
  41. #include "absl/log/internal/globals.h"
  42. #include "absl/log/internal/log_format.h"
  43. #include "absl/log/internal/log_sink_set.h"
  44. #include "absl/log/internal/proto.h"
  45. #include "absl/log/log_entry.h"
  46. #include "absl/log/log_sink.h"
  47. #include "absl/log/log_sink_registry.h"
  48. #include "absl/memory/memory.h"
  49. #include "absl/strings/string_view.h"
  50. #include "absl/time/clock.h"
  51. #include "absl/time/time.h"
  52. #include "absl/types/span.h"
  53. extern "C" ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(
  54. AbslInternalOnFatalLogMessage)(const absl::LogEntry&) {
  55. // Default - Do nothing
  56. }
  57. namespace absl {
  58. ABSL_NAMESPACE_BEGIN
  59. namespace log_internal {
  60. namespace {
  61. // message `logging.proto.Event`
  62. enum EventTag : uint8_t {
  63. kFileName = 2,
  64. kFileLine = 3,
  65. kTimeNsecs = 4,
  66. kSeverity = 5,
  67. kThreadId = 6,
  68. kValue = 7,
  69. kSequenceNumber = 9,
  70. kThreadName = 10,
  71. };
  72. // message `logging.proto.Value`
  73. enum ValueTag : uint8_t {
  74. kString = 1,
  75. kStringLiteral = 6,
  76. };
  77. // Decodes a `logging.proto.Value` from `buf` and writes a string representation
  78. // into `dst`. The string representation will be truncated if `dst` is not
  79. // large enough to hold it. Returns false if `dst` has size zero or one (i.e.
  80. // sufficient only for a nul-terminator) and no decoded data could be written.
  81. // This function may or may not write a nul-terminator into `dst`, and it may or
  82. // may not truncate the data it writes in order to do make space for that nul
  83. // terminator. In any case, `dst` will be advanced to point at the byte where
  84. // subsequent writes should begin.
  85. bool PrintValue(absl::Span<char>& dst, absl::Span<const char> buf) {
  86. if (dst.size() <= 1) return false;
  87. ProtoField field;
  88. while (field.DecodeFrom(&buf)) {
  89. switch (field.tag()) {
  90. case ValueTag::kString:
  91. case ValueTag::kStringLiteral:
  92. if (field.type() == WireType::kLengthDelimited)
  93. if (log_internal::AppendTruncated(field.string_value(), dst) <
  94. field.string_value().size())
  95. return false;
  96. }
  97. }
  98. return true;
  99. }
  100. // See `logging.proto.Severity`
  101. int32_t ProtoSeverity(absl::LogSeverity severity, int verbose_level) {
  102. switch (severity) {
  103. case absl::LogSeverity::kInfo:
  104. if (verbose_level == absl::LogEntry::kNoVerbosityLevel) return 800;
  105. return 600 - verbose_level;
  106. case absl::LogSeverity::kWarning:
  107. return 900;
  108. case absl::LogSeverity::kError:
  109. return 950;
  110. case absl::LogSeverity::kFatal:
  111. return 1100;
  112. default:
  113. return 800;
  114. }
  115. }
  116. absl::string_view Basename(absl::string_view filepath) {
  117. #ifdef _WIN32
  118. size_t path = filepath.find_last_of("/\\");
  119. #else
  120. size_t path = filepath.find_last_of('/');
  121. #endif
  122. if (path != filepath.npos) filepath.remove_prefix(path + 1);
  123. return filepath;
  124. }
  125. void WriteToString(const char* data, void* str) {
  126. reinterpret_cast<std::string*>(str)->append(data);
  127. }
  128. void WriteToStream(const char* data, void* os) {
  129. auto* cast_os = static_cast<std::ostream*>(os);
  130. *cast_os << data;
  131. }
  132. } // namespace
  133. struct LogMessage::LogMessageData final {
  134. LogMessageData(const char* file, int line, absl::LogSeverity severity,
  135. absl::Time timestamp);
  136. LogMessageData(const LogMessageData&) = delete;
  137. LogMessageData& operator=(const LogMessageData&) = delete;
  138. // `LogEntry` sent to `LogSink`s; contains metadata.
  139. absl::LogEntry entry;
  140. // true => this was first fatal msg
  141. bool first_fatal;
  142. // true => all failures should be quiet
  143. bool fail_quietly;
  144. // true => PLOG was requested
  145. bool is_perror;
  146. // Extra `LogSink`s to log to, in addition to `global_sinks`.
  147. absl::InlinedVector<absl::LogSink*, 16> extra_sinks;
  148. // If true, log to `extra_sinks` but not to `global_sinks` or hardcoded
  149. // non-sink targets (e.g. stderr, log files).
  150. bool extra_sinks_only;
  151. std::ostream manipulated; // ostream with IO manipulators applied
  152. // A `logging.proto.Event` proto message is built into `encoded_buf`.
  153. std::array<char, kLogMessageBufferSize> encoded_buf;
  154. // `encoded_remaining()` is the suffix of `encoded_buf` that has not been
  155. // filled yet. If a datum to be encoded does not fit into
  156. // `encoded_remaining()` and cannot be truncated to fit, the size of
  157. // `encoded_remaining()` will be zeroed to prevent encoding of any further
  158. // data. Note that in this case its `data()` pointer will not point past the
  159. // end of `encoded_buf`.
  160. // The first use of `encoded_remaining()` is our chance to record metadata
  161. // after any modifications (e.g. by `AtLocation()`) but before any data have
  162. // been recorded. We want to record metadata before data so that data are
  163. // preferentially truncated if we run out of buffer.
  164. absl::Span<char>& encoded_remaining() {
  165. if (encoded_remaining_actual_do_not_use_directly.data() == nullptr) {
  166. encoded_remaining_actual_do_not_use_directly =
  167. absl::MakeSpan(encoded_buf);
  168. InitializeEncodingAndFormat();
  169. }
  170. return encoded_remaining_actual_do_not_use_directly;
  171. }
  172. absl::Span<char> encoded_remaining_actual_do_not_use_directly;
  173. // A formatted string message is built in `string_buf`.
  174. std::array<char, kLogMessageBufferSize> string_buf;
  175. void InitializeEncodingAndFormat();
  176. void FinalizeEncodingAndFormat();
  177. };
  178. LogMessage::LogMessageData::LogMessageData(const char* file, int line,
  179. absl::LogSeverity severity,
  180. absl::Time timestamp)
  181. : extra_sinks_only(false), manipulated(nullptr) {
  182. // Legacy defaults for LOG's ostream:
  183. manipulated.setf(std::ios_base::showbase | std::ios_base::boolalpha);
  184. entry.full_filename_ = file;
  185. entry.base_filename_ = Basename(file);
  186. entry.line_ = line;
  187. entry.prefix_ = absl::ShouldPrependLogPrefix();
  188. entry.severity_ = absl::NormalizeLogSeverity(severity);
  189. entry.verbose_level_ = absl::LogEntry::kNoVerbosityLevel;
  190. entry.timestamp_ = timestamp;
  191. entry.tid_ = absl::base_internal::GetCachedTID();
  192. }
  193. void LogMessage::LogMessageData::InitializeEncodingAndFormat() {
  194. EncodeStringTruncate(EventTag::kFileName, entry.source_filename(),
  195. &encoded_remaining());
  196. EncodeVarint(EventTag::kFileLine, entry.source_line(), &encoded_remaining());
  197. EncodeVarint(EventTag::kTimeNsecs, absl::ToUnixNanos(entry.timestamp()),
  198. &encoded_remaining());
  199. EncodeVarint(EventTag::kSeverity,
  200. ProtoSeverity(entry.log_severity(), entry.verbosity()),
  201. &encoded_remaining());
  202. EncodeVarint(EventTag::kThreadId, entry.tid(), &encoded_remaining());
  203. }
  204. void LogMessage::LogMessageData::FinalizeEncodingAndFormat() {
  205. // Note that `encoded_remaining()` may have zero size without pointing past
  206. // the end of `encoded_buf`, so the difference between `data()` pointers is
  207. // used to compute the size of `encoded_data`.
  208. absl::Span<const char> encoded_data(
  209. encoded_buf.data(),
  210. static_cast<size_t>(encoded_remaining().data() - encoded_buf.data()));
  211. // `string_remaining` is the suffix of `string_buf` that has not been filled
  212. // yet.
  213. absl::Span<char> string_remaining(string_buf);
  214. // We may need to write a newline and nul-terminator at the end of the decoded
  215. // string data. Rather than worry about whether those should overwrite the
  216. // end of the string (if the buffer is full) or be appended, we avoid writing
  217. // into the last two bytes so we always have space to append.
  218. string_remaining.remove_suffix(2);
  219. entry.prefix_len_ =
  220. entry.prefix() ? log_internal::FormatLogPrefix(
  221. entry.log_severity(), entry.timestamp(), entry.tid(),
  222. entry.source_basename(), entry.source_line(),
  223. log_internal::ThreadIsLoggingToLogSink()
  224. ? PrefixFormat::kRaw
  225. : PrefixFormat::kNotRaw,
  226. string_remaining)
  227. : 0;
  228. // Decode data from `encoded_buf` until we run out of data or we run out of
  229. // `string_remaining`.
  230. ProtoField field;
  231. while (field.DecodeFrom(&encoded_data)) {
  232. switch (field.tag()) {
  233. case EventTag::kValue:
  234. if (field.type() != WireType::kLengthDelimited) continue;
  235. if (PrintValue(string_remaining, field.bytes_value())) continue;
  236. break;
  237. }
  238. }
  239. auto chars_written =
  240. static_cast<size_t>(string_remaining.data() - string_buf.data());
  241. string_buf[chars_written++] = '\n';
  242. string_buf[chars_written++] = '\0';
  243. entry.text_message_with_prefix_and_newline_and_nul_ =
  244. absl::MakeSpan(string_buf).subspan(0, chars_written);
  245. }
  246. LogMessage::LogMessage(const char* file, int line, absl::LogSeverity severity)
  247. : data_(absl::make_unique<LogMessageData>(file, line, severity,
  248. absl::Now())) {
  249. data_->first_fatal = false;
  250. data_->is_perror = false;
  251. data_->fail_quietly = false;
  252. // This logs a backtrace even if the location is subsequently changed using
  253. // AtLocation. This quirk, and the behavior when AtLocation is called twice,
  254. // are fixable but probably not worth fixing.
  255. LogBacktraceIfNeeded();
  256. }
  257. LogMessage::LogMessage(const char* file, int line, InfoTag)
  258. : LogMessage(file, line, absl::LogSeverity::kInfo) {}
  259. LogMessage::LogMessage(const char* file, int line, WarningTag)
  260. : LogMessage(file, line, absl::LogSeverity::kWarning) {}
  261. LogMessage::LogMessage(const char* file, int line, ErrorTag)
  262. : LogMessage(file, line, absl::LogSeverity::kError) {}
  263. LogMessage::~LogMessage() {
  264. #ifdef ABSL_MIN_LOG_LEVEL
  265. if (data_->entry.log_severity() <
  266. static_cast<absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) &&
  267. data_->entry.log_severity() < absl::LogSeverity::kFatal) {
  268. return;
  269. }
  270. #endif
  271. Flush();
  272. }
  273. LogMessage& LogMessage::AtLocation(absl::string_view file, int line) {
  274. data_->entry.full_filename_ = file;
  275. data_->entry.base_filename_ = Basename(file);
  276. data_->entry.line_ = line;
  277. LogBacktraceIfNeeded();
  278. return *this;
  279. }
  280. LogMessage& LogMessage::NoPrefix() {
  281. data_->entry.prefix_ = false;
  282. return *this;
  283. }
  284. LogMessage& LogMessage::WithVerbosity(int verbose_level) {
  285. if (verbose_level == absl::LogEntry::kNoVerbosityLevel) {
  286. data_->entry.verbose_level_ = absl::LogEntry::kNoVerbosityLevel;
  287. } else {
  288. data_->entry.verbose_level_ = std::max(0, verbose_level);
  289. }
  290. return *this;
  291. }
  292. LogMessage& LogMessage::WithTimestamp(absl::Time timestamp) {
  293. data_->entry.timestamp_ = timestamp;
  294. return *this;
  295. }
  296. LogMessage& LogMessage::WithThreadID(absl::LogEntry::tid_t tid) {
  297. data_->entry.tid_ = tid;
  298. return *this;
  299. }
  300. LogMessage& LogMessage::WithMetadataFrom(const absl::LogEntry& entry) {
  301. data_->entry.full_filename_ = entry.full_filename_;
  302. data_->entry.base_filename_ = entry.base_filename_;
  303. data_->entry.line_ = entry.line_;
  304. data_->entry.prefix_ = entry.prefix_;
  305. data_->entry.severity_ = entry.severity_;
  306. data_->entry.verbose_level_ = entry.verbose_level_;
  307. data_->entry.timestamp_ = entry.timestamp_;
  308. data_->entry.tid_ = entry.tid_;
  309. return *this;
  310. }
  311. LogMessage& LogMessage::WithPerror() {
  312. data_->is_perror = true;
  313. return *this;
  314. }
  315. LogMessage& LogMessage::ToSinkAlso(absl::LogSink* sink) {
  316. ABSL_INTERNAL_CHECK(sink, "null LogSink*");
  317. data_->extra_sinks.push_back(sink);
  318. return *this;
  319. }
  320. LogMessage& LogMessage::ToSinkOnly(absl::LogSink* sink) {
  321. ABSL_INTERNAL_CHECK(sink, "null LogSink*");
  322. data_->extra_sinks.clear();
  323. data_->extra_sinks.push_back(sink);
  324. data_->extra_sinks_only = true;
  325. return *this;
  326. }
  327. #ifdef __ELF__
  328. extern "C" void __gcov_dump() ABSL_ATTRIBUTE_WEAK;
  329. extern "C" void __gcov_flush() ABSL_ATTRIBUTE_WEAK;
  330. #endif
  331. void LogMessage::FailWithoutStackTrace() {
  332. // Now suppress repeated trace logging:
  333. log_internal::SetSuppressSigabortTrace(true);
  334. #if defined _DEBUG && defined COMPILER_MSVC
  335. // When debugging on windows, avoid the obnoxious dialog.
  336. __debugbreak();
  337. #endif
  338. #ifdef __ELF__
  339. // For b/8737634, flush coverage if we are in coverage mode.
  340. if (&__gcov_dump != nullptr) {
  341. __gcov_dump();
  342. } else if (&__gcov_flush != nullptr) {
  343. __gcov_flush();
  344. }
  345. #endif
  346. abort();
  347. }
  348. void LogMessage::FailQuietly() {
  349. // _exit. Calling abort() would trigger all sorts of death signal handlers
  350. // and a detailed stack trace. Calling exit() would trigger the onexit
  351. // handlers, including the heap-leak checker, which is guaranteed to fail in
  352. // this case: we probably just new'ed the std::string that we logged.
  353. // Anyway, if you're calling Fail or FailQuietly, you're trying to bail out
  354. // of the program quickly, and it doesn't make much sense for FailQuietly to
  355. // offer different guarantees about exit behavior than Fail does. (And as a
  356. // consequence for QCHECK and CHECK to offer different exit behaviors)
  357. _exit(1);
  358. }
  359. LogMessage& LogMessage::operator<<(const std::string& v) {
  360. CopyToEncodedBuffer<StringType::kNotLiteral>(v);
  361. return *this;
  362. }
  363. LogMessage& LogMessage::operator<<(absl::string_view v) {
  364. CopyToEncodedBuffer<StringType::kNotLiteral>(v);
  365. return *this;
  366. }
  367. LogMessage& LogMessage::operator<<(std::ostream& (*m)(std::ostream& os)) {
  368. OstreamView view(*data_);
  369. data_->manipulated << m;
  370. return *this;
  371. }
  372. LogMessage& LogMessage::operator<<(std::ios_base& (*m)(std::ios_base& os)) {
  373. OstreamView view(*data_);
  374. data_->manipulated << m;
  375. return *this;
  376. }
  377. template LogMessage& LogMessage::operator<<(const char& v);
  378. template LogMessage& LogMessage::operator<<(const signed char& v);
  379. template LogMessage& LogMessage::operator<<(const unsigned char& v);
  380. template LogMessage& LogMessage::operator<<(const short& v); // NOLINT
  381. template LogMessage& LogMessage::operator<<(const unsigned short& v); // NOLINT
  382. template LogMessage& LogMessage::operator<<(const int& v);
  383. template LogMessage& LogMessage::operator<<(const unsigned int& v);
  384. template LogMessage& LogMessage::operator<<(const long& v); // NOLINT
  385. template LogMessage& LogMessage::operator<<(const unsigned long& v); // NOLINT
  386. template LogMessage& LogMessage::operator<<(const long long& v); // NOLINT
  387. template LogMessage& LogMessage::operator<<(
  388. const unsigned long long& v); // NOLINT
  389. template LogMessage& LogMessage::operator<<(void* const& v);
  390. template LogMessage& LogMessage::operator<<(const void* const& v);
  391. template LogMessage& LogMessage::operator<<(const float& v);
  392. template LogMessage& LogMessage::operator<<(const double& v);
  393. template LogMessage& LogMessage::operator<<(const bool& v);
  394. void LogMessage::Flush() {
  395. if (data_->entry.log_severity() < absl::MinLogLevel()) return;
  396. if (data_->is_perror) {
  397. InternalStream() << ": " << absl::base_internal::StrError(errno_saver_())
  398. << " [" << errno_saver_() << "]";
  399. }
  400. // Have we already seen a fatal message?
  401. ABSL_CONST_INIT static std::atomic<bool> seen_fatal(false);
  402. if (data_->entry.log_severity() == absl::LogSeverity::kFatal &&
  403. absl::log_internal::ExitOnDFatal()) {
  404. // Exactly one LOG(FATAL) message is responsible for aborting the process,
  405. // even if multiple threads LOG(FATAL) concurrently.
  406. bool expected_seen_fatal = false;
  407. if (seen_fatal.compare_exchange_strong(expected_seen_fatal, true,
  408. std::memory_order_relaxed)) {
  409. data_->first_fatal = true;
  410. }
  411. }
  412. data_->FinalizeEncodingAndFormat();
  413. data_->entry.encoding_ =
  414. absl::string_view(data_->encoded_buf.data(),
  415. static_cast<size_t>(data_->encoded_remaining().data() -
  416. data_->encoded_buf.data()));
  417. SendToLog();
  418. }
  419. void LogMessage::SetFailQuietly() { data_->fail_quietly = true; }
  420. LogMessage::OstreamView::OstreamView(LogMessageData& message_data)
  421. : data_(message_data), encoded_remaining_copy_(data_.encoded_remaining()) {
  422. // This constructor sets the `streambuf` up so that streaming into an attached
  423. // ostream encodes string data in-place. To do that, we write appropriate
  424. // headers into the buffer using a copy of the buffer view so that we can
  425. // decide not to keep them later if nothing is ever streamed in. We don't
  426. // know how much data we'll get, but we can use the size of the remaining
  427. // buffer as an upper bound and fill in the right size once we know it.
  428. message_start_ =
  429. EncodeMessageStart(EventTag::kValue, encoded_remaining_copy_.size(),
  430. &encoded_remaining_copy_);
  431. string_start_ =
  432. EncodeMessageStart(ValueTag::kString, encoded_remaining_copy_.size(),
  433. &encoded_remaining_copy_);
  434. setp(encoded_remaining_copy_.data(),
  435. encoded_remaining_copy_.data() + encoded_remaining_copy_.size());
  436. data_.manipulated.rdbuf(this);
  437. }
  438. LogMessage::OstreamView::~OstreamView() {
  439. data_.manipulated.rdbuf(nullptr);
  440. if (!string_start_.data()) {
  441. // The second field header didn't fit. Whether the first one did or not, we
  442. // shouldn't commit `encoded_remaining_copy_`, and we also need to zero the
  443. // size of `data_->encoded_remaining()` so that no more data are encoded.
  444. data_.encoded_remaining().remove_suffix(data_.encoded_remaining().size());
  445. return;
  446. }
  447. const absl::Span<const char> contents(pbase(),
  448. static_cast<size_t>(pptr() - pbase()));
  449. if (contents.empty()) return;
  450. encoded_remaining_copy_.remove_prefix(contents.size());
  451. EncodeMessageLength(string_start_, &encoded_remaining_copy_);
  452. EncodeMessageLength(message_start_, &encoded_remaining_copy_);
  453. data_.encoded_remaining() = encoded_remaining_copy_;
  454. }
  455. std::ostream& LogMessage::OstreamView::stream() { return data_.manipulated; }
  456. bool LogMessage::IsFatal() const {
  457. return data_->entry.log_severity() == absl::LogSeverity::kFatal &&
  458. absl::log_internal::ExitOnDFatal();
  459. }
  460. void LogMessage::PrepareToDie() {
  461. // If we log a FATAL message, flush all the log destinations, then toss
  462. // a signal for others to catch. We leave the logs in a state that
  463. // someone else can use them (as long as they flush afterwards)
  464. if (data_->first_fatal) {
  465. // Notify observers about the upcoming fatal error.
  466. ABSL_INTERNAL_C_SYMBOL(AbslInternalOnFatalLogMessage)(data_->entry);
  467. }
  468. if (!data_->fail_quietly) {
  469. // Log the message first before we start collecting stack trace.
  470. log_internal::LogToSinks(data_->entry, absl::MakeSpan(data_->extra_sinks),
  471. data_->extra_sinks_only);
  472. // `DumpStackTrace` generates an empty string under MSVC.
  473. // Adding the constant prefix here simplifies testing.
  474. data_->entry.stacktrace_ = "*** Check failure stack trace: ***\n";
  475. debugging_internal::DumpStackTrace(
  476. 0, log_internal::MaxFramesInLogStackTrace(),
  477. log_internal::ShouldSymbolizeLogStackTrace(), WriteToString,
  478. &data_->entry.stacktrace_);
  479. }
  480. }
  481. void LogMessage::Die() {
  482. absl::FlushLogSinks();
  483. if (data_->fail_quietly) {
  484. FailQuietly();
  485. } else {
  486. FailWithoutStackTrace();
  487. }
  488. }
  489. void LogMessage::SendToLog() {
  490. if (IsFatal()) PrepareToDie();
  491. // Also log to all registered sinks, even if OnlyLogToStderr() is set.
  492. log_internal::LogToSinks(data_->entry, absl::MakeSpan(data_->extra_sinks),
  493. data_->extra_sinks_only);
  494. if (IsFatal()) Die();
  495. }
  496. void LogMessage::LogBacktraceIfNeeded() {
  497. if (!absl::log_internal::IsInitialized()) return;
  498. if (!absl::log_internal::ShouldLogBacktraceAt(data_->entry.source_basename(),
  499. data_->entry.source_line()))
  500. return;
  501. OstreamView view(*data_);
  502. view.stream() << " (stacktrace:\n";
  503. debugging_internal::DumpStackTrace(
  504. 1, log_internal::MaxFramesInLogStackTrace(),
  505. log_internal::ShouldSymbolizeLogStackTrace(), WriteToStream,
  506. &view.stream());
  507. view.stream() << ") ";
  508. }
  509. // Encodes into `data_->encoded_remaining()` a partial `logging.proto.Event`
  510. // containing the specified string data using a `Value` field appropriate to
  511. // `str_type`. Truncates `str` if necessary, but emits nothing and marks the
  512. // buffer full if even the field headers do not fit.
  513. template <LogMessage::StringType str_type>
  514. void LogMessage::CopyToEncodedBuffer(absl::string_view str) {
  515. auto encoded_remaining_copy = data_->encoded_remaining();
  516. auto start = EncodeMessageStart(
  517. EventTag::kValue, BufferSizeFor(WireType::kLengthDelimited) + str.size(),
  518. &encoded_remaining_copy);
  519. // If the `logging.proto.Event.value` field header did not fit,
  520. // `EncodeMessageStart` will have zeroed `encoded_remaining_copy`'s size and
  521. // `EncodeStringTruncate` will fail too.
  522. if (EncodeStringTruncate(str_type == StringType::kLiteral
  523. ? ValueTag::kStringLiteral
  524. : ValueTag::kString,
  525. str, &encoded_remaining_copy)) {
  526. // The string may have been truncated, but the field header fit.
  527. EncodeMessageLength(start, &encoded_remaining_copy);
  528. data_->encoded_remaining() = encoded_remaining_copy;
  529. } else {
  530. // The field header(s) did not fit; zero `encoded_remaining()` so we don't
  531. // write anything else later.
  532. data_->encoded_remaining().remove_suffix(data_->encoded_remaining().size());
  533. }
  534. }
  535. template void LogMessage::CopyToEncodedBuffer<LogMessage::StringType::kLiteral>(
  536. absl::string_view str);
  537. template void LogMessage::CopyToEncodedBuffer<
  538. LogMessage::StringType::kNotLiteral>(absl::string_view str);
  539. template <LogMessage::StringType str_type>
  540. void LogMessage::CopyToEncodedBuffer(char ch, size_t num) {
  541. auto encoded_remaining_copy = data_->encoded_remaining();
  542. auto value_start = EncodeMessageStart(
  543. EventTag::kValue, BufferSizeFor(WireType::kLengthDelimited) + num,
  544. &encoded_remaining_copy);
  545. auto str_start = EncodeMessageStart(str_type == StringType::kLiteral
  546. ? ValueTag::kStringLiteral
  547. : ValueTag::kString,
  548. num, &encoded_remaining_copy);
  549. if (str_start.data()) {
  550. // The field headers fit.
  551. log_internal::AppendTruncated(ch, num, encoded_remaining_copy);
  552. EncodeMessageLength(str_start, &encoded_remaining_copy);
  553. EncodeMessageLength(value_start, &encoded_remaining_copy);
  554. data_->encoded_remaining() = encoded_remaining_copy;
  555. } else {
  556. // The field header(s) did not fit; zero `encoded_remaining()` so we don't
  557. // write anything else later.
  558. data_->encoded_remaining().remove_suffix(data_->encoded_remaining().size());
  559. }
  560. }
  561. template void LogMessage::CopyToEncodedBuffer<LogMessage::StringType::kLiteral>(
  562. char ch, size_t num);
  563. template void LogMessage::CopyToEncodedBuffer<
  564. LogMessage::StringType::kNotLiteral>(char ch, size_t num);
  565. // We intentionally don't return from these destructors. Disable MSVC's warning
  566. // about the destructor never returning as we do so intentionally here.
  567. #if defined(_MSC_VER) && !defined(__clang__)
  568. #pragma warning(push)
  569. #pragma warning(disable : 4722)
  570. #endif
  571. LogMessageFatal::LogMessageFatal(const char* file, int line)
  572. : LogMessage(file, line, absl::LogSeverity::kFatal) {}
  573. LogMessageFatal::LogMessageFatal(const char* file, int line,
  574. absl::string_view failure_msg)
  575. : LogMessage(file, line, absl::LogSeverity::kFatal) {
  576. *this << "Check failed: " << failure_msg << " ";
  577. }
  578. LogMessageFatal::~LogMessageFatal() {
  579. Flush();
  580. FailWithoutStackTrace();
  581. }
  582. LogMessageDebugFatal::LogMessageDebugFatal(const char* file, int line)
  583. : LogMessage(file, line, absl::LogSeverity::kFatal) {}
  584. LogMessageDebugFatal::~LogMessageDebugFatal() {
  585. Flush();
  586. FailWithoutStackTrace();
  587. }
  588. LogMessageQuietlyDebugFatal::LogMessageQuietlyDebugFatal(const char* file,
  589. int line)
  590. : LogMessage(file, line, absl::LogSeverity::kFatal) {
  591. SetFailQuietly();
  592. }
  593. LogMessageQuietlyDebugFatal::~LogMessageQuietlyDebugFatal() {
  594. Flush();
  595. FailQuietly();
  596. }
  597. LogMessageQuietlyFatal::LogMessageQuietlyFatal(const char* file, int line)
  598. : LogMessage(file, line, absl::LogSeverity::kFatal) {
  599. SetFailQuietly();
  600. }
  601. LogMessageQuietlyFatal::LogMessageQuietlyFatal(const char* file, int line,
  602. absl::string_view failure_msg)
  603. : LogMessageQuietlyFatal(file, line) {
  604. *this << "Check failed: " << failure_msg << " ";
  605. }
  606. LogMessageQuietlyFatal::~LogMessageQuietlyFatal() {
  607. Flush();
  608. FailQuietly();
  609. }
  610. #if defined(_MSC_VER) && !defined(__clang__)
  611. #pragma warning(pop)
  612. #endif
  613. } // namespace log_internal
  614. ABSL_NAMESPACE_END
  615. } // namespace absl