raw_logging.h 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // Thread-safe logging routines that do not allocate any memory or
  16. // acquire any locks, and can therefore be used by low-level memory
  17. // allocation, synchronization, and signal-handling code.
  18. #ifndef ABSL_BASE_INTERNAL_RAW_LOGGING_H_
  19. #define ABSL_BASE_INTERNAL_RAW_LOGGING_H_
  20. #include <string>
  21. #include "absl/base/attributes.h"
  22. #include "absl/base/config.h"
  23. #include "absl/base/internal/atomic_hook.h"
  24. #include "absl/base/log_severity.h"
  25. #include "absl/base/macros.h"
  26. #include "absl/base/optimization.h"
  27. #include "absl/base/port.h"
  28. // This is similar to LOG(severity) << format..., but
  29. // * it is to be used ONLY by low-level modules that can't use normal LOG()
  30. // * it is designed to be a low-level logger that does not allocate any
  31. // memory and does not need any locks, hence:
  32. // * it logs straight and ONLY to STDERR w/o buffering
  33. // * it uses an explicit printf-format and arguments list
  34. // * it will silently chop off really long message strings
  35. // Usage example:
  36. // ABSL_RAW_LOG(ERROR, "Failed foo with %i: %s", status, error);
  37. // This will print an almost standard log line like this to stderr only:
  38. // E0821 211317 file.cc:123] RAW: Failed foo with 22: bad_file
  39. #define ABSL_RAW_LOG(severity, ...) \
  40. do { \
  41. constexpr const char* absl_raw_log_internal_basename = \
  42. ::absl::raw_log_internal::Basename(__FILE__, sizeof(__FILE__) - 1); \
  43. ::absl::raw_log_internal::RawLog(ABSL_RAW_LOG_INTERNAL_##severity, \
  44. absl_raw_log_internal_basename, __LINE__, \
  45. __VA_ARGS__); \
  46. } while (0)
  47. // Similar to CHECK(condition) << message, but for low-level modules:
  48. // we use only ABSL_RAW_LOG that does not allocate memory.
  49. // We do not want to provide args list here to encourage this usage:
  50. // if (!cond) ABSL_RAW_LOG(FATAL, "foo ...", hard_to_compute_args);
  51. // so that the args are not computed when not needed.
  52. #define ABSL_RAW_CHECK(condition, message) \
  53. do { \
  54. if (ABSL_PREDICT_FALSE(!(condition))) { \
  55. ABSL_RAW_LOG(FATAL, "Check %s failed: %s", #condition, message); \
  56. } \
  57. } while (0)
  58. // ABSL_INTERNAL_LOG and ABSL_INTERNAL_CHECK work like the RAW variants above,
  59. // except that if the richer log library is linked into the binary, we dispatch
  60. // to that instead. This is potentially useful for internal logging and
  61. // assertions, where we are using RAW_LOG neither for its async-signal-safety
  62. // nor for its non-allocating nature, but rather because raw logging has very
  63. // few other dependencies.
  64. //
  65. // The API is a subset of the above: each macro only takes two arguments. Use
  66. // StrCat if you need to build a richer message.
  67. #define ABSL_INTERNAL_LOG(severity, message) \
  68. do { \
  69. constexpr const char* absl_raw_log_internal_filename = __FILE__; \
  70. ::absl::raw_log_internal::internal_log_function( \
  71. ABSL_RAW_LOG_INTERNAL_##severity, absl_raw_log_internal_filename, \
  72. __LINE__, message); \
  73. if (ABSL_RAW_LOG_INTERNAL_##severity == ::absl::LogSeverity::kFatal) \
  74. ABSL_UNREACHABLE(); \
  75. } while (0)
  76. #define ABSL_INTERNAL_CHECK(condition, message) \
  77. do { \
  78. if (ABSL_PREDICT_FALSE(!(condition))) { \
  79. std::string death_message = "Check " #condition " failed: "; \
  80. death_message += std::string(message); \
  81. ABSL_INTERNAL_LOG(FATAL, death_message); \
  82. } \
  83. } while (0)
  84. #define ABSL_RAW_LOG_INTERNAL_INFO ::absl::LogSeverity::kInfo
  85. #define ABSL_RAW_LOG_INTERNAL_WARNING ::absl::LogSeverity::kWarning
  86. #define ABSL_RAW_LOG_INTERNAL_ERROR ::absl::LogSeverity::kError
  87. #define ABSL_RAW_LOG_INTERNAL_FATAL ::absl::LogSeverity::kFatal
  88. #define ABSL_RAW_LOG_INTERNAL_LEVEL(severity) \
  89. ::absl::NormalizeLogSeverity(severity)
  90. namespace absl {
  91. ABSL_NAMESPACE_BEGIN
  92. namespace raw_log_internal {
  93. // Helper function to implement ABSL_RAW_LOG
  94. // Logs format... at "severity" level, reporting it
  95. // as called from file:line.
  96. // This does not allocate memory or acquire locks.
  97. void RawLog(absl::LogSeverity severity, const char* file, int line,
  98. const char* format, ...) ABSL_PRINTF_ATTRIBUTE(4, 5);
  99. // Writes the provided buffer directly to stderr, in a signal-safe, low-level
  100. // manner.
  101. void AsyncSignalSafeWriteToStderr(const char* s, size_t len);
  102. // compile-time function to get the "base" filename, that is, the part of
  103. // a filename after the last "/" or "\" path separator. The search starts at
  104. // the end of the string; the second parameter is the length of the string.
  105. constexpr const char* Basename(const char* fname, int offset) {
  106. return offset == 0 || fname[offset - 1] == '/' || fname[offset - 1] == '\\'
  107. ? fname + offset
  108. : Basename(fname, offset - 1);
  109. }
  110. // For testing only.
  111. // Returns true if raw logging is fully supported. When it is not
  112. // fully supported, no messages will be emitted, but a log at FATAL
  113. // severity will cause an abort.
  114. //
  115. // TODO(gfalcon): Come up with a better name for this method.
  116. bool RawLoggingFullySupported();
  117. // Function type for a raw_log customization hook for suppressing messages
  118. // by severity, and for writing custom prefixes on non-suppressed messages.
  119. //
  120. // The installed hook is called for every raw log invocation. The message will
  121. // be logged to stderr only if the hook returns true. FATAL errors will cause
  122. // the process to abort, even if writing to stderr is suppressed. The hook is
  123. // also provided with an output buffer, where it can write a custom log message
  124. // prefix.
  125. //
  126. // The raw_log system does not allocate memory or grab locks. User-provided
  127. // hooks must avoid these operations, and must not throw exceptions.
  128. //
  129. // 'severity' is the severity level of the message being written.
  130. // 'file' and 'line' are the file and line number where the ABSL_RAW_LOG macro
  131. // was located.
  132. // 'buf' and 'buf_size' are pointers to the buffer and buffer size. If the
  133. // hook writes a prefix, it must increment *buf and decrement *buf_size
  134. // accordingly.
  135. using LogFilterAndPrefixHook = bool (*)(absl::LogSeverity severity,
  136. const char* file, int line, char** buf,
  137. int* buf_size);
  138. // Function type for a raw_log customization hook called to abort a process
  139. // when a FATAL message is logged. If the provided AbortHook() returns, the
  140. // logging system will call abort().
  141. //
  142. // 'file' and 'line' are the file and line number where the ABSL_RAW_LOG macro
  143. // was located.
  144. // The NUL-terminated logged message lives in the buffer between 'buf_start'
  145. // and 'buf_end'. 'prefix_end' points to the first non-prefix character of the
  146. // buffer (as written by the LogFilterAndPrefixHook.)
  147. //
  148. // The lifetime of the filename and message buffers will not end while the
  149. // process remains alive.
  150. using AbortHook = void (*)(const char* file, int line, const char* buf_start,
  151. const char* prefix_end, const char* buf_end);
  152. // Internal logging function for ABSL_INTERNAL_LOG to dispatch to.
  153. //
  154. // TODO(gfalcon): When string_view no longer depends on base, change this
  155. // interface to take its message as a string_view instead.
  156. using InternalLogFunction = void (*)(absl::LogSeverity severity,
  157. const char* file, int line,
  158. const std::string& message);
  159. ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL extern base_internal::AtomicHook<
  160. InternalLogFunction>
  161. internal_log_function;
  162. // Registers hooks of the above types. Only a single hook of each type may be
  163. // registered. It is an error to call these functions multiple times with
  164. // different input arguments.
  165. //
  166. // These functions are safe to call at any point during initialization; they do
  167. // not block or malloc, and are async-signal safe.
  168. void RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func);
  169. void RegisterAbortHook(AbortHook func);
  170. void RegisterInternalLogFunction(InternalLogFunction func);
  171. } // namespace raw_log_internal
  172. ABSL_NAMESPACE_END
  173. } // namespace absl
  174. #endif // ABSL_BASE_INTERNAL_RAW_LOGGING_H_