logging.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. // Ceres Solver - A fast non-linear least squares minimizer
  2. // Copyright 2015 Google Inc. All rights reserved.
  3. // http://ceres-solver.org/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are met:
  7. //
  8. // * Redistributions of source code must retain the above copyright notice,
  9. // this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above copyright notice,
  11. // this list of conditions and the following disclaimer in the documentation
  12. // and/or other materials provided with the distribution.
  13. // * Neither the name of Google Inc. nor the names of its contributors may be
  14. // used to endorse or promote products derived from this software without
  15. // specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  21. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. // POSSIBILITY OF SUCH DAMAGE.
  28. //
  29. // Author: settinger@google.com (Scott Ettinger)
  30. // mierle@gmail.com (Keir Mierle)
  31. //
  32. // Simplified Glog style logging with Android support. Supported macros in
  33. // decreasing severity level per line:
  34. //
  35. // VLOG(2), VLOG(N)
  36. // VLOG(1),
  37. // LOG(INFO), VLOG(0), LG
  38. // LOG(WARNING),
  39. // LOG(ERROR),
  40. // LOG(FATAL),
  41. //
  42. // With VLOG(n), the output is directed to one of the 5 Android log levels:
  43. //
  44. // 2 - Verbose
  45. // 1 - Debug
  46. // 0 - Info
  47. // -1 - Warning
  48. // -2 - Error
  49. // -3 - Fatal
  50. //
  51. // Any logging of level 2 and above is directed to the Verbose level. All
  52. // Android log output is tagged with the string "native".
  53. //
  54. // If the symbol ANDROID is not defined, all output goes to std::cerr.
  55. // This allows code to be built on a different system for debug.
  56. //
  57. // Portions of this code are taken from the GLOG package. This code is only a
  58. // small subset of the GLOG functionality. Notable differences from GLOG
  59. // behavior include lack of support for displaying unprintable characters and
  60. // lack of stack trace information upon failure of the CHECK macros. On
  61. // non-Android systems, log output goes to std::cerr and is not written to a
  62. // file.
  63. //
  64. // CHECK macros are defined to test for conditions within code. Any CHECK that
  65. // fails will log the failure and terminate the application.
  66. // e.g. CHECK_GE(3, 2) will pass while CHECK_GE(3, 4) will fail after logging
  67. // "Check failed 3 >= 4".
  68. //
  69. // The following CHECK macros are defined:
  70. //
  71. // CHECK(condition) - fails if condition is false and logs condition.
  72. // CHECK_NOTNULL(variable) - fails if the variable is nullptr.
  73. //
  74. // The following binary check macros are also defined :
  75. //
  76. // Macro Operator equivalent
  77. // -------------------- -------------------
  78. // CHECK_EQ(val1, val2) val1 == val2
  79. // CHECK_NE(val1, val2) val1 != val2
  80. // CHECK_GT(val1, val2) val1 > val2
  81. // CHECK_GE(val1, val2) val1 >= val2
  82. // CHECK_LT(val1, val2) val1 < val2
  83. // CHECK_LE(val1, val2) val1 <= val2
  84. //
  85. // Debug only versions of all of the check macros are also defined. These
  86. // macros generate no code in a release build, but avoid unused variable
  87. // warnings / errors.
  88. //
  89. // To use the debug only versions, prepend a D to the normal check macros, e.g.
  90. // DCHECK_EQ(a, b).
  91. #ifndef CERCES_INTERNAL_MINIGLOG_GLOG_LOGGING_H_
  92. #define CERCES_INTERNAL_MINIGLOG_GLOG_LOGGING_H_
  93. #ifdef ANDROID
  94. #include <android/log.h>
  95. #endif // ANDROID
  96. #include <algorithm>
  97. #include <ctime>
  98. #include <fstream>
  99. #include <iostream>
  100. #include <set>
  101. #include <sstream>
  102. #include <string>
  103. #include <vector>
  104. #include "ceres/internal/disable_warnings.h"
  105. #include "ceres/internal/export.h"
  106. // Log severity level constants.
  107. // clang-format off
  108. const int FATAL = -3;
  109. const int ERROR = -2;
  110. const int WARNING = -1;
  111. const int INFO = 0;
  112. // clang-format on
  113. // ------------------------- Glog compatibility ------------------------------
  114. namespace google {
  115. using LogSeverity = int;
  116. // clang-format off
  117. const int INFO = ::INFO;
  118. const int WARNING = ::WARNING;
  119. const int ERROR = ::ERROR;
  120. const int FATAL = ::FATAL;
  121. // clang-format on
  122. // Sink class used for integration with mock and test functions. If sinks are
  123. // added, all log output is also sent to each sink through the send function.
  124. // In this implementation, WaitTillSent() is called immediately after the send.
  125. // This implementation is not thread safe.
  126. class CERES_EXPORT LogSink {
  127. public:
  128. virtual ~LogSink() = default;
  129. virtual void send(LogSeverity severity,
  130. const char* full_filename,
  131. const char* base_filename,
  132. int line,
  133. const struct tm* tm_time,
  134. const char* message,
  135. size_t message_len) = 0;
  136. virtual void WaitTillSent() = 0;
  137. };
  138. // Global set of log sinks. The actual object is defined in logging.cc.
  139. extern CERES_EXPORT std::set<LogSink*> log_sinks_global;
  140. inline void InitGoogleLogging(const char* /* argv */) {
  141. // Do nothing; this is ignored.
  142. }
  143. // Note: the Log sink functions are not thread safe.
  144. inline void AddLogSink(LogSink* sink) {
  145. // TODO(settinger): Add locks for thread safety.
  146. log_sinks_global.insert(sink);
  147. }
  148. inline void RemoveLogSink(LogSink* sink) { log_sinks_global.erase(sink); }
  149. } // namespace google
  150. // ---------------------------- Logger Class --------------------------------
  151. // Class created for each use of the logging macros.
  152. // The logger acts as a stream and routes the final stream contents to the
  153. // Android logcat output at the proper filter level. If ANDROID is not
  154. // defined, output is directed to std::cerr. This class should not
  155. // be directly instantiated in code, rather it should be invoked through the
  156. // use of the log macros LG, LOG, or VLOG.
  157. class CERES_EXPORT MessageLogger {
  158. public:
  159. MessageLogger(const char* file, int line, const char* tag, int severity)
  160. : file_(file), line_(line), tag_(tag), severity_(severity) {
  161. // Pre-pend the stream with the file and line number.
  162. StripBasename(std::string(file), &filename_only_);
  163. stream_ << filename_only_ << ":" << line << " ";
  164. }
  165. // Output the contents of the stream to the proper channel on destruction.
  166. ~MessageLogger() {
  167. stream_ << "\n";
  168. #ifdef ANDROID
  169. static const int android_log_levels[] = {
  170. ANDROID_LOG_FATAL, // LOG(FATAL)
  171. ANDROID_LOG_ERROR, // LOG(ERROR)
  172. ANDROID_LOG_WARN, // LOG(WARNING)
  173. ANDROID_LOG_INFO, // LOG(INFO), LG, VLOG(0)
  174. ANDROID_LOG_DEBUG, // VLOG(1)
  175. ANDROID_LOG_VERBOSE, // VLOG(2) .. VLOG(N)
  176. };
  177. // Bound the logging level.
  178. const int kMaxVerboseLevel = 2;
  179. int android_level_index =
  180. std::min(std::max(FATAL, severity_), kMaxVerboseLevel) - FATAL;
  181. int android_log_level = android_log_levels[android_level_index];
  182. // Output the log string the Android log at the appropriate level.
  183. __android_log_write(android_log_level, tag_.c_str(), stream_.str().c_str());
  184. // Indicate termination if needed.
  185. if (severity_ == FATAL) {
  186. __android_log_write(ANDROID_LOG_FATAL, tag_.c_str(), "terminating.\n");
  187. }
  188. #else
  189. // If not building on Android, log all output to std::cerr.
  190. std::cerr << stream_.str();
  191. #endif // ANDROID
  192. LogToSinks(severity_);
  193. WaitForSinks();
  194. // Android logging at level FATAL does not terminate execution, so abort()
  195. // is still required to stop the program.
  196. if (severity_ == FATAL) {
  197. abort();
  198. }
  199. }
  200. // Return the stream associated with the logger object.
  201. std::stringstream& stream() { return stream_; }
  202. private:
  203. void LogToSinks(int severity) {
  204. time_t rawtime;
  205. time(&rawtime);
  206. struct tm timeinfo;
  207. #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
  208. // On Windows, use secure localtime_s not localtime.
  209. localtime_s(&timeinfo, &rawtime);
  210. #else
  211. // On non-Windows systems, use threadsafe localtime_r not localtime.
  212. localtime_r(&rawtime, &timeinfo);
  213. #endif
  214. std::set<google::LogSink*>::iterator iter;
  215. // Send the log message to all sinks.
  216. for (iter = google::log_sinks_global.begin();
  217. iter != google::log_sinks_global.end();
  218. ++iter) {
  219. (*iter)->send(severity,
  220. file_.c_str(),
  221. filename_only_.c_str(),
  222. line_,
  223. &timeinfo,
  224. stream_.str().c_str(),
  225. stream_.str().size());
  226. }
  227. }
  228. void WaitForSinks() {
  229. // TODO(settinger): Add locks for thread safety.
  230. std::set<google::LogSink*>::iterator iter;
  231. // Call WaitTillSent() for all sinks.
  232. for (iter = google::log_sinks_global.begin();
  233. iter != google::log_sinks_global.end();
  234. ++iter) {
  235. (*iter)->WaitTillSent();
  236. }
  237. }
  238. void StripBasename(const std::string& full_path, std::string* filename) {
  239. // TODO(settinger): Add support for OSs with different path separators.
  240. const char kSeparator = '/';
  241. size_t pos = full_path.rfind(kSeparator);
  242. if (pos != std::string::npos) {
  243. *filename = full_path.substr(pos + 1, std::string::npos);
  244. } else {
  245. *filename = full_path;
  246. }
  247. }
  248. std::string file_;
  249. std::string filename_only_;
  250. int line_;
  251. std::string tag_;
  252. std::stringstream stream_;
  253. int severity_;
  254. };
  255. // ---------------------- Logging Macro definitions --------------------------
  256. // This class is used to explicitly ignore values in the conditional
  257. // logging macros. This avoids compiler warnings like "value computed
  258. // is not used" and "statement has no effect".
  259. class CERES_EXPORT LoggerVoidify {
  260. public:
  261. // This has to be an operator with a precedence lower than << but
  262. // higher than ?:
  263. void operator&(const std::ostream& s) {}
  264. };
  265. // Log only if condition is met. Otherwise evaluates to void.
  266. // clang-format off
  267. #define LOG_IF(severity, condition) \
  268. !(condition) ? (void) 0 : LoggerVoidify() & \
  269. MessageLogger((char *)__FILE__, __LINE__, "native", severity).stream()
  270. // clang-format on
  271. // Log only if condition is NOT met. Otherwise evaluates to void.
  272. #define LOG_IF_FALSE(severity, condition) LOG_IF(severity, !(condition))
  273. // LG is a convenient shortcut for LOG(INFO). Its use is in new
  274. // google3 code is discouraged and the following shortcut exists for
  275. // backward compatibility with existing code.
  276. // clang-format off
  277. #ifdef MAX_LOG_LEVEL
  278. # define LOG(n) LOG_IF(n, n <= MAX_LOG_LEVEL)
  279. # define VLOG(n) LOG_IF(n, n <= MAX_LOG_LEVEL)
  280. # define LG LOG_IF(INFO, INFO <= MAX_LOG_LEVEL)
  281. # define VLOG_IF(n, condition) LOG_IF(n, (n <= MAX_LOG_LEVEL) && condition)
  282. #else
  283. # define LOG(n) MessageLogger((char *)__FILE__, __LINE__, "native", n).stream() // NOLINT
  284. # define VLOG(n) MessageLogger((char *)__FILE__, __LINE__, "native", n).stream() // NOLINT
  285. # define LG MessageLogger((char *)__FILE__, __LINE__, "native", INFO).stream() // NOLINT
  286. # define VLOG_IF(n, condition) LOG_IF(n, condition)
  287. #endif
  288. // Currently, VLOG is always on for levels below MAX_LOG_LEVEL.
  289. #ifndef MAX_LOG_LEVEL
  290. # define VLOG_IS_ON(x) (1)
  291. #else
  292. # define VLOG_IS_ON(x) (x <= MAX_LOG_LEVEL)
  293. #endif
  294. #ifndef NDEBUG
  295. # define DLOG LOG
  296. #else
  297. # define DLOG(severity) true ? (void) 0 : LoggerVoidify() & \
  298. MessageLogger((char *)__FILE__, __LINE__, "native", severity).stream()
  299. #endif
  300. // clang-format on
  301. // Log a message and terminate.
  302. template <class T>
  303. void LogMessageFatal(const char* file, int line, const T& message) {
  304. MessageLogger((char*)__FILE__, __LINE__, "native", FATAL).stream() << message;
  305. }
  306. // ---------------------------- CHECK macros ---------------------------------
  307. // Check for a given boolean condition.
  308. #define CHECK(condition) \
  309. LOG_IF_FALSE(FATAL, condition) << "Check failed: " #condition " "
  310. #ifndef NDEBUG
  311. // Debug only version of CHECK
  312. #define DCHECK(condition) \
  313. LOG_IF_FALSE(FATAL, condition) << "Check failed: " #condition " "
  314. #else
  315. // Optimized version - generates no code.
  316. #define DCHECK(condition) \
  317. if (false) LOG_IF_FALSE(FATAL, condition) << "Check failed: " #condition " "
  318. #endif // NDEBUG
  319. // ------------------------- CHECK_OP macros ---------------------------------
  320. // Generic binary operator check macro. This should not be directly invoked,
  321. // instead use the binary comparison macros defined below.
  322. #define CHECK_OP(val1, val2, op) \
  323. LOG_IF_FALSE(FATAL, ((val1)op(val2))) \
  324. << "Check failed: " #val1 " " #op " " #val2 " "
  325. // clang-format off
  326. // Check_op macro definitions
  327. #define CHECK_EQ(val1, val2) CHECK_OP(val1, val2, ==)
  328. #define CHECK_NE(val1, val2) CHECK_OP(val1, val2, !=)
  329. #define CHECK_LE(val1, val2) CHECK_OP(val1, val2, <=)
  330. #define CHECK_LT(val1, val2) CHECK_OP(val1, val2, <)
  331. #define CHECK_GE(val1, val2) CHECK_OP(val1, val2, >=)
  332. #define CHECK_GT(val1, val2) CHECK_OP(val1, val2, >)
  333. #ifndef NDEBUG
  334. // Debug only versions of CHECK_OP macros.
  335. # define DCHECK_EQ(val1, val2) CHECK_OP(val1, val2, ==)
  336. # define DCHECK_NE(val1, val2) CHECK_OP(val1, val2, !=)
  337. # define DCHECK_LE(val1, val2) CHECK_OP(val1, val2, <=)
  338. # define DCHECK_LT(val1, val2) CHECK_OP(val1, val2, <)
  339. # define DCHECK_GE(val1, val2) CHECK_OP(val1, val2, >=)
  340. # define DCHECK_GT(val1, val2) CHECK_OP(val1, val2, >)
  341. #else
  342. // These versions generate no code in optimized mode.
  343. # define DCHECK_EQ(val1, val2) if (false) CHECK_OP(val1, val2, ==)
  344. # define DCHECK_NE(val1, val2) if (false) CHECK_OP(val1, val2, !=)
  345. # define DCHECK_LE(val1, val2) if (false) CHECK_OP(val1, val2, <=)
  346. # define DCHECK_LT(val1, val2) if (false) CHECK_OP(val1, val2, <)
  347. # define DCHECK_GE(val1, val2) if (false) CHECK_OP(val1, val2, >=)
  348. # define DCHECK_GT(val1, val2) if (false) CHECK_OP(val1, val2, >)
  349. #endif // NDEBUG
  350. // clang-format on
  351. // ---------------------------CHECK_NOTNULL macros ---------------------------
  352. // Helpers for CHECK_NOTNULL(). Two are necessary to support both raw pointers
  353. // and smart pointers.
  354. template <typename T>
  355. T& CheckNotNullCommon(const char* file, int line, const char* names, T& t) {
  356. if (t == nullptr) {
  357. LogMessageFatal(file, line, std::string(names));
  358. }
  359. return t;
  360. }
  361. template <typename T>
  362. T* CheckNotNull(const char* file, int line, const char* names, T* t) {
  363. return CheckNotNullCommon(file, line, names, t);
  364. }
  365. template <typename T>
  366. T& CheckNotNull(const char* file, int line, const char* names, T& t) {
  367. return CheckNotNullCommon(file, line, names, t);
  368. }
  369. // Check that a pointer is not null.
  370. #define CHECK_NOTNULL(val) \
  371. CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non nullptr", (val))
  372. #ifndef NDEBUG
  373. // Debug only version of CHECK_NOTNULL
  374. #define DCHECK_NOTNULL(val) \
  375. CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non nullptr", (val))
  376. #else
  377. // Optimized version - generates no code.
  378. #define DCHECK_NOTNULL(val) \
  379. if (false) \
  380. CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non nullptr", (val))
  381. #endif // NDEBUG
  382. #include "ceres/internal/reenable_warnings.h"
  383. #endif // CERCES_INTERNAL_MINIGLOG_GLOG_LOGGING_H_