1 // Ceres Solver - A fast non-linear least squares minimizer
2 // Copyright 2015 Google Inc. All rights reserved.
3 // http://ceres-solver.org/
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are met:
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.
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.
29 // Author: settinger@google.com (Scott Ettinger)
30 // mierle@gmail.com (Keir Mierle)
32 // Simplified Glog style logging with Android support. Supported macros in
33 // decreasing severity level per line:
37 // LOG(INFO), VLOG(0), LG
42 // With VLOG(n), the output is directed to one of the 5 Android log levels:
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".
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.
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
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".
69 // The following CHECK macros are defined:
71 // CHECK(condition) - fails if condition is false and logs condition.
72 // CHECK_NOTNULL(variable) - fails if the variable is NULL.
74 // The following binary check macros are also defined :
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
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
89 // To use the debug only versions, prepend a D to the normal check macros, e.g.
92 #ifndef CERCES_INTERNAL_MINIGLOG_GLOG_LOGGING_H_
93 #define CERCES_INTERNAL_MINIGLOG_GLOG_LOGGING_H_
96 # include <android/log.h>
108 // For appropriate definition of CERES_EXPORT macro.
109 #include "ceres/internal/port.h"
110 #include "ceres/internal/disable_warnings.h"
112 // Log severity level constants.
113 const int FATAL = -3;
114 const int ERROR = -2;
115 const int WARNING = -1;
118 // ------------------------- Glog compatibility ------------------------------
122 typedef int LogSeverity;
123 const int INFO = ::INFO;
124 const int WARNING = ::WARNING;
125 const int ERROR = ::ERROR;
126 const int FATAL = ::FATAL;
128 // Sink class used for integration with mock and test functions. If sinks are
129 // added, all log output is also sent to each sink through the send function.
130 // In this implementation, WaitTillSent() is called immediately after the send.
131 // This implementation is not thread safe.
132 class CERES_EXPORT LogSink {
134 virtual ~LogSink() {}
135 virtual void send(LogSeverity severity,
136 const char* full_filename,
137 const char* base_filename,
139 const struct tm* tm_time,
141 size_t message_len) = 0;
142 virtual void WaitTillSent() = 0;
145 // Global set of log sinks. The actual object is defined in logging.cc.
146 extern CERES_EXPORT std::set<LogSink *> log_sinks_global;
148 inline void InitGoogleLogging(char *argv) {
149 // Do nothing; this is ignored.
152 // Note: the Log sink functions are not thread safe.
153 inline void AddLogSink(LogSink *sink) {
154 // TODO(settinger): Add locks for thread safety.
155 log_sinks_global.insert(sink);
157 inline void RemoveLogSink(LogSink *sink) {
158 log_sinks_global.erase(sink);
161 } // namespace google
163 // ---------------------------- Logger Class --------------------------------
165 // Class created for each use of the logging macros.
166 // The logger acts as a stream and routes the final stream contents to the
167 // Android logcat output at the proper filter level. If ANDROID is not
168 // defined, output is directed to std::cerr. This class should not
169 // be directly instantiated in code, rather it should be invoked through the
170 // use of the log macros LG, LOG, or VLOG.
171 class CERES_EXPORT MessageLogger {
173 MessageLogger(const char *file, int line, const char *tag, int severity)
174 : file_(file), line_(line), tag_(tag), severity_(severity) {
175 // Pre-pend the stream with the file and line number.
176 StripBasename(std::string(file), &filename_only_);
177 stream_ << filename_only_ << ":" << line << " ";
180 // Output the contents of the stream to the proper channel on destruction.
185 static const int android_log_levels[] = {
186 ANDROID_LOG_FATAL, // LOG(FATAL)
187 ANDROID_LOG_ERROR, // LOG(ERROR)
188 ANDROID_LOG_WARN, // LOG(WARNING)
189 ANDROID_LOG_INFO, // LOG(INFO), LG, VLOG(0)
190 ANDROID_LOG_DEBUG, // VLOG(1)
191 ANDROID_LOG_VERBOSE, // VLOG(2) .. VLOG(N)
194 // Bound the logging level.
195 const int kMaxVerboseLevel = 2;
196 int android_level_index = std::min(std::max(FATAL, severity_),
197 kMaxVerboseLevel) - FATAL;
198 int android_log_level = android_log_levels[android_level_index];
200 // Output the log string the Android log at the appropriate level.
201 __android_log_write(android_log_level, tag_.c_str(), stream_.str().c_str());
203 // Indicate termination if needed.
204 if (severity_ == FATAL) {
205 __android_log_write(ANDROID_LOG_FATAL,
210 // If not building on Android, log all output to std::cerr.
211 std::cerr << stream_.str();
214 LogToSinks(severity_);
217 // Android logging at level FATAL does not terminate execution, so abort()
218 // is still required to stop the program.
219 if (severity_ == FATAL) {
224 // Return the stream associated with the logger object.
225 std::stringstream &stream() { return stream_; }
228 void LogToSinks(int severity) {
233 #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
234 // On Windows, use secure localtime_s not localtime.
235 localtime_s(&timeinfo, &rawtime);
237 // On non-Windows systems, use threadsafe localtime_r not localtime.
238 localtime_r(&rawtime, &timeinfo);
241 std::set<google::LogSink*>::iterator iter;
242 // Send the log message to all sinks.
243 for (iter = google::log_sinks_global.begin();
244 iter != google::log_sinks_global.end(); ++iter) {
245 (*iter)->send(severity, file_.c_str(), filename_only_.c_str(), line_,
246 &timeinfo, stream_.str().c_str(), stream_.str().size());
250 void WaitForSinks() {
251 // TODO(settinger): Add locks for thread safety.
252 std::set<google::LogSink *>::iterator iter;
254 // Call WaitTillSent() for all sinks.
255 for (iter = google::log_sinks_global.begin();
256 iter != google::log_sinks_global.end(); ++iter) {
257 (*iter)->WaitTillSent();
261 void StripBasename(const std::string &full_path, std::string *filename) {
262 // TODO(settinger): Add support for OSs with different path separators.
263 const char kSeparator = '/';
264 size_t pos = full_path.rfind(kSeparator);
265 if (pos != std::string::npos) {
266 *filename = full_path.substr(pos + 1, std::string::npos);
268 *filename = full_path;
273 std::string filename_only_;
276 std::stringstream stream_;
280 // ---------------------- Logging Macro definitions --------------------------
282 // This class is used to explicitly ignore values in the conditional
283 // logging macros. This avoids compiler warnings like "value computed
284 // is not used" and "statement has no effect".
285 class CERES_EXPORT LoggerVoidify {
288 // This has to be an operator with a precedence lower than << but
290 void operator&(const std::ostream &s) { }
293 // Log only if condition is met. Otherwise evaluates to void.
294 #define LOG_IF(severity, condition) \
295 !(condition) ? (void) 0 : LoggerVoidify() & \
296 MessageLogger((char *)__FILE__, __LINE__, "native", severity).stream()
298 // Log only if condition is NOT met. Otherwise evaluates to void.
299 #define LOG_IF_FALSE(severity, condition) LOG_IF(severity, !(condition))
301 // LG is a convenient shortcut for LOG(INFO). Its use is in new
302 // google3 code is discouraged and the following shortcut exists for
303 // backward compatibility with existing code.
305 # define LOG(n) LOG_IF(n, n <= MAX_LOG_LEVEL)
306 # define VLOG(n) LOG_IF(n, n <= MAX_LOG_LEVEL)
307 # define LG LOG_IF(INFO, INFO <= MAX_LOG_LEVEL)
308 # define VLOG_IF(n, condition) LOG_IF(n, (n <= MAX_LOG_LEVEL) && condition)
310 # define LOG(n) MessageLogger((char *)__FILE__, __LINE__, "native", n).stream() // NOLINT
311 # define VLOG(n) MessageLogger((char *)__FILE__, __LINE__, "native", n).stream() // NOLINT
312 # define LG MessageLogger((char *)__FILE__, __LINE__, "native", INFO).stream() // NOLINT
313 # define VLOG_IF(n, condition) LOG_IF(n, condition)
316 // Currently, VLOG is always on for levels below MAX_LOG_LEVEL.
317 #ifndef MAX_LOG_LEVEL
318 # define VLOG_IS_ON(x) (1)
320 # define VLOG_IS_ON(x) (x <= MAX_LOG_LEVEL)
326 # define DLOG(severity) true ? (void) 0 : LoggerVoidify() & \
327 MessageLogger((char *)__FILE__, __LINE__, "native", severity).stream()
331 // Log a message and terminate.
333 void LogMessageFatal(const char *file, int line, const T &message) {
334 MessageLogger((char *)__FILE__, __LINE__, "native", FATAL).stream()
338 // ---------------------------- CHECK macros ---------------------------------
340 // Check for a given boolean condition.
341 #define CHECK(condition) LOG_IF_FALSE(FATAL, condition) \
342 << "Check failed: " #condition " "
345 // Debug only version of CHECK
346 # define DCHECK(condition) LOG_IF_FALSE(FATAL, condition) \
347 << "Check failed: " #condition " "
349 // Optimized version - generates no code.
350 # define DCHECK(condition) if (false) LOG_IF_FALSE(FATAL, condition) \
351 << "Check failed: " #condition " "
354 // ------------------------- CHECK_OP macros ---------------------------------
356 // Generic binary operator check macro. This should not be directly invoked,
357 // instead use the binary comparison macros defined below.
358 #define CHECK_OP(val1, val2, op) LOG_IF_FALSE(FATAL, ((val1) op (val2))) \
359 << "Check failed: " #val1 " " #op " " #val2 " "
361 // Check_op macro definitions
362 #define CHECK_EQ(val1, val2) CHECK_OP(val1, val2, ==)
363 #define CHECK_NE(val1, val2) CHECK_OP(val1, val2, !=)
364 #define CHECK_LE(val1, val2) CHECK_OP(val1, val2, <=)
365 #define CHECK_LT(val1, val2) CHECK_OP(val1, val2, <)
366 #define CHECK_GE(val1, val2) CHECK_OP(val1, val2, >=)
367 #define CHECK_GT(val1, val2) CHECK_OP(val1, val2, >)
370 // Debug only versions of CHECK_OP macros.
371 # define DCHECK_EQ(val1, val2) CHECK_OP(val1, val2, ==)
372 # define DCHECK_NE(val1, val2) CHECK_OP(val1, val2, !=)
373 # define DCHECK_LE(val1, val2) CHECK_OP(val1, val2, <=)
374 # define DCHECK_LT(val1, val2) CHECK_OP(val1, val2, <)
375 # define DCHECK_GE(val1, val2) CHECK_OP(val1, val2, >=)
376 # define DCHECK_GT(val1, val2) CHECK_OP(val1, val2, >)
378 // These versions generate no code in optimized mode.
379 # define DCHECK_EQ(val1, val2) if (false) CHECK_OP(val1, val2, ==)
380 # define DCHECK_NE(val1, val2) if (false) CHECK_OP(val1, val2, !=)
381 # define DCHECK_LE(val1, val2) if (false) CHECK_OP(val1, val2, <=)
382 # define DCHECK_LT(val1, val2) if (false) CHECK_OP(val1, val2, <)
383 # define DCHECK_GE(val1, val2) if (false) CHECK_OP(val1, val2, >=)
384 # define DCHECK_GT(val1, val2) if (false) CHECK_OP(val1, val2, >)
387 // ---------------------------CHECK_NOTNULL macros ---------------------------
389 // Helpers for CHECK_NOTNULL(). Two are necessary to support both raw pointers
390 // and smart pointers.
391 template <typename T>
392 T& CheckNotNullCommon(const char *file, int line, const char *names, T& t) {
394 LogMessageFatal(file, line, std::string(names));
399 template <typename T>
400 T* CheckNotNull(const char *file, int line, const char *names, T* t) {
401 return CheckNotNullCommon(file, line, names, t);
404 template <typename T>
405 T& CheckNotNull(const char *file, int line, const char *names, T& t) {
406 return CheckNotNullCommon(file, line, names, t);
409 // Check that a pointer is not null.
410 #define CHECK_NOTNULL(val) \
411 CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
414 // Debug only version of CHECK_NOTNULL
415 #define DCHECK_NOTNULL(val) \
416 CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
418 // Optimized version - generates no code.
419 #define DCHECK_NOTNULL(val) if (false)\
420 CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
423 #include "ceres/internal/reenable_warnings.h"
425 #endif // CERCES_INTERNAL_MINIGLOG_GLOG_LOGGING_H_