blob: 8bfb204625a8c97490ce76fce1d7a9d28ca6c5e2 [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 */
16
17#include "base/logging.h"
18
19#include <iostream>
20#include <limits>
21#include <sstream>
22#include <string>
23#include <vector>
24
25#include "base/strings.h"
Dan Albert7dfb61d2015-03-20 13:46:28 -070026#include "cutils/threads.h"
Dan Albert58310b42015-03-13 23:06:01 -070027
28// Headers for LogMessage::LogLine.
29#ifdef __ANDROID__
30#include <android/set_abort_message.h>
31#include "cutils/log.h"
32#else
33#include <sys/types.h>
34#include <unistd.h>
35#endif
36
Dan Albert58310b42015-03-13 23:06:01 -070037namespace android {
38namespace base {
39
40static std::mutex logging_lock;
41
42static LogSeverity gMinimumLogSeverity = INFO;
43static std::unique_ptr<std::string> gCmdLine;
44static std::unique_ptr<std::string> gProgramInvocationName;
45static std::unique_ptr<std::string> gProgramInvocationShortName;
46
Dan Albert58310b42015-03-13 23:06:01 -070047const char* GetCmdLine() {
48 return (gCmdLine.get() != nullptr) ? gCmdLine->c_str() : nullptr;
49}
50
51const char* ProgramInvocationName() {
52 return (gProgramInvocationName.get() != nullptr)
53 ? gProgramInvocationName->c_str()
54 : "unknown";
55}
56
57const char* ProgramInvocationShortName() {
58 return (gProgramInvocationShortName.get() != nullptr)
59 ? gProgramInvocationShortName->c_str()
60 : "unknown";
61}
62
63void InitLogging(char* argv[]) {
64 if (gCmdLine.get() != nullptr) {
65 return;
66 }
67
68 // Stash the command line for later use. We can use /proc/self/cmdline on
69 // Linux to recover this, but we don't have that luxury on the Mac, and there
70 // are a couple of argv[0] variants that are commonly used.
71 if (argv != nullptr) {
72 gCmdLine.reset(new std::string(argv[0]));
73 for (size_t i = 1; argv[i] != nullptr; ++i) {
74 gCmdLine->append(" ");
75 gCmdLine->append(argv[i]);
76 }
77 gProgramInvocationName.reset(new std::string(argv[0]));
78 const char* last_slash = strrchr(argv[0], '/');
79 gProgramInvocationShortName.reset(
80 new std::string((last_slash != nullptr) ? last_slash + 1 : argv[0]));
81 } else {
82 // TODO: fall back to /proc/self/cmdline when argv is NULL on Linux.
83 gCmdLine.reset(new std::string("<unset>"));
84 }
85 const char* tags = getenv("ANDROID_LOG_TAGS");
86 if (tags == nullptr) {
87 return;
88 }
89
Dan Albert47328c92015-03-19 13:24:26 -070090 std::vector<std::string> specs = Split(tags, " ");
Dan Albert58310b42015-03-13 23:06:01 -070091 for (size_t i = 0; i < specs.size(); ++i) {
92 // "tag-pattern:[vdiwefs]"
93 std::string spec(specs[i]);
94 if (spec.size() == 3 && StartsWith(spec, "*:")) {
95 switch (spec[2]) {
96 case 'v':
97 gMinimumLogSeverity = VERBOSE;
98 continue;
99 case 'd':
100 gMinimumLogSeverity = DEBUG;
101 continue;
102 case 'i':
103 gMinimumLogSeverity = INFO;
104 continue;
105 case 'w':
106 gMinimumLogSeverity = WARNING;
107 continue;
108 case 'e':
109 gMinimumLogSeverity = ERROR;
110 continue;
111 case 'f':
112 gMinimumLogSeverity = FATAL;
113 continue;
114 // liblog will even suppress FATAL if you say 's' for silent, but that's
115 // crazy!
116 case 's':
117 gMinimumLogSeverity = FATAL;
118 continue;
119 }
120 }
121 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
122 << ")";
123 }
124}
125
126// This indirection greatly reduces the stack impact of having lots of
127// checks/logging in a function.
128class LogMessageData {
129 public:
130 LogMessageData(const char* file, unsigned int line, LogSeverity severity,
131 int error)
132 : file_(file), line_number_(line), severity_(severity), error_(error) {
133 const char* last_slash = strrchr(file, '/');
134 file = (last_slash == nullptr) ? file : last_slash + 1;
135 }
136
137 const char* GetFile() const {
138 return file_;
139 }
140
141 unsigned int GetLineNumber() const {
142 return line_number_;
143 }
144
145 LogSeverity GetSeverity() const {
146 return severity_;
147 }
148
149 int GetError() const {
150 return error_;
151 }
152
153 std::ostream& GetBuffer() {
154 return buffer_;
155 }
156
157 std::string ToString() const {
158 return buffer_.str();
159 }
160
161 private:
162 std::ostringstream buffer_;
163 const char* const file_;
164 const unsigned int line_number_;
165 const LogSeverity severity_;
166 const int error_;
167
168 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
169};
170
171LogMessage::LogMessage(const char* file, unsigned int line,
172 LogSeverity severity, int error)
173 : data_(new LogMessageData(file, line, severity, error)) {
174}
175
176LogMessage::~LogMessage() {
177 if (data_->GetSeverity() < gMinimumLogSeverity) {
178 return; // No need to format something we're not going to output.
179 }
180
181 // Finish constructing the message.
182 if (data_->GetError() != -1) {
183 data_->GetBuffer() << ": " << strerror(data_->GetError());
184 }
185 std::string msg(data_->ToString());
186
187 // Do the actual logging with the lock held.
188 {
189 std::lock_guard<std::mutex> lock(logging_lock);
190 if (msg.find('\n') == std::string::npos) {
191 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetSeverity(),
192 msg.c_str());
193 } else {
194 msg += '\n';
195 size_t i = 0;
196 while (i < msg.size()) {
197 size_t nl = msg.find('\n', i);
198 msg[nl] = '\0';
199 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetSeverity(),
200 &msg[i]);
201 i = nl + 1;
202 }
203 }
204 }
205
206 // Abort if necessary.
207 if (data_->GetSeverity() == FATAL) {
208#ifdef __ANDROID__
209 android_set_abort_message(msg.c_str());
210#endif
211 abort();
212 }
213}
214
215std::ostream& LogMessage::stream() {
216 return data_->GetBuffer();
217}
218
219#ifdef __ANDROID__
220static const android_LogPriority kLogSeverityToAndroidLogPriority[] = {
221 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
222 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL};
223static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
224 "Mismatch in size of kLogSeverityToAndroidLogPriority and values "
225 "in LogSeverity");
226#endif
227
228void LogMessage::LogLine(const char* file, unsigned int line,
229 LogSeverity log_severity, const char* message) {
230#ifdef __ANDROID__
231 const char* tag = ProgramInvocationShortName();
232 int priority = kLogSeverityToAndroidLogPriority[log_severity];
233 if (priority == ANDROID_LOG_FATAL) {
234 LOG_PRI(priority, tag, "%s:%u] %s", file, line, message);
235 } else {
236 LOG_PRI(priority, tag, "%s", message);
237 }
238#else
239 static const char* log_characters = "VDIWEF";
240 CHECK_EQ(strlen(log_characters), FATAL + 1U);
241 char severity = log_characters[log_severity];
242 fprintf(stderr, "%s %c %5d %5d %s:%u] %s\n", ProgramInvocationShortName(),
Dan Albert7dfb61d2015-03-20 13:46:28 -0700243 severity, getpid(), gettid(), file, line, message);
Dan Albert58310b42015-03-13 23:06:01 -0700244#endif
245}
246
247void LogMessage::LogLineLowStack(const char* file, unsigned int line,
248 LogSeverity log_severity, const char* message) {
249#ifdef __ANDROID__
250 // Use android_writeLog() to avoid stack-based buffers used by
251 // android_printLog().
252 const char* tag = ProgramInvocationShortName();
253 int priority = kLogSeverityToAndroidLogPriority[log_severity];
254 char* buf = nullptr;
255 size_t buf_size = 0u;
256 if (priority == ANDROID_LOG_FATAL) {
257 // Allocate buffer for snprintf(buf, buf_size, "%s:%u] %s", file, line,
258 // message) below. If allocation fails, fall back to printing only the
259 // message.
260 buf_size = strlen(file) + 1 /* ':' */ +
261 std::numeric_limits<typeof(line)>::max_digits10 + 2 /* "] " */ +
262 strlen(message) + 1 /* terminating 0 */;
263 buf = reinterpret_cast<char*>(malloc(buf_size));
264 }
265 if (buf != nullptr) {
266 snprintf(buf, buf_size, "%s:%u] %s", file, line, message);
267 android_writeLog(priority, tag, buf);
268 free(buf);
269 } else {
270 android_writeLog(priority, tag, message);
271 }
272#else
273 static const char* log_characters = "VDIWEF";
274 CHECK_EQ(strlen(log_characters), FATAL + 1U);
275
276 const char* program_name = ProgramInvocationShortName();
277 write(STDERR_FILENO, program_name, strlen(program_name));
278 write(STDERR_FILENO, " ", 1);
279 write(STDERR_FILENO, &log_characters[log_severity], 1);
280 write(STDERR_FILENO, " ", 1);
281 // TODO: pid and tid.
282 write(STDERR_FILENO, file, strlen(file));
283 // TODO: line.
284 UNUSED(line);
285 write(STDERR_FILENO, "] ", 2);
286 write(STDERR_FILENO, message, strlen(message));
287 write(STDERR_FILENO, "\n", 1);
288#endif
289}
290
291ScopedLogSeverity::ScopedLogSeverity(LogSeverity level) {
292 old_ = gMinimumLogSeverity;
293 gMinimumLogSeverity = level;
294}
295
296ScopedLogSeverity::~ScopedLogSeverity() {
297 gMinimumLogSeverity = old_;
298}
299
300} // namespace base
301} // namespace android