raw_logging.h 9.3 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_logging_internal_basename = \
  42. ::absl::raw_logging_internal::Basename(__FILE__, \
  43. sizeof(__FILE__) - 1); \
  44. ::absl::raw_logging_internal::RawLog(ABSL_RAW_LOGGING_INTERNAL_##severity, \
  45. absl_raw_logging_internal_basename, \
  46. __LINE__, __VA_ARGS__); \
  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_logging_internal_filename = __FILE__; \
  71. ::absl::raw_logging_internal::internal_log_function( \
  72. ABSL_RAW_LOGGING_INTERNAL_##severity, \
  73. absl_raw_logging_internal_filename, __LINE__, message); \
  74. if (ABSL_RAW_LOGGING_INTERNAL_##severity == ::absl::LogSeverity::kFatal) \
  75. ABSL_INTERNAL_UNREACHABLE; \
  76. } while (0)
  77. #define ABSL_INTERNAL_CHECK(condition, message) \
  78. do { \
  79. if (ABSL_PREDICT_FALSE(!(condition))) { \
  80. std::string death_message = "Check " #condition " failed: "; \
  81. death_message += std::string(message); \
  82. ABSL_INTERNAL_LOG(FATAL, death_message); \
  83. } \
  84. } while (0)
  85. #define ABSL_RAW_LOGGING_INTERNAL_INFO ::absl::LogSeverity::kInfo
  86. #define ABSL_RAW_LOGGING_INTERNAL_WARNING ::absl::LogSeverity::kWarning
  87. #define ABSL_RAW_LOGGING_INTERNAL_ERROR ::absl::LogSeverity::kError
  88. #define ABSL_RAW_LOGGING_INTERNAL_FATAL ::absl::LogSeverity::kFatal
  89. #define ABSL_RAW_LOGGING_INTERNAL_LEVEL(severity) \
  90. ::absl::NormalizeLogSeverity(severity)
  91. namespace absl {
  92. ABSL_NAMESPACE_BEGIN
  93. namespace raw_logging_internal {
  94. // Helper function to implement ABSL_RAW_LOG
  95. // Logs format... at "severity" level, reporting it
  96. // as called from file:line.
  97. // This does not allocate memory or acquire locks.
  98. void RawLog(absl::LogSeverity severity, const char* file, int line,
  99. const char* format, ...) ABSL_PRINTF_ATTRIBUTE(4, 5);
  100. // Writes the provided buffer directly to stderr, in a safe, low-level manner.
  101. //
  102. // In POSIX this means calling write(), which is async-signal safe and does
  103. // not malloc. If the platform supports the SYS_write syscall, we invoke that
  104. // directly to side-step any libc interception.
  105. void SafeWriteToStderr(const char *s, size_t len);
  106. // compile-time function to get the "base" filename, that is, the part of
  107. // a filename after the last "/" or "\" path separator. The search starts at
  108. // the end of the string; the second parameter is the length of the string.
  109. constexpr const char* Basename(const char* fname, int offset) {
  110. return offset == 0 || fname[offset - 1] == '/' || fname[offset - 1] == '\\'
  111. ? fname + offset
  112. : Basename(fname, offset - 1);
  113. }
  114. // For testing only.
  115. // Returns true if raw logging is fully supported. When it is not
  116. // fully supported, no messages will be emitted, but a log at FATAL
  117. // severity will cause an abort.
  118. //
  119. // TODO(gfalcon): Come up with a better name for this method.
  120. bool RawLoggingFullySupported();
  121. // Function type for a raw_logging customization hook for suppressing messages
  122. // by severity, and for writing custom prefixes on non-suppressed messages.
  123. //
  124. // The installed hook is called for every raw log invocation. The message will
  125. // be logged to stderr only if the hook returns true. FATAL errors will cause
  126. // the process to abort, even if writing to stderr is suppressed. The hook is
  127. // also provided with an output buffer, where it can write a custom log message
  128. // prefix.
  129. //
  130. // The raw_logging system does not allocate memory or grab locks. User-provided
  131. // hooks must avoid these operations, and must not throw exceptions.
  132. //
  133. // 'severity' is the severity level of the message being written.
  134. // 'file' and 'line' are the file and line number where the ABSL_RAW_LOG macro
  135. // was located.
  136. // 'buffer' and 'buf_size' are pointers to the buffer and buffer size. If the
  137. // hook writes a prefix, it must increment *buffer and decrement *buf_size
  138. // accordingly.
  139. using LogPrefixHook = bool (*)(absl::LogSeverity severity, const char* file,
  140. int line, char** buffer, int* buf_size);
  141. // Function type for a raw_logging customization hook called to abort a process
  142. // when a FATAL message is logged. If the provided AbortHook() returns, the
  143. // logging system will call abort().
  144. //
  145. // 'file' and 'line' are the file and line number where the ABSL_RAW_LOG macro
  146. // was located.
  147. // The NUL-terminated logged message lives in the buffer between 'buf_start'
  148. // and 'buf_end'. 'prefix_end' points to the first non-prefix character of the
  149. // buffer (as written by the LogPrefixHook.)
  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 RegisterLogPrefixHook(LogPrefixHook func);
  169. void RegisterAbortHook(AbortHook func);
  170. void RegisterInternalLogFunction(InternalLogFunction func);
  171. } // namespace raw_logging_internal
  172. ABSL_NAMESPACE_END
  173. } // namespace absl
  174. #endif // ABSL_BASE_INTERNAL_RAW_LOGGING_H_