raw_logging.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_##severity; \
  47. } while (0)
  48. // Similar to CHECK(condition) << message, but for low-level modules:
  49. // we use only ABSL_RAW_LOG that does not allocate memory.
  50. // We do not want to provide args list here to encourage this usage:
  51. // if (!cond) ABSL_RAW_LOG(FATAL, "foo ...", hard_to_compute_args);
  52. // so that the args are not computed when not needed.
  53. #define ABSL_RAW_CHECK(condition, message) \
  54. do { \
  55. if (ABSL_PREDICT_FALSE(!(condition))) { \
  56. ABSL_RAW_LOG(FATAL, "Check %s failed: %s", #condition, message); \
  57. } \
  58. } while (0)
  59. // ABSL_INTERNAL_LOG and ABSL_INTERNAL_CHECK work like the RAW variants above,
  60. // except that if the richer log library is linked into the binary, we dispatch
  61. // to that instead. This is potentially useful for internal logging and
  62. // assertions, where we are using RAW_LOG neither for its async-signal-safety
  63. // nor for its non-allocating nature, but rather because raw logging has very
  64. // few other dependencies.
  65. //
  66. // The API is a subset of the above: each macro only takes two arguments. Use
  67. // StrCat if you need to build a richer message.
  68. #define ABSL_INTERNAL_LOG(severity, message) \
  69. do { \
  70. constexpr const char* absl_raw_log_internal_filename = __FILE__; \
  71. ::absl::raw_log_internal::internal_log_function( \
  72. ABSL_RAW_LOG_INTERNAL_##severity, absl_raw_log_internal_filename, \
  73. __LINE__, message); \
  74. ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_##severity; \
  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. #ifndef NDEBUG
  85. #define ABSL_RAW_DLOG(severity, ...) ABSL_RAW_LOG(severity, __VA_ARGS__)
  86. #define ABSL_RAW_DCHECK(condition, message) ABSL_RAW_CHECK(condition, message)
  87. #else // NDEBUG
  88. #define ABSL_RAW_DLOG(severity, ...) \
  89. while (false) ABSL_RAW_LOG(severity, __VA_ARGS__)
  90. #define ABSL_RAW_DCHECK(condition, message) \
  91. while (false) ABSL_RAW_CHECK(condition, message)
  92. #endif // NDEBUG
  93. #define ABSL_RAW_LOG_INTERNAL_INFO ::absl::LogSeverity::kInfo
  94. #define ABSL_RAW_LOG_INTERNAL_WARNING ::absl::LogSeverity::kWarning
  95. #define ABSL_RAW_LOG_INTERNAL_ERROR ::absl::LogSeverity::kError
  96. #define ABSL_RAW_LOG_INTERNAL_FATAL ::absl::LogSeverity::kFatal
  97. #define ABSL_RAW_LOG_INTERNAL_DFATAL ::absl::kLogDebugFatal
  98. #define ABSL_RAW_LOG_INTERNAL_LEVEL(severity) \
  99. ::absl::NormalizeLogSeverity(severity)
  100. #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_INFO
  101. #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_WARNING
  102. #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_ERROR
  103. #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_FATAL ABSL_UNREACHABLE()
  104. #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_DFATAL
  105. #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_LEVEL(severity)
  106. namespace absl {
  107. ABSL_NAMESPACE_BEGIN
  108. namespace raw_log_internal {
  109. // Helper function to implement ABSL_RAW_LOG
  110. // Logs format... at "severity" level, reporting it
  111. // as called from file:line.
  112. // This does not allocate memory or acquire locks.
  113. void RawLog(absl::LogSeverity severity, const char* file, int line,
  114. const char* format, ...) ABSL_PRINTF_ATTRIBUTE(4, 5);
  115. // Writes the provided buffer directly to stderr, in a signal-safe, low-level
  116. // manner. Preserves errno.
  117. void AsyncSignalSafeWriteError(const char* s, size_t len);
  118. // compile-time function to get the "base" filename, that is, the part of
  119. // a filename after the last "/" or "\" path separator. The search starts at
  120. // the end of the string; the second parameter is the length of the string.
  121. constexpr const char* Basename(const char* fname, int offset) {
  122. return offset == 0 || fname[offset - 1] == '/' || fname[offset - 1] == '\\'
  123. ? fname + offset
  124. : Basename(fname, offset - 1);
  125. }
  126. // For testing only.
  127. // Returns true if raw logging is fully supported. When it is not
  128. // fully supported, no messages will be emitted, but a log at FATAL
  129. // severity will cause an abort.
  130. //
  131. // TODO(gfalcon): Come up with a better name for this method.
  132. bool RawLoggingFullySupported();
  133. // Function type for a raw_log customization hook for suppressing messages
  134. // by severity, and for writing custom prefixes on non-suppressed messages.
  135. //
  136. // The installed hook is called for every raw log invocation. The message will
  137. // be logged to stderr only if the hook returns true. FATAL errors will cause
  138. // the process to abort, even if writing to stderr is suppressed. The hook is
  139. // also provided with an output buffer, where it can write a custom log message
  140. // prefix.
  141. //
  142. // The raw_log system does not allocate memory or grab locks. User-provided
  143. // hooks must avoid these operations, and must not throw exceptions.
  144. //
  145. // 'severity' is the severity level of the message being written.
  146. // 'file' and 'line' are the file and line number where the ABSL_RAW_LOG macro
  147. // was located.
  148. // 'buf' and 'buf_size' are pointers to the buffer and buffer size. If the
  149. // hook writes a prefix, it must increment *buf and decrement *buf_size
  150. // accordingly.
  151. using LogFilterAndPrefixHook = bool (*)(absl::LogSeverity severity,
  152. const char* file, int line, char** buf,
  153. int* buf_size);
  154. // Function type for a raw_log customization hook called to abort a process
  155. // when a FATAL message is logged. If the provided AbortHook() returns, the
  156. // logging system will call abort().
  157. //
  158. // 'file' and 'line' are the file and line number where the ABSL_RAW_LOG macro
  159. // was located.
  160. // The NUL-terminated logged message lives in the buffer between 'buf_start'
  161. // and 'buf_end'. 'prefix_end' points to the first non-prefix character of the
  162. // buffer (as written by the LogFilterAndPrefixHook.)
  163. //
  164. // The lifetime of the filename and message buffers will not end while the
  165. // process remains alive.
  166. using AbortHook = void (*)(const char* file, int line, const char* buf_start,
  167. const char* prefix_end, const char* buf_end);
  168. // Internal logging function for ABSL_INTERNAL_LOG to dispatch to.
  169. //
  170. // TODO(gfalcon): When string_view no longer depends on base, change this
  171. // interface to take its message as a string_view instead.
  172. using InternalLogFunction = void (*)(absl::LogSeverity severity,
  173. const char* file, int line,
  174. const std::string& message);
  175. ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL extern base_internal::AtomicHook<
  176. InternalLogFunction>
  177. internal_log_function;
  178. // Registers hooks of the above types. Only a single hook of each type may be
  179. // registered. It is an error to call these functions multiple times with
  180. // different input arguments.
  181. //
  182. // These functions are safe to call at any point during initialization; they do
  183. // not block or malloc, and are async-signal safe.
  184. void RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func);
  185. void RegisterAbortHook(AbortHook func);
  186. void RegisterInternalLogFunction(InternalLogFunction func);
  187. } // namespace raw_log_internal
  188. ABSL_NAMESPACE_END
  189. } // namespace absl
  190. #endif // ABSL_BASE_INTERNAL_RAW_LOGGING_H_