blob: 30f69065781d80b2b3cdd6190cad8fda7a070b8c [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 */
Dan Alberte3ea0582015-03-13 23:06:01 -070016#ifndef BASE_LOGGING_H
17#define BASE_LOGGING_H
18
Spencer Low47590522015-05-19 22:12:06 -070019// NOTE: For Windows, you must include logging.h after windows.h to allow the
20// following code to suppress the evil ERROR macro:
Dan Albert2f638c02015-05-04 16:40:38 -070021#ifdef _WIN32
Spencer Low47590522015-05-19 22:12:06 -070022// windows.h includes wingdi.h which defines an evil macro ERROR.
23#ifdef ERROR
24#undef ERROR
Dan Albert2f638c02015-05-04 16:40:38 -070025#endif
Spencer Low5d6ee462015-05-06 16:13:42 -070026#endif
Dan Albert2f638c02015-05-04 16:40:38 -070027
Dan Albert1f65c492015-03-27 11:20:14 -070028#include <functional>
Dan Alberte3ea0582015-03-13 23:06:01 -070029#include <memory>
30#include <ostream>
31
32#include "base/macros.h"
33
34namespace android {
35namespace base {
36
37enum LogSeverity {
38 VERBOSE,
39 DEBUG,
40 INFO,
41 WARNING,
42 ERROR,
43 FATAL,
44};
45
Dan Albertab5c8822015-03-27 11:20:14 -070046enum LogId {
Dan Albert1f65c492015-03-27 11:20:14 -070047 DEFAULT,
Dan Albertab5c8822015-03-27 11:20:14 -070048 MAIN,
49 SYSTEM,
50};
51
Dan Albert1f65c492015-03-27 11:20:14 -070052typedef std::function<void(LogId, LogSeverity, const char*, const char*,
53 unsigned int, const char*)> LogFunction;
54
55extern void StderrLogger(LogId, LogSeverity, const char*, const char*,
56 unsigned int, const char*);
57
58#ifdef __ANDROID__
59// We expose this even though it is the default because a user that wants to
60// override the default log buffer will have to construct this themselves.
61class LogdLogger {
62 public:
63 explicit LogdLogger(LogId default_log_id = android::base::MAIN);
64
65 void operator()(LogId, LogSeverity, const char* tag, const char* file,
66 unsigned int line, const char* message);
67
68 private:
69 LogId default_log_id_;
70};
71#endif
72
Dan Alberte3ea0582015-03-13 23:06:01 -070073// Configure logging based on ANDROID_LOG_TAGS environment variable.
74// We need to parse a string that looks like
75//
76// *:v jdwp:d dalvikvm:d dalvikvm-gc:i dalvikvmi:i
77//
78// The tag (or '*' for the global level) comes first, followed by a colon and a
79// letter indicating the minimum priority level we're expected to log. This can
80// be used to reveal or conceal logs with specific tags.
Dan Albert1f65c492015-03-27 11:20:14 -070081extern void InitLogging(char* argv[], LogFunction&& logger);
82
83// Configures logging using the default logger (logd for the device, stderr for
84// the host).
Dan Alberte3ea0582015-03-13 23:06:01 -070085extern void InitLogging(char* argv[]);
86
Dan Albert1f65c492015-03-27 11:20:14 -070087// Replace the current logger.
88extern void SetLogger(LogFunction&& logger);
89
Spencer Lowe0671d62015-09-17 19:36:10 -070090// Get the minimum severity level for logging.
91extern LogSeverity GetMinimumLogSeverity();
92
93class ErrnoRestorer {
94 public:
95 ErrnoRestorer()
96 : saved_errno_(errno) {
97 }
98
99 ~ErrnoRestorer() {
100 errno = saved_errno_;
101 }
102
103 // Allow this object to evaluate to false which is useful in macros.
104 operator bool() const {
105 return false;
106 }
107
108 private:
109 const int saved_errno_;
110
111 DISALLOW_COPY_AND_ASSIGN(ErrnoRestorer);
112};
113
Dan Alberte3ea0582015-03-13 23:06:01 -0700114// Logs a message to logcat on Android otherwise to stderr. If the severity is
115// FATAL it also causes an abort. For example:
116//
117// LOG(FATAL) << "We didn't expect to reach here";
Spencer Lowe0671d62015-09-17 19:36:10 -0700118#define LOG(severity) LOG_TO(DEFAULT, severity)
Dan Albertab5c8822015-03-27 11:20:14 -0700119
120// Logs a message to logcat with the specified log ID on Android otherwise to
121// stderr. If the severity is FATAL it also causes an abort.
Spencer Lowe0671d62015-09-17 19:36:10 -0700122// Use an if-else statement instead of just an if statement here. So if there is a
123// else statement after LOG() macro, it won't bind to the if statement in the macro.
124// do-while(0) statement doesn't work here. Because we need to support << operator
125// following the macro, like "LOG(DEBUG) << xxx;".
126#define LOG_TO(dest, severity) \
127 if (LIKELY(::android::base::severity < ::android::base::GetMinimumLogSeverity())) \
128 ; \
129 else \
130 ::android::base::ErrnoRestorer() ? *(std::ostream*)nullptr : \
131 ::android::base::LogMessage(__FILE__, __LINE__, \
132 ::android::base::dest, \
133 ::android::base::severity, -1).stream()
Dan Alberte3ea0582015-03-13 23:06:01 -0700134
135// A variant of LOG that also logs the current errno value. To be used when
136// library calls fail.
Spencer Lowe0671d62015-09-17 19:36:10 -0700137#define PLOG(severity) PLOG_TO(DEFAULT, severity)
Dan Albertab5c8822015-03-27 11:20:14 -0700138
139// Behaves like PLOG, but logs to the specified log ID.
Spencer Lowe0671d62015-09-17 19:36:10 -0700140#define PLOG_TO(dest, severity) \
141 if (LIKELY(::android::base::severity < ::android::base::GetMinimumLogSeverity())) \
142 ; \
143 else \
144 ::android::base::ErrnoRestorer() ? *(std::ostream*)nullptr : \
145 ::android::base::LogMessage(__FILE__, __LINE__, \
146 ::android::base::dest, \
147 ::android::base::severity, errno).stream()
Dan Alberte3ea0582015-03-13 23:06:01 -0700148
149// Marker that code is yet to be implemented.
150#define UNIMPLEMENTED(level) \
151 LOG(level) << __PRETTY_FUNCTION__ << " unimplemented "
152
153// Check whether condition x holds and LOG(FATAL) if not. The value of the
154// expression x is only evaluated once. Extra logging can be appended using <<
155// after. For example:
156//
157// CHECK(false == true) results in a log message of
158// "Check failed: false == true".
Spencer Lowe0671d62015-09-17 19:36:10 -0700159#define CHECK(x) \
160 if (LIKELY((x))) \
161 ; \
162 else \
163 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
164 ::android::base::FATAL, -1).stream() \
165 << "Check failed: " #x << " "
Dan Alberte3ea0582015-03-13 23:06:01 -0700166
167// Helper for CHECK_xx(x,y) macros.
Dan Albert1f65c492015-03-27 11:20:14 -0700168#define CHECK_OP(LHS, RHS, OP) \
169 for (auto _values = ::android::base::MakeEagerEvaluator(LHS, RHS); \
170 UNLIKELY(!(_values.lhs OP _values.rhs)); \
171 /* empty */) \
172 ::android::base::LogMessage(__FILE__, __LINE__, ::android::base::DEFAULT, \
173 ::android::base::FATAL, -1).stream() \
174 << "Check failed: " << #LHS << " " << #OP << " " << #RHS \
Dan Alberte3ea0582015-03-13 23:06:01 -0700175 << " (" #LHS "=" << _values.lhs << ", " #RHS "=" << _values.rhs << ") "
176
177// Check whether a condition holds between x and y, LOG(FATAL) if not. The value
178// of the expressions x and y is evaluated once. Extra logging can be appended
179// using << after. For example:
180//
181// CHECK_NE(0 == 1, false) results in
182// "Check failed: false != false (0==1=false, false=false) ".
183#define CHECK_EQ(x, y) CHECK_OP(x, y, == )
184#define CHECK_NE(x, y) CHECK_OP(x, y, != )
185#define CHECK_LE(x, y) CHECK_OP(x, y, <= )
186#define CHECK_LT(x, y) CHECK_OP(x, y, < )
187#define CHECK_GE(x, y) CHECK_OP(x, y, >= )
188#define CHECK_GT(x, y) CHECK_OP(x, y, > )
189
190// Helper for CHECK_STRxx(s1,s2) macros.
191#define CHECK_STROP(s1, s2, sense) \
Spencer Lowe0671d62015-09-17 19:36:10 -0700192 if (LIKELY((strcmp(s1, s2) == 0) == sense)) \
193 ; \
194 else \
Dan Alberte3ea0582015-03-13 23:06:01 -0700195 LOG(FATAL) << "Check failed: " \
196 << "\"" << s1 << "\"" \
197 << (sense ? " == " : " != ") << "\"" << s2 << "\""
198
199// Check for string (const char*) equality between s1 and s2, LOG(FATAL) if not.
200#define CHECK_STREQ(s1, s2) CHECK_STROP(s1, s2, true)
201#define CHECK_STRNE(s1, s2) CHECK_STROP(s1, s2, false)
202
203// Perform the pthread function call(args), LOG(FATAL) on error.
204#define CHECK_PTHREAD_CALL(call, args, what) \
205 do { \
206 int rc = call args; \
207 if (rc != 0) { \
208 errno = rc; \
209 PLOG(FATAL) << #call << " failed for " << what; \
210 } \
211 } while (false)
212
213// CHECK that can be used in a constexpr function. For example:
214//
215// constexpr int half(int n) {
216// return
217// DCHECK_CONSTEXPR(n >= 0, , 0)
218// CHECK_CONSTEXPR((n & 1) == 0),
219// << "Extra debugging output: n = " << n, 0)
220// n / 2;
221// }
222#define CHECK_CONSTEXPR(x, out, dummy) \
223 (UNLIKELY(!(x))) \
224 ? (LOG(FATAL) << "Check failed: " << #x out, dummy) \
225 :
226
227// DCHECKs are debug variants of CHECKs only enabled in debug builds. Generally
228// CHECK should be used unless profiling identifies a CHECK as being in
229// performance critical code.
230#if defined(NDEBUG)
231static constexpr bool kEnableDChecks = false;
232#else
233static constexpr bool kEnableDChecks = true;
234#endif
235
236#define DCHECK(x) \
237 if (::android::base::kEnableDChecks) CHECK(x)
238#define DCHECK_EQ(x, y) \
239 if (::android::base::kEnableDChecks) CHECK_EQ(x, y)
240#define DCHECK_NE(x, y) \
241 if (::android::base::kEnableDChecks) CHECK_NE(x, y)
242#define DCHECK_LE(x, y) \
243 if (::android::base::kEnableDChecks) CHECK_LE(x, y)
244#define DCHECK_LT(x, y) \
245 if (::android::base::kEnableDChecks) CHECK_LT(x, y)
246#define DCHECK_GE(x, y) \
247 if (::android::base::kEnableDChecks) CHECK_GE(x, y)
248#define DCHECK_GT(x, y) \
249 if (::android::base::kEnableDChecks) CHECK_GT(x, y)
250#define DCHECK_STREQ(s1, s2) \
251 if (::android::base::kEnableDChecks) CHECK_STREQ(s1, s2)
252#define DCHECK_STRNE(s1, s2) \
253 if (::android::base::kEnableDChecks) CHECK_STRNE(s1, s2)
254#if defined(NDEBUG)
255#define DCHECK_CONSTEXPR(x, out, dummy)
256#else
257#define DCHECK_CONSTEXPR(x, out, dummy) CHECK_CONSTEXPR(x, out, dummy)
258#endif
259
260// Temporary class created to evaluate the LHS and RHS, used with
261// MakeEagerEvaluator to infer the types of LHS and RHS.
262template <typename LHS, typename RHS>
263struct EagerEvaluator {
264 EagerEvaluator(LHS l, RHS r) : lhs(l), rhs(r) {
265 }
266 LHS lhs;
267 RHS rhs;
268};
269
270// Helper function for CHECK_xx.
271template <typename LHS, typename RHS>
272static inline EagerEvaluator<LHS, RHS> MakeEagerEvaluator(LHS lhs, RHS rhs) {
273 return EagerEvaluator<LHS, RHS>(lhs, rhs);
274}
275
276// Explicitly instantiate EagerEvalue for pointers so that char*s aren't treated
277// as strings. To compare strings use CHECK_STREQ and CHECK_STRNE. We rely on
278// signed/unsigned warnings to protect you against combinations not explicitly
279// listed below.
280#define EAGER_PTR_EVALUATOR(T1, T2) \
281 template <> \
282 struct EagerEvaluator<T1, T2> { \
283 EagerEvaluator(T1 l, T2 r) \
284 : lhs(reinterpret_cast<const void*>(l)), \
285 rhs(reinterpret_cast<const void*>(r)) { \
286 } \
287 const void* lhs; \
288 const void* rhs; \
289 }
290EAGER_PTR_EVALUATOR(const char*, const char*);
291EAGER_PTR_EVALUATOR(const char*, char*);
292EAGER_PTR_EVALUATOR(char*, const char*);
293EAGER_PTR_EVALUATOR(char*, char*);
294EAGER_PTR_EVALUATOR(const unsigned char*, const unsigned char*);
295EAGER_PTR_EVALUATOR(const unsigned char*, unsigned char*);
296EAGER_PTR_EVALUATOR(unsigned char*, const unsigned char*);
297EAGER_PTR_EVALUATOR(unsigned char*, unsigned char*);
298EAGER_PTR_EVALUATOR(const signed char*, const signed char*);
299EAGER_PTR_EVALUATOR(const signed char*, signed char*);
300EAGER_PTR_EVALUATOR(signed char*, const signed char*);
301EAGER_PTR_EVALUATOR(signed char*, signed char*);
302
303// Data for the log message, not stored in LogMessage to avoid increasing the
304// stack size.
305class LogMessageData;
306
307// A LogMessage is a temporarily scoped object used by LOG and the unlikely part
308// of a CHECK. The destructor will abort if the severity is FATAL.
309class LogMessage {
310 public:
Dan Albertab5c8822015-03-27 11:20:14 -0700311 LogMessage(const char* file, unsigned int line, LogId id,
312 LogSeverity severity, int error);
Dan Alberte3ea0582015-03-13 23:06:01 -0700313
314 ~LogMessage();
315
316 // Returns the stream associated with the message, the LogMessage performs
317 // output when it goes out of scope.
318 std::ostream& stream();
319
320 // The routine that performs the actual logging.
Dan Albertab5c8822015-03-27 11:20:14 -0700321 static void LogLine(const char* file, unsigned int line, LogId id,
322 LogSeverity severity, const char* msg);
Dan Alberte3ea0582015-03-13 23:06:01 -0700323
Dan Alberte3ea0582015-03-13 23:06:01 -0700324 private:
325 const std::unique_ptr<LogMessageData> data_;
326
327 DISALLOW_COPY_AND_ASSIGN(LogMessage);
328};
329
330// Allows to temporarily change the minimum severity level for logging.
331class ScopedLogSeverity {
332 public:
333 explicit ScopedLogSeverity(LogSeverity level);
334 ~ScopedLogSeverity();
335
336 private:
337 LogSeverity old_;
338};
339
340} // namespace base
341} // namespace android
342
343#endif // BASE_LOGGING_H