blob: e8b445f2647084336f8bbf6056bf6adccf12e16c [file] [log] [blame]
Dan Alberte3ea0582015-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 Hughesf5224432016-03-23 15:04:52 -070016
17#ifndef ANDROID_BASE_LOGGING_H
18#define ANDROID_BASE_LOGGING_H
Dan Alberte3ea0582015-03-13 23:06:01 -070019
Spencer Low47590522015-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 Albert2f638c02015-05-04 16:40:38 -070022#ifdef _WIN32
Spencer Low47590522015-05-19 22:12:06 -070023// windows.h includes wingdi.h which defines an evil macro ERROR.
24#ifdef ERROR
25#undef ERROR
Dan Albert2f638c02015-05-04 16:40:38 -070026#endif
Spencer Low5d6ee462015-05-06 16:13:42 -070027#endif
Dan Albert2f638c02015-05-04 16:40:38 -070028
Dan Albert1f65c492015-03-27 11:20:14 -070029#include <functional>
Dan Alberte3ea0582015-03-13 23:06:01 -070030#include <memory>
31#include <ostream>
32
Elliott Hughesb6351622015-12-04 22:00:26 -080033#include "android-base/macros.h"
Dan Alberte3ea0582015-03-13 23:06:01 -070034
35namespace android {
36namespace base {
37
38enum LogSeverity {
39 VERBOSE,
40 DEBUG,
41 INFO,
42 WARNING,
43 ERROR,
Andreas Gamped2a4f212016-09-07 10:10:50 -070044 FATAL_WITHOUT_ABORT,
Dan Alberte3ea0582015-03-13 23:06:01 -070045 FATAL,
46};
47
Dan Albertab5c8822015-03-27 11:20:14 -070048enum LogId {
Dan Albert1f65c492015-03-27 11:20:14 -070049 DEFAULT,
Dan Albertab5c8822015-03-27 11:20:14 -070050 MAIN,
51 SYSTEM,
52};
53
Andreas Gampe9008e8d2016-09-08 11:03:58 -070054using LogFunction = std::function<void(LogId, LogSeverity, const char*, const char*,
55 unsigned int, const char*)>;
56using AbortFunction = std::function<void(const char*)>;
Dan Albert1f65c492015-03-27 11:20:14 -070057
Elliott Hughes8cf75f02016-08-04 16:09:39 -070058void KernelLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
59void StderrLogger(LogId, LogSeverity, const char*, const char*, unsigned int, const char*);
Dan Albert1f65c492015-03-27 11:20:14 -070060
Andreas Gampe9008e8d2016-09-08 11:03:58 -070061void DefaultAborter(const char* abort_message);
62
Dan Albert1f65c492015-03-27 11:20:14 -070063#ifdef __ANDROID__
64// We expose this even though it is the default because a user that wants to
65// override the default log buffer will have to construct this themselves.
66class LogdLogger {
67 public:
68 explicit LogdLogger(LogId default_log_id = android::base::MAIN);
69
70 void operator()(LogId, LogSeverity, const char* tag, const char* file,
71 unsigned int line, const char* message);
72
73 private:
74 LogId default_log_id_;
75};
76#endif
77
Dan Alberte3ea0582015-03-13 23:06:01 -070078// Configure logging based on ANDROID_LOG_TAGS environment variable.
79// We need to parse a string that looks like
80//
81// *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
82//
83// The tag (or '*' for the global level) comes first, followed by a colon and a
84// letter indicating the minimum priority level we're expected to log. This can
85// be used to reveal or conceal logs with specific tags.
Andreas Gampe9008e8d2016-09-08 11:03:58 -070086#ifdef __ANDROID__
87#define INIT_LOGGING_DEFAULT_LOGGER LogdLogger()
88#else
89#define INIT_LOGGING_DEFAULT_LOGGER StderrLogger
90#endif
91void InitLogging(char* argv[],
92 LogFunction&& logger = INIT_LOGGING_DEFAULT_LOGGER,
93 AbortFunction&& aborter = DefaultAborter);
94#undef INIT_LOGGING_DEFAULT_LOGGER
Dan Alberte3ea0582015-03-13 23:06:01 -070095
Dan Albert1f65c492015-03-27 11:20:14 -070096// Replace the current logger.
Elliott Hughes8cf75f02016-08-04 16:09:39 -070097void SetLogger(LogFunction&& logger);
Spencer Lowe0671d62015-09-17 19:36:10 -070098
Andreas Gampe9008e8d2016-09-08 11:03:58 -070099// Replace the current aborter.
100void SetAborter(AbortFunction&& aborter);
101
Spencer Lowe0671d62015-09-17 19:36:10 -0700102class ErrnoRestorer {
103 public:
104 ErrnoRestorer()
105 : saved_errno_(errno) {
106 }
107
108 ~ErrnoRestorer() {
109 errno = saved_errno_;
110 }
111
Yabin Cuid65bb9d2016-03-21 17:46:21 -0700112 // Allow this object to be used as part of && operation.
Spencer Lowe0671d62015-09-17 19:36:10 -0700113 operator bool() const {
Yabin Cuid65bb9d2016-03-21 17:46:21 -0700114 return true;
Spencer Lowe0671d62015-09-17 19:36:10 -0700115 }
116
117 private:
118 const int saved_errno_;
119
120 DISALLOW_COPY_AND_ASSIGN(ErrnoRestorer);
121};
122
Dan Alberte3ea0582015-03-13 23:06:01 -0700123// Logs a message to logcat on Android otherwise to stderr. If the severity is
124// FATAL it also causes an abort. For example:
125//
126// LOG(FATAL) << "We didn't expect to reach here";
Spencer Lowe0671d62015-09-17 19:36:10 -0700127#define LOG(severity) LOG_TO(DEFAULT, severity)
Dan Albertab5c8822015-03-27 11:20:14 -0700128
129// Logs a message to logcat with the specified log ID on Android otherwise to
130// stderr. If the severity is FATAL it also causes an abort.
Spencer Lowe0671d62015-09-17 19:36:10 -0700131// Use an if-else statement instead of just an if statement here. So if there is a
132// else statement after LOG() macro, it won't bind to the if statement in the macro.
133// do-while(0) statement doesn't work here. Because we need to support << operator
134// following the macro, like "LOG(DEBUG) << xxx;".
Yabin Cuid65bb9d2016-03-21 17:46:21 -0700135#define LOG_TO(dest, severity) \
136 UNLIKELY(::android::base::severity >= ::android::base::GetMinimumLogSeverity()) && \
137 ::android::base::ErrnoRestorer() && \
138 ::android::base::LogMessage(__FILE__, __LINE__, \
139 ::android::base::dest, \
Spencer Lowe0671d62015-09-17 19:36:10 -0700140 ::android::base::severity, -1).stream()
Dan Alberte3ea0582015-03-13 23:06:01 -0700141
142// A variant of LOG that also logs the current errno value. To be used when
143// library calls fail.
Spencer Lowe0671d62015-09-17 19:36:10 -0700144#define PLOG(severity) PLOG_TO(DEFAULT, severity)
Dan Albertab5c8822015-03-27 11:20:14 -0700145
146// Behaves like PLOG, but logs to the specified log ID.
Yabin Cuid65bb9d2016-03-21 17:46:21 -0700147#define PLOG_TO(dest, severity) \
148 UNLIKELY(::android::base::severity >= ::android::base::GetMinimumLogSeverity()) && \
149 ::android::base::ErrnoRestorer() && \
150 ::android::base::LogMessage(__FILE__, __LINE__, \
151 ::android::base::dest, \
Spencer Lowe0671d62015-09-17 19:36:10 -0700152 ::android::base::severity, errno).stream()
Dan Alberte3ea0582015-03-13 23:06:01 -0700153
154// Marker that code is yet to be implemented.
155#define UNIMPLEMENTED(level) \
156 LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
157
Chih-Hung Hsieh2de4cac2016-02-26 11:32:14 -0800158#ifdef __clang_analyzer__
159// ClangL static analyzer does not see the conditional statement inside
160// LogMessage's destructor that will abort on FATAL severity.
161#define ABORT_AFTER_LOG_FATAL for (;;abort())
162#else
163#define ABORT_AFTER_LOG_FATAL
164#endif
165
Dan Alberte3ea0582015-03-13 23:06:01 -0700166// Check whether condition x holds and LOG(FATAL) if not. The value of the
167// expression x is only evaluated once. Extra logging can be appended using <<
168// after. For example:
169//
170// CHECK(false == true) results in a log message of
171// "Check failed: false == true".
Spencer Lowe0671d62015-09-17 19:36:10 -0700172#define CHECK(x) \
Yabin Cuid65bb9d2016-03-21 17:46:21 -0700173 LIKELY((x)) || \
Chih-Hung Hsieh2de4cac2016-02-26 11:32:14 -0800174 ABORT_AFTER_LOG_FATAL \
Spencer Lowe0671d62015-09-17 19:36:10 -0700175 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
176 ::android::base::FATAL, -1).stream() \
177 << "Check failed: " #x << " "
Dan Alberte3ea0582015-03-13 23:06:01 -0700178
179// Helper for CHECK_xx(x,y) macros.
Dan Albert1f65c492015-03-27 11:20:14 -0700180#define CHECK_OP(LHS, RHS, OP) \
181 for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS); \
182 UNLIKELY(!(_values.lhs OP _values.rhs)); \
183 /* empty */) \
Chih-Hung Hsieh2de4cac2016-02-26 11:32:14 -0800184 ABORT_AFTER_LOG_FATAL \
Dan Albert1f65c492015-03-27 11:20:14 -0700185 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
186 ::android::base::FATAL, -1).stream() \
187 << "Check failed: " << #LHS << " " << #OP << " " << #RHS \
Dan Alberte3ea0582015-03-13 23:06:01 -0700188 << " (" #LHS "=" << _values.lhs << ", " #RHS "=" << _values.rhs << ") "
189
190// Check whether a condition holds between x and y, LOG(FATAL) if not. The value
191// of the expressions x and y is evaluated once. Extra logging can be appended
192// using << after. For example:
193//
194// CHECK_NE(0 == 1, false) results in
195// "Check failed: false != false (0==1=false, false=false) ".
196#define CHECK_EQ(x, y) CHECK_OP(x, y, == )
197#define CHECK_NE(x, y) CHECK_OP(x, y, != )
198#define CHECK_LE(x, y) CHECK_OP(x, y, <= )
199#define CHECK_LT(x, y) CHECK_OP(x, y, < )
200#define CHECK_GE(x, y) CHECK_OP(x, y, >= )
201#define CHECK_GT(x, y) CHECK_OP(x, y, > )
202
203// Helper for CHECK_STRxx(s1,s2) macros.
Andreas Gampe702ab482016-09-13 10:44:46 -0700204#define CHECK_STROP(s1, s2, sense) \
205 while (UNLIKELY((strcmp(s1, s2) == 0) != (sense))) \
206 ABORT_AFTER_LOG_FATAL \
207 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
208 ::android::base::FATAL, -1).stream() \
209 << "Check failed: " << "\"" << (s1) << "\"" \
210 << ((sense) ? " == " : " != ") << "\"" << (s2) << "\""
Dan Alberte3ea0582015-03-13 23:06:01 -0700211
212// Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
213#define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
214#define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false)
215
216// Perform the pthread function call(args), LOG(FATAL) on error.
217#define CHECK_PTHREAD_CALL(call, args, what) \
218 do { \
219 int rc = call args; \
220 if (rc != 0) { \
221 errno = rc; \
Chih-Hung Hsieh2de4cac2016-02-26 11:32:14 -0800222 ABORT_AFTER_LOG_FATAL \
Chih-Hung Hsieh7fb99342016-05-18 15:59:37 -0700223 PLOG(FATAL) << #call << " failed for " << (what); \
Dan Alberte3ea0582015-03-13 23:06:01 -0700224 } \
225 } while (false)
226
227// CHECK that can be used in a constexpr function. For example:
228//
229// constexpr int half(int n) {
230// return
231// DCHECK_CONSTEXPR(n >= 0, , 0)
232// CHECK_CONSTEXPR((n & 1) == 0),
233// << "Extra debugging output: n = " << n, 0)
234// n / 2;
235// }
236#define CHECK_CONSTEXPR(x, out, dummy) \
237 (UNLIKELY(!(x))) \
238 ? (LOG(FATAL) << "Check failed: " << #x out, dummy) \
239 :
240
241// DCHECKs are debug variants of CHECKs only enabled in debug builds. Generally
242// CHECK should be used unless profiling identifies a CHECK as being in
243// performance critical code.
244#if defined(NDEBUG)
245static constexpr bool kEnableDChecks = false;
246#else
247static constexpr bool kEnableDChecks = true;
248#endif
249
250#define DCHECK(x) \
251 if (::android::base::kEnableDChecks) CHECK(x)
252#define DCHECK_EQ(x, y) \
253 if (::android::base::kEnableDChecks) CHECK_EQ(x, y)
254#define DCHECK_NE(x, y) \
255 if (::android::base::kEnableDChecks) CHECK_NE(x, y)
256#define DCHECK_LE(x, y) \
257 if (::android::base::kEnableDChecks) CHECK_LE(x, y)
258#define DCHECK_LT(x, y) \
259 if (::android::base::kEnableDChecks) CHECK_LT(x, y)
260#define DCHECK_GE(x, y) \
261 if (::android::base::kEnableDChecks) CHECK_GE(x, y)
262#define DCHECK_GT(x, y) \
263 if (::android::base::kEnableDChecks) CHECK_GT(x, y)
264#define DCHECK_STREQ(s1, s2) \
265 if (::android::base::kEnableDChecks) CHECK_STREQ(s1, s2)
266#define DCHECK_STRNE(s1, s2) \
267 if (::android::base::kEnableDChecks) CHECK_STRNE(s1, s2)
268#if defined(NDEBUG)
269#define DCHECK_CONSTEXPR(x, out, dummy)
270#else
271#define DCHECK_CONSTEXPR(x, out, dummy) CHECK_CONSTEXPR(x, out, dummy)
272#endif
273
274// Temporary class created to evaluate the LHS and RHS, used with
275// MakeEagerEvaluator to infer the types of LHS and RHS.
276template <typename LHS, typename RHS>
277struct EagerEvaluator {
Andreas Gampeb1de3772016-08-31 20:55:42 -0700278 constexpr EagerEvaluator(LHS l, RHS r) : lhs(l), rhs(r) {
Dan Alberte3ea0582015-03-13 23:06:01 -0700279 }
280 LHS lhs;
281 RHS rhs;
282};
283
284// Helper function for CHECK_xx.
285template <typename LHS, typename RHS>
Andreas Gampeb1de3772016-08-31 20:55:42 -0700286constexpr EagerEvaluator<LHS, RHS> MakeEagerEvaluator(LHS lhs, RHS rhs) {
Dan Alberte3ea0582015-03-13 23:06:01 -0700287 return EagerEvaluator<LHS, RHS>(lhs, rhs);
288}
289
290// Explicitly instantiate EagerEvalue for pointers so that char*s aren't treated
291// as strings. To compare strings use CHECK_STREQ and CHECK_STRNE. We rely on
292// signed/unsigned warnings to protect you against combinations not explicitly
293// listed below.
294#define EAGER_PTR_EVALUATOR(T1, T2) \
295 template <> \
296 struct EagerEvaluator<T1, T2> { \
297 EagerEvaluator(T1 l, T2 r) \
298 : lhs(reinterpret_cast<const void*>(l)), \
299 rhs(reinterpret_cast<const void*>(r)) { \
300 } \
301 const void* lhs; \
302 const void* rhs; \
303 }
304EAGER_PTR_EVALUATOR(const char*, const char*);
305EAGER_PTR_EVALUATOR(const char*, char*);
306EAGER_PTR_EVALUATOR(char*, const char*);
307EAGER_PTR_EVALUATOR(char*, char*);
308EAGER_PTR_EVALUATOR(const unsigned char*, const unsigned char*);
309EAGER_PTR_EVALUATOR(const unsigned char*, unsigned char*);
310EAGER_PTR_EVALUATOR(unsigned char*, const unsigned char*);
311EAGER_PTR_EVALUATOR(unsigned char*, unsigned char*);
312EAGER_PTR_EVALUATOR(const signed char*, const signed char*);
313EAGER_PTR_EVALUATOR(const signed char*, signed char*);
314EAGER_PTR_EVALUATOR(signed char*, const signed char*);
315EAGER_PTR_EVALUATOR(signed char*, signed char*);
316
317// Data for the log message, not stored in LogMessage to avoid increasing the
318// stack size.
319class LogMessageData;
320
321// A LogMessage is a temporarily scoped object used by LOG and the unlikely part
322// of a CHECK. The destructor will abort if the severity is FATAL.
323class LogMessage {
324 public:
Dan Albertab5c8822015-03-27 11:20:14 -0700325 LogMessage(const char* file, unsigned int line, LogId id,
326 LogSeverity severity, int error);
Dan Alberte3ea0582015-03-13 23:06:01 -0700327
328 ~LogMessage();
329
330 // Returns the stream associated with the message, the LogMessage performs
331 // output when it goes out of scope.
332 std::ostream& stream();
333
334 // The routine that performs the actual logging.
Dan Albertab5c8822015-03-27 11:20:14 -0700335 static void LogLine(const char* file, unsigned int line, LogId id,
336 LogSeverity severity, const char* msg);
Dan Alberte3ea0582015-03-13 23:06:01 -0700337
Dan Alberte3ea0582015-03-13 23:06:01 -0700338 private:
339 const std::unique_ptr<LogMessageData> data_;
340
341 DISALLOW_COPY_AND_ASSIGN(LogMessage);
342};
343
Elliott Hughes8cf75f02016-08-04 16:09:39 -0700344// Get the minimum severity level for logging.
345LogSeverity GetMinimumLogSeverity();
346
347// Set the minimum severity level for logging, returning the old severity.
348LogSeverity SetMinimumLogSeverity(LogSeverity new_severity);
349
Dan Alberte3ea0582015-03-13 23:06:01 -0700350// Allows to temporarily change the minimum severity level for logging.
351class ScopedLogSeverity {
352 public:
353 explicit ScopedLogSeverity(LogSeverity level);
354 ~ScopedLogSeverity();
355
356 private:
357 LogSeverity old_;
358};
359
360} // namespace base
361} // namespace android
362
Elliott Hughesf5224432016-03-23 15:04:52 -0700363#endif // ANDROID_BASE_LOGGING_H