blob: 56e2ddeed6c5a9dc19859d61fbd539366873bcae [file] [log] [blame]
Dan Albert58310b42015-03-13 23:06:01 -07001/*
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 */
Elliott Hughes54c72aa2016-03-23 15:04:52 -070016
17#ifndef ANDROID_BASE_LOGGING_H
18#define ANDROID_BASE_LOGGING_H
Dan Albert58310b42015-03-13 23:06:01 -070019
Spencer Lowac3f7d92015-05-19 22:12:06 -070020// NOTE: For Windows, you must include logging.h after windows.h to allow the
21// following code to suppress the evil ERROR macro:
Dan Albertea41c212015-05-04 16:40:38 -070022#ifdef _WIN32
Spencer Lowac3f7d92015-05-19 22:12:06 -070023// windows.h includes wingdi.h which defines an evil macro ERROR.
24#ifdef ERROR
25#undef ERROR
Dan Albertea41c212015-05-04 16:40:38 -070026#endif
Spencer Low142ec752015-05-06 16:13:42 -070027#endif
Dan Albertea41c212015-05-04 16:40:38 -070028
Dan Albertb547c852015-03-27 11:20:14 -070029#include <functional>
Dan Albert58310b42015-03-13 23:06:01 -070030#include <memory>
31#include <ostream>
32
Elliott Hughes4f713192015-12-04 22:00:26 -080033#include "android-base/macros.h"
Dan Albert58310b42015-03-13 23:06:01 -070034
35namespace android {
36namespace base {
37
38enum LogSeverity {
39 VERBOSE,
40 DEBUG,
41 INFO,
42 WARNING,
43 ERROR,
44 FATAL,
45};
46
Dan Albert0c055862015-03-27 11:20:14 -070047enum LogId {
Dan Albertb547c852015-03-27 11:20:14 -070048 DEFAULT,
Dan Albert0c055862015-03-27 11:20:14 -070049 MAIN,
50 SYSTEM,
51};
52
Dan Albertb547c852015-03-27 11:20:14 -070053typedef std::function<void(LogId, LogSeverity, const char*, const char*,
54 unsigned int, const char*)> LogFunction;
55
56extern void StderrLogger(LogId, LogSeverity, const char*, const char*,
57 unsigned int, const char*);
58
59#ifdef __ANDROID__
60// We expose this even though it is the default because a user that wants to
61// override the default log buffer will have to construct this themselves.
62class LogdLogger {
63 public:
64 explicit LogdLogger(LogId default_log_id = android::base::MAIN);
65
66 void operator()(LogId, LogSeverity, const char* tag, const char* file,
67 unsigned int line, const char* message);
68
69 private:
70 LogId default_log_id_;
71};
72#endif
73
Dan Albert58310b42015-03-13 23:06:01 -070074// Configure logging based on ANDROID_LOG_TAGS environment variable.
75// We need to parse a string that looks like
76//
77// *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
78//
79// The tag (or '*' for the global level) comes first, followed by a colon and a
80// letter indicating the minimum priority level we're expected to log. This can
81// be used to reveal or conceal logs with specific tags.
Dan Albertb547c852015-03-27 11:20:14 -070082extern void InitLogging(char* argv[], LogFunction&& logger);
83
84// Configures logging using the default logger (logd for the device, stderr for
85// the host).
Dan Albert58310b42015-03-13 23:06:01 -070086extern void InitLogging(char* argv[]);
87
Dan Albertb547c852015-03-27 11:20:14 -070088// Replace the current logger.
89extern void SetLogger(LogFunction&& logger);
90
Spencer Low765ae6b2015-09-17 19:36:10 -070091// Get the minimum severity level for logging.
92extern LogSeverity GetMinimumLogSeverity();
93
94class ErrnoRestorer {
95 public:
96 ErrnoRestorer()
97 : saved_errno_(errno) {
98 }
99
100 ~ErrnoRestorer() {
101 errno = saved_errno_;
102 }
103
Yabin Cui25276282016-03-21 17:46:21 -0700104 // Allow this object to be used as part of && operation.
Spencer Low765ae6b2015-09-17 19:36:10 -0700105 operator bool() const {
Yabin Cui25276282016-03-21 17:46:21 -0700106 return true;
Spencer Low765ae6b2015-09-17 19:36:10 -0700107 }
108
109 private:
110 const int saved_errno_;
111
112 DISALLOW_COPY_AND_ASSIGN(ErrnoRestorer);
113};
114
Dan Albert58310b42015-03-13 23:06:01 -0700115// Logs a message to logcat on Android otherwise to stderr. If the severity is
116// FATAL it also causes an abort. For example:
117//
118// LOG(FATAL) << "We didn't expect to reach here";
Spencer Low765ae6b2015-09-17 19:36:10 -0700119#define LOG(severity) LOG_TO(DEFAULT, severity)
Dan Albert0c055862015-03-27 11:20:14 -0700120
121// Logs a message to logcat with the specified log ID on Android otherwise to
122// stderr. If the severity is FATAL it also causes an abort.
Spencer Low765ae6b2015-09-17 19:36:10 -0700123// Use an if-else statement instead of just an if statement here. So if there is a
124// else statement after LOG() macro, it won't bind to the if statement in the macro.
125// do-while(0) statement doesn't work here. Because we need to support << operator
126// following the macro, like "LOG(DEBUG) << xxx;".
Yabin Cui25276282016-03-21 17:46:21 -0700127#define LOG_TO(dest, severity) \
128 UNLIKELY(::android::base::severity >= ::android::base::GetMinimumLogSeverity()) && \
129 ::android::base::ErrnoRestorer() && \
130 ::android::base::LogMessage(__FILE__, __LINE__, \
131 ::android::base::dest, \
Spencer Low765ae6b2015-09-17 19:36:10 -0700132 ::android::base::severity, -1).stream()
Dan Albert58310b42015-03-13 23:06:01 -0700133
134// A variant of LOG that also logs the current errno value. To be used when
135// library calls fail.
Spencer Low765ae6b2015-09-17 19:36:10 -0700136#define PLOG(severity) PLOG_TO(DEFAULT, severity)
Dan Albert0c055862015-03-27 11:20:14 -0700137
138// Behaves like PLOG, but logs to the specified log ID.
Yabin Cui25276282016-03-21 17:46:21 -0700139#define PLOG_TO(dest, severity) \
140 UNLIKELY(::android::base::severity >= ::android::base::GetMinimumLogSeverity()) && \
141 ::android::base::ErrnoRestorer() && \
142 ::android::base::LogMessage(__FILE__, __LINE__, \
143 ::android::base::dest, \
Spencer Low765ae6b2015-09-17 19:36:10 -0700144 ::android::base::severity, errno).stream()
Dan Albert58310b42015-03-13 23:06:01 -0700145
146// Marker that code is yet to be implemented.
147#define UNIMPLEMENTED(level) \
148 LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
149
Chih-Hung Hsieh7e0e14c2016-02-26 11:32:14 -0800150#ifdef __clang_analyzer__
151// ClangL static analyzer does not see the conditional statement inside
152// LogMessage's destructor that will abort on FATAL severity.
153#define ABORT_AFTER_LOG_FATAL for (;;abort())
154#else
155#define ABORT_AFTER_LOG_FATAL
156#endif
157
Dan Albert58310b42015-03-13 23:06:01 -0700158// Check whether condition x holds and LOG(FATAL) if not. The value of the
159// expression x is only evaluated once. Extra logging can be appended using <<
160// after. For example:
161//
162// CHECK(false == true) results in a log message of
163// "Check failed: false == true".
Spencer Low765ae6b2015-09-17 19:36:10 -0700164#define CHECK(x) \
Yabin Cui25276282016-03-21 17:46:21 -0700165 LIKELY((x)) || \
Chih-Hung Hsieh7e0e14c2016-02-26 11:32:14 -0800166 ABORT_AFTER_LOG_FATAL \
Spencer Low765ae6b2015-09-17 19:36:10 -0700167 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
168 ::android::base::FATAL, -1).stream() \
169 << "Check failed: " #x << " "
Dan Albert58310b42015-03-13 23:06:01 -0700170
171// Helper for CHECK_xx(x,y) macros.
Dan Albertb547c852015-03-27 11:20:14 -0700172#define CHECK_OP(LHS, RHS, OP) \
173 for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS); \
174 UNLIKELY(!(_values.lhs OP _values.rhs)); \
175 /* empty */) \
Chih-Hung Hsieh7e0e14c2016-02-26 11:32:14 -0800176 ABORT_AFTER_LOG_FATAL \
Dan Albertb547c852015-03-27 11:20:14 -0700177 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
178 ::android::base::FATAL, -1).stream() \
179 << "Check failed: " << #LHS << " " << #OP << " " << #RHS \
Dan Albert58310b42015-03-13 23:06:01 -0700180 << " (" #LHS "=" << _values.lhs << ", " #RHS "=" << _values.rhs << ") "
181
182// Check whether a condition holds between x and y, LOG(FATAL) if not. The value
183// of the expressions x and y is evaluated once. Extra logging can be appended
184// using << after. For example:
185//
186// CHECK_NE(0 == 1, false) results in
187// "Check failed: false != false (0==1=false, false=false) ".
188#define CHECK_EQ(x, y) CHECK_OP(x, y, == )
189#define CHECK_NE(x, y) CHECK_OP(x, y, != )
190#define CHECK_LE(x, y) CHECK_OP(x, y, <= )
191#define CHECK_LT(x, y) CHECK_OP(x, y, < )
192#define CHECK_GE(x, y) CHECK_OP(x, y, >= )
193#define CHECK_GT(x, y) CHECK_OP(x, y, > )
194
195// Helper for CHECK_STRxx(s1,s2) macros.
196#define CHECK_STROP(s1, s2, sense) \
Chih-Hung Hsiehc713bce2016-05-18 15:59:37 -0700197 if (LIKELY((strcmp(s1, s2) == 0) == (sense))) \
Spencer Low765ae6b2015-09-17 19:36:10 -0700198 ; \
199 else \
Chih-Hung Hsieh7e0e14c2016-02-26 11:32:14 -0800200 ABORT_AFTER_LOG_FATAL \
Dan Albert58310b42015-03-13 23:06:01 -0700201 LOG(FATAL) << "Check failed: " \
Chih-Hung Hsiehc713bce2016-05-18 15:59:37 -0700202 << "\"" << (s1) << "\"" \
203 << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
Dan Albert58310b42015-03-13 23:06:01 -0700204
205// Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
206#define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
207#define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false)
208
209// Perform the pthread function call(args), LOG(FATAL) on error.
210#define CHECK_PTHREAD_CALL(call, args, what) \
211 do { \
212 int rc = call args; \
213 if (rc != 0) { \
214 errno = rc; \
Chih-Hung Hsieh7e0e14c2016-02-26 11:32:14 -0800215 ABORT_AFTER_LOG_FATAL \
Chih-Hung Hsiehc713bce2016-05-18 15:59:37 -0700216 PLOG(FATAL) << #call << " failed for " << (what); \
Dan Albert58310b42015-03-13 23:06:01 -0700217 } \
218 } while (false)
219
220// CHECK that can be used in a constexpr function. For example:
221//
222// constexpr int half(int n) {
223// return
224// DCHECK_CONSTEXPR(n >= 0, , 0)
225// CHECK_CONSTEXPR((n & 1) == 0),
226// << "Extra debugging output: n = " << n, 0)
227// n / 2;
228// }
229#define CHECK_CONSTEXPR(x, out, dummy) \
230 (UNLIKELY(!(x))) \
231 ? (LOG(FATAL) << "Check failed: " << #x out, dummy) \
232 :
233
234// DCHECKs are debug variants of CHECKs only enabled in debug builds. Generally
235// CHECK should be used unless profiling identifies a CHECK as being in
236// performance critical code.
237#if defined(NDEBUG)
238static constexpr bool kEnableDChecks = false;
239#else
240static constexpr bool kEnableDChecks = true;
241#endif
242
243#define DCHECK(x) \
244 if (::android::base::kEnableDChecks) CHECK(x)
245#define DCHECK_EQ(x, y) \
246 if (::android::base::kEnableDChecks) CHECK_EQ(x, y)
247#define DCHECK_NE(x, y) \
248 if (::android::base::kEnableDChecks) CHECK_NE(x, y)
249#define DCHECK_LE(x, y) \
250 if (::android::base::kEnableDChecks) CHECK_LE(x, y)
251#define DCHECK_LT(x, y) \
252 if (::android::base::kEnableDChecks) CHECK_LT(x, y)
253#define DCHECK_GE(x, y) \
254 if (::android::base::kEnableDChecks) CHECK_GE(x, y)
255#define DCHECK_GT(x, y) \
256 if (::android::base::kEnableDChecks) CHECK_GT(x, y)
257#define DCHECK_STREQ(s1, s2) \
258 if (::android::base::kEnableDChecks) CHECK_STREQ(s1, s2)
259#define DCHECK_STRNE(s1, s2) \
260 if (::android::base::kEnableDChecks) CHECK_STRNE(s1, s2)
261#if defined(NDEBUG)
262#define DCHECK_CONSTEXPR(x, out, dummy)
263#else
264#define DCHECK_CONSTEXPR(x, out, dummy) CHECK_CONSTEXPR(x, out, dummy)
265#endif
266
267// Temporary class created to evaluate the LHS and RHS, used with
268// MakeEagerEvaluator to infer the types of LHS and RHS.
269template <typename LHS, typename RHS>
270struct EagerEvaluator {
271 EagerEvaluator(LHS l, RHS r) : lhs(l), rhs(r) {
272 }
273 LHS lhs;
274 RHS rhs;
275};
276
277// Helper function for CHECK_xx.
278template <typename LHS, typename RHS>
279static inline EagerEvaluator<LHS, RHS> MakeEagerEvaluator(LHS lhs, RHS rhs) {
280 return EagerEvaluator<LHS, RHS>(lhs, rhs);
281}
282
283// Explicitly instantiate EagerEvalue for pointers so that char*s aren't treated
284// as strings. To compare strings use CHECK_STREQ and CHECK_STRNE. We rely on
285// signed/unsigned warnings to protect you against combinations not explicitly
286// listed below.
287#define EAGER_PTR_EVALUATOR(T1, T2) \
288 template <> \
289 struct EagerEvaluator<T1, T2> { \
290 EagerEvaluator(T1 l, T2 r) \
291 : lhs(reinterpret_cast<const void*>(l)), \
292 rhs(reinterpret_cast<const void*>(r)) { \
293 } \
294 const void* lhs; \
295 const void* rhs; \
296 }
297EAGER_PTR_EVALUATOR(const char*, const char*);
298EAGER_PTR_EVALUATOR(const char*, char*);
299EAGER_PTR_EVALUATOR(char*, const char*);
300EAGER_PTR_EVALUATOR(char*, char*);
301EAGER_PTR_EVALUATOR(const unsigned char*, const unsigned char*);
302EAGER_PTR_EVALUATOR(const unsigned char*, unsigned char*);
303EAGER_PTR_EVALUATOR(unsigned char*, const unsigned char*);
304EAGER_PTR_EVALUATOR(unsigned char*, unsigned char*);
305EAGER_PTR_EVALUATOR(const signed char*, const signed char*);
306EAGER_PTR_EVALUATOR(const signed char*, signed char*);
307EAGER_PTR_EVALUATOR(signed char*, const signed char*);
308EAGER_PTR_EVALUATOR(signed char*, signed char*);
309
310// Data for the log message, not stored in LogMessage to avoid increasing the
311// stack size.
312class LogMessageData;
313
314// A LogMessage is a temporarily scoped object used by LOG and the unlikely part
315// of a CHECK. The destructor will abort if the severity is FATAL.
316class LogMessage {
317 public:
Dan Albert0c055862015-03-27 11:20:14 -0700318 LogMessage(const char* file, unsigned int line, LogId id,
319 LogSeverity severity, int error);
Dan Albert58310b42015-03-13 23:06:01 -0700320
321 ~LogMessage();
322
323 // Returns the stream associated with the message, the LogMessage performs
324 // output when it goes out of scope.
325 std::ostream& stream();
326
327 // The routine that performs the actual logging.
Dan Albert0c055862015-03-27 11:20:14 -0700328 static void LogLine(const char* file, unsigned int line, LogId id,
329 LogSeverity severity, const char* msg);
Dan Albert58310b42015-03-13 23:06:01 -0700330
Dan Albert58310b42015-03-13 23:06:01 -0700331 private:
332 const std::unique_ptr<LogMessageData> data_;
333
334 DISALLOW_COPY_AND_ASSIGN(LogMessage);
335};
336
337// Allows to temporarily change the minimum severity level for logging.
338class ScopedLogSeverity {
339 public:
340 explicit ScopedLogSeverity(LogSeverity level);
341 ~ScopedLogSeverity();
342
343 private:
344 LogSeverity old_;
345};
346
347} // namespace base
348} // namespace android
349
Elliott Hughes54c72aa2016-03-23 15:04:52 -0700350#endif // ANDROID_BASE_LOGGING_H