Home | History | Annotate | Download | only in android-base
      1 /*
      2  * Copyright (C) 2015 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef ANDROID_BASE_LOGGING_H
     18 #define ANDROID_BASE_LOGGING_H
     19 
     20 //
     21 // Google-style C++ logging.
     22 //
     23 
     24 // This header provides a C++ stream interface to logging.
     25 //
     26 // To log:
     27 //
     28 //   LOG(INFO) << "Some text; " << some_value;
     29 //
     30 // Replace `INFO` with any severity from `enum LogSeverity`.
     31 //
     32 // To log the result of a failed function and include the string
     33 // representation of `errno` at the end:
     34 //
     35 //   PLOG(ERROR) << "Write failed";
     36 //
     37 // The output will be something like `Write failed: I/O error`.
     38 // Remember this as 'P' as in perror(3).
     39 //
     40 // To output your own types, simply implement operator<< as normal.
     41 //
     42 // By default, output goes to logcat on Android and stderr on the host.
     43 // A process can use `SetLogger` to decide where all logging goes.
     44 // Implementations are provided for logcat, stderr, and dmesg.
     45 
     46 // This header also provides assertions:
     47 //
     48 //   CHECK(must_be_true);
     49 //   CHECK_EQ(a, b) << z_is_interesting_too;
     50 
     51 // NOTE: For Windows, you must include logging.h after windows.h to allow the
     52 // following code to suppress the evil ERROR macro:
     53 #ifdef _WIN32
     54 // windows.h includes wingdi.h which defines an evil macro ERROR.
     55 #ifdef ERROR
     56 #undef ERROR
     57 #endif
     58 #endif
     59 
     60 #include <functional>
     61 #include <memory>
     62 #include <ostream>
     63 
     64 #include "android-base/macros.h"
     65 
     66 namespace android {
     67 namespace base {
     68 
     69 enum LogSeverity {
     70   VERBOSE,
     71   DEBUG,
     72   INFO,
     73   WARNING,
     74   ERROR,
     75   FATAL_WITHOUT_ABORT,
     76   FATAL,
     77 };
     78 
     79 enum LogId {
     80   DEFAULT,
     81   MAIN,
     82   SYSTEM,
     83 };
     84 
     85 using LogFunction = std::function<void(LogId, LogSeverity, const char*, const char*,
     86                                        unsigned int, const char*)>;
     87 using AbortFunction = std::function<void(const char*)>;
     88 
     89 void KernelLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
     90 void StderrLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
     91 
     92 void DefaultAborter(const char* abort_message);
     93 
     94 #ifdef __ANDROID__
     95 // We expose this even though it is the default because a user that wants to
     96 // override the default log buffer will have to construct this themselves.
     97 class LogdLogger {
     98  public:
     99   explicit LogdLogger(LogId default_log_id = android::base::MAIN);
    100 
    101   void operator()(LogId, LogSeverity, const char* tag, const char* file,
    102                   unsigned int line, const char* message);
    103 
    104  private:
    105   LogId default_log_id_;
    106 };
    107 #endif
    108 
    109 // Configure logging based on ANDROID_LOG_TAGS environment variable.
    110 // We need to parse a string that looks like
    111 //
    112 //      *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
    113 //
    114 // The tag (or '*' for the global level) comes first, followed by a colon and a
    115 // letter indicating the minimum priority level we're expected to log.  This can
    116 // be used to reveal or conceal logs with specific tags.
    117 #ifdef __ANDROID__
    118 #define INIT_LOGGING_DEFAULT_LOGGER LogdLogger()
    119 #else
    120 #define INIT_LOGGING_DEFAULT_LOGGER StderrLogger
    121 #endif
    122 void InitLogging(char* argv[],
    123                  LogFunction&& logger = INIT_LOGGING_DEFAULT_LOGGER,
    124                  AbortFunction&& aborter = DefaultAborter);
    125 #undef INIT_LOGGING_DEFAULT_LOGGER
    126 
    127 // Replace the current logger.
    128 void SetLogger(LogFunction&& logger);
    129 
    130 // Replace the current aborter.
    131 void SetAborter(AbortFunction&& aborter);
    132 
    133 class ErrnoRestorer {
    134  public:
    135   ErrnoRestorer()
    136       : saved_errno_(errno) {
    137   }
    138 
    139   ~ErrnoRestorer() {
    140     errno = saved_errno_;
    141   }
    142 
    143   // Allow this object to be used as part of && operation.
    144   operator bool() const {
    145     return true;
    146   }
    147 
    148  private:
    149   const int saved_errno_;
    150 
    151   DISALLOW_COPY_AND_ASSIGN(ErrnoRestorer);
    152 };
    153 
    154 // A helper macro that produces an expression that accepts both a qualified name and an
    155 // unqualified name for a LogSeverity, and returns a LogSeverity value.
    156 // Note: DO NOT USE DIRECTLY. This is an implementation detail.
    157 #define SEVERITY_LAMBDA(severity) ([&]() {    \
    158   using ::android::base::VERBOSE;             \
    159   using ::android::base::DEBUG;               \
    160   using ::android::base::INFO;                \
    161   using ::android::base::WARNING;             \
    162   using ::android::base::ERROR;               \
    163   using ::android::base::FATAL_WITHOUT_ABORT; \
    164   using ::android::base::FATAL;               \
    165   return (severity); }())
    166 
    167 // Defines whether the given severity will be logged or silently swallowed.
    168 #define WOULD_LOG(severity) \
    169   UNLIKELY((SEVERITY_LAMBDA(severity)) >= ::android::base::GetMinimumLogSeverity())
    170 
    171 // Get an ostream that can be used for logging at the given severity and to the default
    172 // destination.
    173 //
    174 // Notes:
    175 // 1) This will not check whether the severity is high enough. One should use WOULD_LOG to filter
    176 //    usage manually.
    177 // 2) This does not save and restore errno.
    178 #define LOG_STREAM(severity) LOG_STREAM_TO(DEFAULT, severity)
    179 
    180 // Get an ostream that can be used for logging at the given severity and to the
    181 // given destination. The same notes as for LOG_STREAM apply.
    182 #define LOG_STREAM_TO(dest, severity)                                   \
    183   ::android::base::LogMessage(__FILE__, __LINE__,                       \
    184                               ::android::base::dest,                    \
    185                               SEVERITY_LAMBDA(severity), -1).stream()
    186 
    187 // Logs a message to logcat on Android otherwise to stderr. If the severity is
    188 // FATAL it also causes an abort. For example:
    189 //
    190 //     LOG(FATAL) << "We didn't expect to reach here";
    191 #define LOG(severity) LOG_TO(DEFAULT, severity)
    192 
    193 // Logs a message to logcat with the specified log ID on Android otherwise to
    194 // stderr. If the severity is FATAL it also causes an abort.
    195 // Use an if-else statement instead of just an if statement here. So if there is a
    196 // else statement after LOG() macro, it won't bind to the if statement in the macro.
    197 // do-while(0) statement doesn't work here. Because we need to support << operator
    198 // following the macro, like "LOG(DEBUG) << xxx;".
    199 
    200 #define LOG_TO(dest, severity) \
    201   WOULD_LOG(severity) &&                   \
    202     ::android::base::ErrnoRestorer() &&    \
    203       LOG_STREAM_TO(dest, severity)
    204 
    205 // A variant of LOG that also logs the current errno value. To be used when
    206 // library calls fail.
    207 #define PLOG(severity) PLOG_TO(DEFAULT, severity)
    208 
    209 // Behaves like PLOG, but logs to the specified log ID.
    210 #define PLOG_TO(dest, severity)                         \
    211   WOULD_LOG(SEVERITY_LAMBDA(severity)) &&               \
    212     ::android::base::ErrnoRestorer() &&                 \
    213       ::android::base::LogMessage(__FILE__, __LINE__,   \
    214           ::android::base::dest,                        \
    215           SEVERITY_LAMBDA(severity), errno).stream()
    216 
    217 // Marker that code is yet to be implemented.
    218 #define UNIMPLEMENTED(level) \
    219   LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
    220 
    221 #ifdef __clang_analyzer__
    222 // ClangL static analyzer does not see the conditional statement inside
    223 // LogMessage's destructor that will abort on FATAL severity.
    224 #define ABORT_AFTER_LOG_FATAL for (;;abort())
    225 #else
    226 #define ABORT_AFTER_LOG_FATAL
    227 #endif
    228 
    229 // Check whether condition x holds and LOG(FATAL) if not. The value of the
    230 // expression x is only evaluated once. Extra logging can be appended using <<
    231 // after. For example:
    232 //
    233 //     CHECK(false == true) results in a log message of
    234 //       "Check failed: false == true".
    235 #define CHECK(x)                                                              \
    236   LIKELY((x)) ||                                                              \
    237     ABORT_AFTER_LOG_FATAL                                                     \
    238     ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
    239                                 ::android::base::FATAL, -1).stream()          \
    240         << "Check failed: " #x << " "
    241 
    242 // Helper for CHECK_xx(x,y) macros.
    243 #define CHECK_OP(LHS, RHS, OP)                                              \
    244   for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS);        \
    245        UNLIKELY(!(_values.lhs OP _values.rhs));                             \
    246        /* empty */)                                                         \
    247   ABORT_AFTER_LOG_FATAL                                                     \
    248   ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
    249                               ::android::base::FATAL, -1).stream()          \
    250       << "Check failed: " << #LHS << " " << #OP << " " << #RHS              \
    251       << " (" #LHS "=" << _values.lhs << ", " #RHS "=" << _values.rhs << ") "
    252 
    253 // Check whether a condition holds between x and y, LOG(FATAL) if not. The value
    254 // of the expressions x and y is evaluated once. Extra logging can be appended
    255 // using << after. For example:
    256 //
    257 //     CHECK_NE(0 == 1, false) results in
    258 //       "Check failed: false != false (0==1=false, false=false) ".
    259 #define CHECK_EQ(x, y) CHECK_OP(x, y, == )
    260 #define CHECK_NE(x, y) CHECK_OP(x, y, != )
    261 #define CHECK_LE(x, y) CHECK_OP(x, y, <= )
    262 #define CHECK_LT(x, y) CHECK_OP(x, y, < )
    263 #define CHECK_GE(x, y) CHECK_OP(x, y, >= )
    264 #define CHECK_GT(x, y) CHECK_OP(x, y, > )
    265 
    266 // Helper for CHECK_STRxx(s1,s2) macros.
    267 #define CHECK_STROP(s1, s2, sense)                                             \
    268   while (UNLIKELY((strcmp(s1, s2) == 0) != (sense)))                           \
    269     ABORT_AFTER_LOG_FATAL                                                      \
    270     ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT,  \
    271                                 ::android::base::FATAL, -1).stream()           \
    272         << "Check failed: " << "\"" << (s1) << "\""                            \
    273         << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
    274 
    275 // Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
    276 #define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
    277 #define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false)
    278 
    279 // Perform the pthread function call(args), LOG(FATAL) on error.
    280 #define CHECK_PTHREAD_CALL(call, args, what)                           \
    281   do {                                                                 \
    282     int rc = call args;                                                \
    283     if (rc != 0) {                                                     \
    284       errno = rc;                                                      \
    285       ABORT_AFTER_LOG_FATAL                                            \
    286       PLOG(FATAL) << #call << " failed for " << (what);                \
    287     }                                                                  \
    288   } while (false)
    289 
    290 // CHECK that can be used in a constexpr function. For example:
    291 //
    292 //    constexpr int half(int n) {
    293 //      return
    294 //          DCHECK_CONSTEXPR(n >= 0, , 0)
    295 //          CHECK_CONSTEXPR((n & 1) == 0),
    296 //              << "Extra debugging output: n = " << n, 0)
    297 //          n / 2;
    298 //    }
    299 #define CHECK_CONSTEXPR(x, out, dummy)                                     \
    300   (UNLIKELY(!(x)))                                                         \
    301       ? (LOG(FATAL) << "Check failed: " << #x out, dummy) \
    302       :
    303 
    304 // DCHECKs are debug variants of CHECKs only enabled in debug builds. Generally
    305 // CHECK should be used unless profiling identifies a CHECK as being in
    306 // performance critical code.
    307 #if defined(NDEBUG)
    308 static constexpr bool kEnableDChecks = false;
    309 #else
    310 static constexpr bool kEnableDChecks = true;
    311 #endif
    312 
    313 #define DCHECK(x) \
    314   if (::android::base::kEnableDChecks) CHECK(x)
    315 #define DCHECK_EQ(x, y) \
    316   if (::android::base::kEnableDChecks) CHECK_EQ(x, y)
    317 #define DCHECK_NE(x, y) \
    318   if (::android::base::kEnableDChecks) CHECK_NE(x, y)
    319 #define DCHECK_LE(x, y) \
    320   if (::android::base::kEnableDChecks) CHECK_LE(x, y)
    321 #define DCHECK_LT(x, y) \
    322   if (::android::base::kEnableDChecks) CHECK_LT(x, y)
    323 #define DCHECK_GE(x, y) \
    324   if (::android::base::kEnableDChecks) CHECK_GE(x, y)
    325 #define DCHECK_GT(x, y) \
    326   if (::android::base::kEnableDChecks) CHECK_GT(x, y)
    327 #define DCHECK_STREQ(s1, s2) \
    328   if (::android::base::kEnableDChecks) CHECK_STREQ(s1, s2)
    329 #define DCHECK_STRNE(s1, s2) \
    330   if (::android::base::kEnableDChecks) CHECK_STRNE(s1, s2)
    331 #if defined(NDEBUG)
    332 #define DCHECK_CONSTEXPR(x, out, dummy)
    333 #else
    334 #define DCHECK_CONSTEXPR(x, out, dummy) CHECK_CONSTEXPR(x, out, dummy)
    335 #endif
    336 
    337 // Temporary class created to evaluate the LHS and RHS, used with
    338 // MakeEagerEvaluator to infer the types of LHS and RHS.
    339 template <typename LHS, typename RHS>
    340 struct EagerEvaluator {
    341   constexpr EagerEvaluator(LHS l, RHS r) : lhs(l), rhs(r) {
    342   }
    343   LHS lhs;
    344   RHS rhs;
    345 };
    346 
    347 // Helper function for CHECK_xx.
    348 template <typename LHS, typename RHS>
    349 constexpr EagerEvaluator<LHS, RHS> MakeEagerEvaluator(LHS lhs, RHS rhs) {
    350   return EagerEvaluator<LHS, RHS>(lhs, rhs);
    351 }
    352 
    353 // Explicitly instantiate EagerEvalue for pointers so that char*s aren't treated
    354 // as strings. To compare strings use CHECK_STREQ and CHECK_STRNE. We rely on
    355 // signed/unsigned warnings to protect you against combinations not explicitly
    356 // listed below.
    357 #define EAGER_PTR_EVALUATOR(T1, T2)               \
    358   template <>                                     \
    359   struct EagerEvaluator<T1, T2> {                 \
    360     EagerEvaluator(T1 l, T2 r)                    \
    361         : lhs(reinterpret_cast<const void*>(l)),  \
    362           rhs(reinterpret_cast<const void*>(r)) { \
    363     }                                             \
    364     const void* lhs;                              \
    365     const void* rhs;                              \
    366   }
    367 EAGER_PTR_EVALUATOR(const char*, const char*);
    368 EAGER_PTR_EVALUATOR(const char*, char*);
    369 EAGER_PTR_EVALUATOR(char*, const char*);
    370 EAGER_PTR_EVALUATOR(char*, char*);
    371 EAGER_PTR_EVALUATOR(const unsigned char*, const unsigned char*);
    372 EAGER_PTR_EVALUATOR(const unsigned char*, unsigned char*);
    373 EAGER_PTR_EVALUATOR(unsigned char*, const unsigned char*);
    374 EAGER_PTR_EVALUATOR(unsigned char*, unsigned char*);
    375 EAGER_PTR_EVALUATOR(const signed char*, const signed char*);
    376 EAGER_PTR_EVALUATOR(const signed char*, signed char*);
    377 EAGER_PTR_EVALUATOR(signed char*, const signed char*);
    378 EAGER_PTR_EVALUATOR(signed char*, signed char*);
    379 
    380 // Data for the log message, not stored in LogMessage to avoid increasing the
    381 // stack size.
    382 class LogMessageData;
    383 
    384 // A LogMessage is a temporarily scoped object used by LOG and the unlikely part
    385 // of a CHECK. The destructor will abort if the severity is FATAL.
    386 class LogMessage {
    387  public:
    388   LogMessage(const char* file, unsigned int line, LogId id,
    389              LogSeverity severity, int error);
    390 
    391   ~LogMessage();
    392 
    393   // Returns the stream associated with the message, the LogMessage performs
    394   // output when it goes out of scope.
    395   std::ostream& stream();
    396 
    397   // The routine that performs the actual logging.
    398   static void LogLine(const char* file, unsigned int line, LogId id,
    399                       LogSeverity severity, const char* msg);
    400 
    401  private:
    402   const std::unique_ptr<LogMessageData> data_;
    403 
    404   DISALLOW_COPY_AND_ASSIGN(LogMessage);
    405 };
    406 
    407 // Get the minimum severity level for logging.
    408 LogSeverity GetMinimumLogSeverity();
    409 
    410 // Set the minimum severity level for logging, returning the old severity.
    411 LogSeverity SetMinimumLogSeverity(LogSeverity new_severity);
    412 
    413 // Allows to temporarily change the minimum severity level for logging.
    414 class ScopedLogSeverity {
    415  public:
    416   explicit ScopedLogSeverity(LogSeverity level);
    417   ~ScopedLogSeverity();
    418 
    419  private:
    420   LogSeverity old_;
    421 };
    422 
    423 }  // namespace base
    424 }  // namespace android
    425 
    426 #endif  // ANDROID_BASE_LOGGING_H
    427