blob: b1fd3e2627ae332ebd27c97aada3f908b9ca77d8 [file] [log] [blame]
[email protected]63e66802012-01-18 21:21:091// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
[email protected]b16ef312008-08-19 18:36:235#include "base/logging.h"
[email protected]f6abeba2008-08-08 13:27:286
Hans Wennborg12aea3e2020-04-14 15:29:007// logging.h is a widely included header and its size has significant impact on
8// build time. Try not to raise this limit unless absolutely necessary. See
9// https://chromium.googlesource.com/chromium/src/+/HEAD/docs/wmax_tokens.md
10#ifndef NACL_TC_REV
Hans Wennborg944479f2020-06-25 21:39:2511#pragma clang max_tokens_here 350000
Hans Wennborg12aea3e2020-04-14 15:29:0012#endif // NACL_TC_REV
13
Hans Wennborg944479f2020-06-25 21:39:2514#ifdef BASE_CHECK_H_
15#error "logging.h should not include check.h"
16#endif
17
avi51ba3e692015-12-26 17:30:5018#include <limits.h>
avi9b6f42932015-12-26 22:15:1419#include <stdint.h>
20
David Bienvenub4b441e2020-09-23 05:49:5721#include <vector>
22
Chris Hamilton306740d2019-04-25 18:48:3623#include "base/pending_task.h"
Weze976b732018-10-20 03:37:3124#include "base/stl_util.h"
Chris Hamilton306740d2019-04-25 18:48:3625#include "base/task/common/task_annotator.h"
Eric Secklerf6c544f2020-06-02 10:49:2126#include "base/trace_event/base_tracing.h"
avi9b6f42932015-12-26 22:15:1427#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5028
[email protected]b16ef312008-08-19 18:36:2329#if defined(OS_WIN)
[email protected]e36ddc82009-12-08 04:22:5030#include <io.h>
alex-accc1bde62017-04-19 08:33:5531#include <windows.h>
[email protected]f6abeba2008-08-08 13:27:2832typedef HANDLE FileHandle;
[email protected]e36ddc82009-12-08 04:22:5033// Windows warns on using write(). It prefers _write().
34#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
35// Windows doesn't define STDERR_FILENO. Define it here.
36#define STDERR_FILENO 2
Eric Noyaufce100702017-10-16 09:46:3437
Avi Drissman5b286372020-07-28 21:59:3838#elif defined(OS_APPLE)
Eric Noyaufce100702017-10-16 09:46:3439// In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
40// in favor of OS_LOG (Unified Logging).
41#include <AvailabilityMacros.h>
42#if defined(OS_IOS)
43#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
44#define USE_ASL
45#endif
46#else // !defined(OS_IOS)
47#if !defined(MAC_OS_X_VERSION_10_12) || \
48 MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
49#define USE_ASL
50#endif
51#endif // defined(OS_IOS)
52
53#if defined(USE_ASL)
mark4c7449c2015-11-10 19:53:4254#include <asl.h>
Eric Noyaufce100702017-10-16 09:46:3455#else
56#include <os/log.h>
57#endif
58
mark4c7449c2015-11-10 19:53:4259#include <CoreFoundation/CoreFoundation.h>
[email protected]f6abeba2008-08-08 13:27:2860#include <mach/mach.h>
61#include <mach/mach_time.h>
62#include <mach-o/dyld.h>
Eric Noyaufce100702017-10-16 09:46:3463
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3964#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]19ea84ca2010-11-12 08:37:0865#if defined(OS_NACL)
thestig75f87352014-12-03 21:42:2766#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0867#endif
[email protected]052f1b52008-11-06 21:43:0768#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5969#endif
70
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3971#if defined(OS_FUCHSIA)
Sharon Yanga4b908de2019-05-07 22:19:0372#include <lib/syslog/global.h>
73#include <lib/syslog/logger.h>
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3974#include <zircon/process.h>
75#include <zircon/syscalls.h>
76#endif
77
78#if defined(OS_ANDROID)
79#include <android/log.h>
80#endif
81
82#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:2083#include <errno.h>
mark4c7449c2015-11-10 19:53:4284#include <paths.h>
[email protected]f6abeba2008-08-08 13:27:2885#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0086#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2887#include <string.h>
mark4c7449c2015-11-10 19:53:4288#include <sys/stat.h>
Chris Findeisen2a373a2d2019-08-15 19:44:3089#include "base/process/process_handle.h"
[email protected]f6abeba2008-08-08 13:27:2890#define MAX_PATH PATH_MAX
91typedef FILE* FileHandle;
[email protected]f6abeba2008-08-08 13:27:2892#endif
93
[email protected]1f88b5162011-04-01 00:02:2994#include <algorithm>
95#include <cstring>
initial.commitd7cae122008-07-26 21:49:3896#include <ctime>
97#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2998#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0199#include <string>
alex-accc1bde62017-04-19 08:33:55100#include <utility>
[email protected]b16ef312008-08-19 18:36:23101
initial.commitd7cae122008-07-26 21:49:38102#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:55103#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:38104#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:28105#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:55106#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:05107#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:50108#include "base/debug/debugger.h"
109#include "base/debug/stack_trace.h"
Alan Cutter9b0e1ab2019-03-21 04:22:16110#include "base/debug/task_trace.h"
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45111#include "base/no_destructor.h"
Sharon Yanga4b908de2019-05-07 22:19:03112#include "base/path_service.h"
[email protected]2025d002012-11-14 20:54:35113#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:00114#include "base/strings/string_piece.h"
Xianzhu Wangae8d96a32018-10-16 20:41:13115#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:01116#include "base/strings/string_util.h"
117#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42118#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07119#include "base/strings/utf_string_conversions.h"
Benoit Lize5c98a832020-07-07 16:32:01120#include "base/synchronization/lock.h"
Yuta Hijikata9b7279a2020-08-26 16:10:54121#include "base/test/scoped_logging_settings.h"
[email protected]63e66802012-01-18 21:21:09122#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36123#include "base/vlog.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39124
Cliff Smolinskyc5c52102019-05-03 20:51:54125#if defined(OS_WIN)
126#include "base/win/win_util.h"
127#endif
128
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39129#if defined(OS_POSIX) || defined(OS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24130#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04131#endif
[email protected]52a261f2009-03-03 15:01:12132
Robbie McElrath8bf49842019-08-20 22:22:53133#if defined(OS_CHROMEOS)
134#include "base/files/scoped_file.h"
135#endif
136
initial.commitd7cae122008-07-26 21:49:38137namespace logging {
138
[email protected]064aa162011-12-03 00:30:08139namespace {
140
thestig3e4787d2015-05-19 19:31:52141VlogInfo* g_vlog_info = nullptr;
142VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:38143
weza245bd072017-06-18 23:26:34144const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
Avi Drissmane3b70bf2019-01-04 19:50:22145static_assert(LOG_NUM_SEVERITIES == base::size(log_severity_names),
weza245bd072017-06-18 23:26:34146 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38147
thestig75f87352014-12-03 21:42:27148const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:19149 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
150 return log_severity_names[severity];
151 return "UNKNOWN";
152}
153
thestig3e4787d2015-05-19 19:31:52154int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32155
Sharon Yang7cb919a2019-05-20 20:27:15156// Specifies the process' logging sink(s), represented as a combination of
157// LoggingDestination values joined by bitwise OR.
158int g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38159
Yuta Hijikata9b7279a2020-08-26 16:10:54160#if defined(OS_CHROMEOS)
Yuta Hijikata1fc8f6342020-09-01 03:25:56161// Specifies the format of log header for chrome os.
162LogFormat g_log_format = LogFormat::LOG_FORMAT_SYSLOG;
Yuta Hijikata9b7279a2020-08-26 16:10:54163#endif
164
[email protected]a33c9892008-08-25 20:10:31165// For LOG_ERROR and above, always print to stderr.
166const int kAlwaysPrintErrorLevel = LOG_ERROR;
167
[email protected]614e9fa2008-08-11 22:52:59168// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38169// will be lazily initialized to the default value when it is
170// first needed.
jdoerrie5c4dc4e2019-02-01 18:02:33171using PathString = base::FilePath::StringType;
thestig3e4787d2015-05-19 19:31:52172PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38173
thestig3e4787d2015-05-19 19:31:52174// This file is lazily opened and the handle may be nullptr
175FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38176
thestig3e4787d2015-05-19 19:31:52177// What should be prepended to each message?
178bool g_log_process_id = false;
179bool g_log_thread_id = false;
180bool g_log_timestamp = true;
181bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31182const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38183
[email protected]81e0a852010-08-17 00:38:12184// Should we pop up fatal debug messages in a dialog?
185bool show_error_dialogs = false;
186
initial.commitd7cae122008-07-26 21:49:38187// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55188// the debug message dialog and process termination. Assert handlers are stored
189// in stack to allow overriding and restoring.
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45190base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() {
191 static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance;
192 return *instance;
193}
alex-accc1bde62017-04-19 08:33:55194
[email protected]2b07b8412009-11-25 15:26:34195// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52196LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38197
avi9b6f42932015-12-26 22:15:14198uint64_t TickCount() {
[email protected]f8588472008-11-05 23:17:24199#if defined(OS_WIN)
200 return GetTickCount();
Wezb0501302018-03-09 05:18:45201#elif defined(OS_FUCHSIA)
Sharon Yang52c60992019-05-16 22:41:35202 return zx_clock_get_monotonic() /
Wezb0501302018-03-09 05:18:45203 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
Avi Drissman5b286372020-07-28 21:59:38204#elif defined(OS_APPLE)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39205 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08206#elif defined(OS_NACL)
207 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
208 // So we have to use clock() for now.
209 return clock();
[email protected]e43eddf12009-12-29 00:32:52210#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07211 struct timespec ts;
212 clock_gettime(CLOCK_MONOTONIC, &ts);
213
avi9b6f42932015-12-26 22:15:14214 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
215 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07216
217 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24218#endif
219}
220
[email protected]614e9fa2008-08-11 22:52:59221void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28222#if defined(OS_WIN)
Jan Wilken Dörrieb630aca2019-12-04 10:59:11223 DeleteFile(log_name.c_str());
thestig75f87352014-12-03 21:42:27224#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45225 // Do nothing; unlink() isn't supported on NaCl.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39226#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59227 unlink(log_name.c_str());
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39228#else
229#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28230#endif
231}
initial.commitd7cae122008-07-26 21:49:38232
[email protected]5f95d532010-10-01 17:16:58233PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55234#if defined(OS_WIN)
235 // On Windows we use the same path as the exe.
Jan Wilken Dörrieb630aca2019-12-04 10:59:11236 wchar_t module_name[MAX_PATH];
237 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58238
scottmgfc5b7072015-01-27 21:46:28239 PathString log_name = module_name;
240 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58241 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28242 log_name.erase(last_backslash + 1);
Jan Wilken Dörrieb630aca2019-12-04 10:59:11243 log_name += FILE_PATH_LITERAL("debug.log");
scottmgfc5b7072015-01-27 21:46:28244 return log_name;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39245#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55246 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58247 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55248#endif
249}
250
ananta61762fb2015-09-18 01:00:09251// We don't need locks on Windows for atomically appending to files. The OS
252// provides this functionality.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39253#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55254
Benoit Lize5c98a832020-07-07 16:32:01255base::Lock& GetLoggingLock() {
256 static base::NoDestructor<base::Lock> lock;
257 return *lock;
258}
[email protected]5b84fe32010-09-14 22:24:55259
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39260#endif // OS_POSIX || OS_FUCHSIA
ananta61762fb2015-09-18 01:00:09261
thestig3e4787d2015-05-19 19:31:52262// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38263// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52264// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38265bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52266 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38267 return true;
268
thestig3e4787d2015-05-19 19:31:52269 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59270 // Nobody has called InitLogging to specify a debug log file, so here we
271 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52272 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38273 }
274
Robbie McElrath8bf49842019-08-20 22:22:53275 if ((g_logging_destination & LOG_TO_FILE) == 0)
276 return true;
277
[email protected]614e9fa2008-08-11 22:52:59278#if defined(OS_WIN)
Robbie McElrath8bf49842019-08-20 22:22:53279 // The FILE_APPEND_DATA access mask ensures that the file is atomically
280 // appended to across accesses from multiple threads.
281 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
282 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
Jan Wilken Dörrieb630aca2019-12-04 10:59:11283 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
Robbie McElrath8bf49842019-08-20 22:22:53284 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
285 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
286 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
287 // We are intentionally not using FilePath or FileUtil here to reduce the
288 // dependencies of the logging implementation. For e.g. FilePath and
289 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
290 // some consumers of base logging like chrome_elf, etc.
291 // Please don't change the code below to use FilePath.
292 // try the current directory
Jan Wilken Dörrieb630aca2019-12-04 10:59:11293 wchar_t system_buffer[MAX_PATH];
Robbie McElrath8bf49842019-08-20 22:22:53294 system_buffer[0] = 0;
Jan Wilken Dörrieb630aca2019-12-04 10:59:11295 DWORD len = ::GetCurrentDirectory(base::size(system_buffer), system_buffer);
Robbie McElrath8bf49842019-08-20 22:22:53296 if (len == 0 || len > base::size(system_buffer))
297 return false;
298
299 *g_log_file_name = system_buffer;
300 // Append a trailing backslash if needed.
301 if (g_log_file_name->back() != L'\\')
Jan Wilken Dörrieb630aca2019-12-04 10:59:11302 *g_log_file_name += FILE_PATH_LITERAL("\\");
303 *g_log_file_name += FILE_PATH_LITERAL("debug.log");
Robbie McElrath8bf49842019-08-20 22:22:53304
Jan Wilken Dörrieb630aca2019-12-04 10:59:11305 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52306 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
307 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
308 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
Robbie McElrath8bf49842019-08-20 22:22:53309 g_log_file = nullptr;
[email protected]78c6dd62009-06-08 23:29:11310 return false;
Robbie McElrath8bf49842019-08-20 22:22:53311 }
312 }
313#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
314 g_log_file = fopen(g_log_file_name->c_str(), "a");
315 if (g_log_file == nullptr)
316 return false;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39317#else
318#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28319#endif
[email protected]1d8c2702008-08-19 23:39:32320
initial.commitd7cae122008-07-26 21:49:38321 return true;
322}
323
[email protected]17dcf752013-07-15 21:47:09324void CloseFile(FileHandle log) {
325#if defined(OS_WIN)
326 CloseHandle(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39327#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09328 fclose(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39329#else
330#error Unsupported platform
[email protected]17dcf752013-07-15 21:47:09331#endif
332}
333
334void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52335 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09336 return;
337
thestig3e4787d2015-05-19 19:31:52338 CloseFile(g_log_file);
339 g_log_file = nullptr;
Robbie McElrath8bf49842019-08-20 22:22:53340
341 // If we initialized logging via an externally-provided file descriptor, we
342 // won't have a log path set and shouldn't try to reopen the log file.
343 if (!g_log_file_name)
344 g_logging_destination &= ~LOG_TO_FILE;
[email protected]17dcf752013-07-15 21:47:09345}
346
[email protected]064aa162011-12-03 00:30:08347} // namespace
348
Tomas Popelaafffa972018-11-13 20:42:05349#if defined(DCHECK_IS_CONFIGURABLE)
Sigurdur Asgeirsson69d0bcd2018-03-29 21:50:51350// In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be
Wez289477f2017-08-24 20:51:30351// determined at run-time. We default it to INFO, to avoid it triggering
352// crashes before the run-time has explicitly chosen the behaviour.
353BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
Tomas Popelaafffa972018-11-13 20:42:05354#endif // defined(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30355
scottmg3c957a52016-12-10 20:57:59356// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
357// an object of the correct type on the LHS of the unused part of the ternary
358// operator.
359std::ostream* g_swallow_stream;
360
[email protected]5e3f7c22013-06-21 21:15:33361bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45362#if defined(OS_NACL)
Sharon Yang7cb919a2019-05-20 20:27:15363 // Can log only to the system debug log and stderr.
364 CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR),
365 0u);
[email protected]ac07ec52013-04-22 17:32:45366#endif
Robbie McElrath8bf49842019-08-20 22:22:53367
Yuta Hijikata8a93e522020-09-25 08:59:57368#if defined(OS_CHROMEOS)
369 g_log_format = settings.log_format;
370#endif
371
pgal.u-szeged421dddb2014-11-25 12:55:02372 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52373 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36374 // vlog switches.
375 if (command_line->HasSwitch(switches::kV) ||
376 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52377 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08378 // by another thread. Don't delete the old VLogInfo, just create a second
379 // one. We keep track of both to avoid memory leak warnings.
380 CHECK(!g_vlog_info_prev);
381 g_vlog_info_prev = g_vlog_info;
382
[email protected]99b7c57f2010-09-29 19:26:36383 g_vlog_info =
384 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49385 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52386 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36387 }
388
thestig3e4787d2015-05-19 19:31:52389 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38390
Wez224c0bf62019-05-24 19:26:13391#if defined(OS_FUCHSIA)
392 if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) {
393 fx_logger_config_t config;
394 config.min_severity = FX_LOG_INFO;
395 config.console_fd = -1;
396 config.log_service_channel = ZX_HANDLE_INVALID;
397 std::string log_tag = command_line->GetProgram().BaseName().AsUTF8Unsafe();
398 const char* log_tag_data = log_tag.data();
399 config.tags = &log_tag_data;
400 config.num_tags = 1;
Wez0e6cefc2020-04-21 18:04:47401 fx_log_reconfigure(&config);
Wez224c0bf62019-05-24 19:26:13402 }
403#endif
404
[email protected]5e3f7c22013-06-21 21:15:33405 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52406 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21407 return true;
initial.commitd7cae122008-07-26 21:49:38408
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39409#if defined(OS_POSIX) || defined(OS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:01410 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09411#endif
[email protected]17dcf752013-07-15 21:47:09412
413 // Calling InitLogging twice or after some log call has already opened the
414 // default log file will re-initialize to the new options.
415 CloseLogFileUnlocked();
416
Robbie McElrath8bf49842019-08-20 22:22:53417#if defined(OS_CHROMEOS)
418 if (settings.log_file) {
419 DCHECK(!settings.log_file_path);
420 g_log_file = settings.log_file;
421 return true;
422 }
423#endif
Xiaohan Wang5411974b2020-10-10 19:36:12424
425 DCHECK(settings.log_file_path) << "LOG_TO_FILE set but no log_file_path!";
Robbie McElrath8bf49842019-08-20 22:22:53426
thestig3e4787d2015-05-19 19:31:52427 if (!g_log_file_name)
428 g_log_file_name = new PathString();
Robbie McElrath8bf49842019-08-20 22:22:53429 *g_log_file_name = settings.log_file_path;
[email protected]5e3f7c22013-06-21 21:15:33430 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52431 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38432
[email protected]c7d5da992010-10-28 00:20:21433 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38434}
435
436void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52437 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38438}
439
440int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52441 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38442}
443
skobesc78c0ad72015-12-07 20:21:23444bool ShouldCreateLogMessage(int severity) {
445 if (severity < g_min_log_level)
446 return false;
447
Wez6c8acb82019-07-18 00:32:59448 // Return true here unless we know ~LogMessage won't do anything.
skobesc78c0ad72015-12-07 20:21:23449 return g_logging_destination != LOG_NONE || log_message_handler ||
450 severity >= kAlwaysPrintErrorLevel;
451}
452
Wez6c8acb82019-07-18 00:32:59453// Returns true when LOG_TO_STDERR flag is set, or |severity| is high.
454// If |severity| is high then true will be returned when no log destinations are
455// set, or only LOG_TO_FILE is set, since that is useful for local development
456// and debugging.
457bool ShouldLogToStderr(int severity) {
458 if (g_logging_destination & LOG_TO_STDERR)
459 return true;
460 if (severity >= kAlwaysPrintErrorLevel)
461 return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
462 return false;
463}
464
[email protected]162ac0f2010-11-04 15:50:49465int GetVlogVerbosity() {
466 return std::max(-1, LOG_INFO - GetMinLogLevel());
467}
468
[email protected]99b7c57f2010-09-29 19:26:36469int GetVlogLevelHelper(const char* file, size_t N) {
470 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52471 // Note: |g_vlog_info| may change on a different thread during startup
472 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08473 VlogInfo* vlog_info = g_vlog_info;
474 return vlog_info ?
475 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49476 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36477}
478
initial.commitd7cae122008-07-26 21:49:38479void SetLogItems(bool enable_process_id, bool enable_thread_id,
480 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52481 g_log_process_id = enable_process_id;
482 g_log_thread_id = enable_thread_id;
483 g_log_timestamp = enable_timestamp;
484 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38485}
486
James Cooka0536c32018-08-01 20:13:31487void SetLogPrefix(const char* prefix) {
488 DCHECK(!prefix ||
489 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
490 g_log_prefix = prefix;
491}
492
[email protected]81e0a852010-08-17 00:38:12493void SetShowErrorDialogs(bool enable_dialogs) {
494 show_error_dialogs = enable_dialogs;
495}
496
alex-accc1bde62017-04-19 08:33:55497ScopedLogAssertHandler::ScopedLogAssertHandler(
498 LogAssertHandlerFunction handler) {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45499 GetLogAssertHandlerStack().push(std::move(handler));
alex-accc1bde62017-04-19 08:33:55500}
501
502ScopedLogAssertHandler::~ScopedLogAssertHandler() {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45503 GetLogAssertHandlerStack().pop();
initial.commitd7cae122008-07-26 21:49:38504}
505
[email protected]2b07b8412009-11-25 15:26:34506void SetLogMessageHandler(LogMessageHandlerFunction handler) {
507 log_message_handler = handler;
508}
509
[email protected]64e5cc02010-11-03 19:20:27510LogMessageHandlerFunction GetLogMessageHandler() {
511 return log_message_handler;
512}
513
[email protected]f2c05492014-06-17 12:04:23514#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22515// Displays a message box to the user with the error message in it.
516// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25517// This is for developers only; we don't use this in circumstances
518// (like release builds) where users could see it, since users don't
519// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22520void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38521 if (str.empty())
522 return;
523
[email protected]81e0a852010-08-17 00:38:12524 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44525 return;
526
[email protected]f6abeba2008-08-08 13:27:28527#if defined(OS_WIN)
[email protected]561513f2010-12-16 23:29:25528 // We intentionally don't implement a dialog on other platforms.
529 // You can just look at stderr.
Cliff Smolinskyc5c52102019-05-03 20:51:54530 if (base::win::IsUser32AndGdi32Available()) {
531 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
532 MB_OK | MB_ICONHAND | MB_TOPMOST);
533 } else {
534 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
535 }
thestig3e4787d2015-05-19 19:31:52536#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38537}
[email protected]f2c05492014-06-17 12:04:23538#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38539
[email protected]eae9c062011-01-11 00:50:59540LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
541 : severity_(severity), file_(file), line_(line) {
542 Init(file, line);
543}
544
tnagel4a045d3f2015-07-12 14:19:28545LogMessage::LogMessage(const char* file, int line, const char* condition)
546 : severity_(LOG_FATAL), file_(file), line_(line) {
547 Init(file, line);
548 stream_ << "Check failed: " << condition << ". ";
549}
550
initial.commitd7cae122008-07-26 21:49:38551LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55552 size_t stack_start = stream_.tellp();
rayb0088ee52017-04-26 22:35:08553#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
554 !defined(OS_AIX)
brucedawson7c559eb2015-09-05 00:34:42555 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
556 // Include a stack trace on a fatal, unless a debugger is attached.
Alan Cutter9b0e1ab2019-03-21 04:22:16557 base::debug::StackTrace stack_trace;
[email protected]d1ccc35a2010-03-24 05:03:24558 stream_ << std::endl; // Newline to separate from log message.
Alan Cutter9b0e1ab2019-03-21 04:22:16559 stack_trace.OutputToStream(&stream_);
560 base::debug::TaskTrace task_trace;
561 if (!task_trace.empty())
562 task_trace.OutputToStream(&stream_);
Chris Hamilton306740d2019-04-25 18:48:36563
Chris Hamilton888085312019-05-30 00:53:30564 // Include the IPC context, if any.
565 // TODO(chrisha): Integrate with symbolization once those tools exist!
Chris Hamilton306740d2019-04-25 18:48:36566 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
Chris Hamilton888085312019-05-30 00:53:30567 if (task && task->ipc_hash) {
568 stream_ << "IPC message handler context: "
569 << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
Chris Hamilton306740d2019-04-25 18:48:36570 }
[email protected]d1ccc35a2010-03-24 05:03:24571 }
[email protected]1d8c2702008-08-19 23:39:32572#endif
[email protected]d1ccc35a2010-03-24 05:03:24573 stream_ << std::endl;
574 std::string str_newline(stream_.str());
Nicolò Mazzucato6c278d9b2019-08-02 16:25:44575 TRACE_LOG_MESSAGE(
576 file_, base::StringPiece(str_newline).substr(message_start_), line_);
[email protected]d1ccc35a2010-03-24 05:03:24577
[email protected]2b07b8412009-11-25 15:26:34578 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33579 if (log_message_handler &&
580 log_message_handler(severity_, file_, line_,
581 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49582 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34583 return;
[email protected]162ac0f2010-11-04 15:50:49584 }
initial.commitd7cae122008-07-26 21:49:38585
thestig3e4787d2015-05-19 19:31:52586 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28587#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38588 OutputDebugStringA(str_newline.c_str());
Avi Drissman5b286372020-07-28 21:59:38589#elif defined(OS_APPLE)
mark4c7449c2015-11-10 19:53:42590 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Eric Noyaufce100702017-10-16 09:46:34591 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
592 // its successor OS_LOG. If there's something weird about stderr, assume
593 // that log messages are going nowhere and log via ASL/OS_LOG too.
594 // Messages logged via ASL/OS_LOG show up in Console.app.
mark4c7449c2015-11-10 19:53:42595 //
596 // Programs started by launchd, as UI applications normally are, have had
597 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
598 // a pipe to launchd, which logged what it received (see log_redirect_fd in
599 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
600 //
601 // Another alternative would be to determine whether stderr is a pipe to
602 // launchd and avoid logging via ASL only in that case. See 10.7.5
603 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Eric Noyaufce100702017-10-16 09:46:34604 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
605 // to the system log at all.
mark4c7449c2015-11-10 19:53:42606 //
607 // Note that the ASL client by default discards messages whose levels are
608 // below ASL_LEVEL_NOTICE. It's possible to change that with
609 // asl_set_filter(), but this is pointless because syslogd normally applies
610 // the same filter.
Eric Noyaufce100702017-10-16 09:46:34611 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42612 struct stat stderr_stat;
613 if (fstat(fileno(stderr), &stderr_stat) == -1) {
614 return true;
615 }
616 if (!S_ISCHR(stderr_stat.st_mode)) {
617 return false;
618 }
619
620 struct stat dev_null_stat;
621 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
622 return true;
623 }
624
625 return !S_ISCHR(dev_null_stat.st_mode) ||
626 stderr_stat.st_rdev == dev_null_stat.st_rdev;
627 }();
628
Eric Noyaufce100702017-10-16 09:46:34629 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42630 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
631 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42632 CFBundleRef main_bundle = CFBundleGetMainBundle();
633 CFStringRef main_bundle_id_cf =
634 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34635 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42636 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34637 : std::string("");
638#if defined(USE_ASL)
639 // The facility is set to the main bundle ID if available. Otherwise,
640 // "com.apple.console" is used.
641 const class ASLClient {
mark4c7449c2015-11-10 19:53:42642 public:
Bruce Dawson4c6f8e12017-11-16 04:35:59643 explicit ASLClient(const std::string& facility)
644 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
David Bienvenub4b441e2020-09-23 05:49:57645 ASLClient(const ASLClient&) = delete;
646 ASLClient& operator=(const ASLClient&) = delete;
mark4c7449c2015-11-10 19:53:42647 ~ASLClient() { asl_close(client_); }
648
649 aslclient get() const { return client_; }
650
651 private:
652 aslclient client_;
Eric Noyaufce100702017-10-16 09:46:34653 } asl_client(main_bundle_id.empty() ? main_bundle_id
654 : "com.apple.console");
mark4c7449c2015-11-10 19:53:42655
Eric Noyaufce100702017-10-16 09:46:34656 const class ASLMessage {
mark4c7449c2015-11-10 19:53:42657 public:
658 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
David Bienvenub4b441e2020-09-23 05:49:57659 ASLMessage(const ASLMessage&) = delete;
660 ASLMessage& operator=(const ASLMessage&) = delete;
mark4c7449c2015-11-10 19:53:42661 ~ASLMessage() { asl_free(message_); }
662
663 aslmsg get() const { return message_; }
664
665 private:
666 aslmsg message_;
mark4c7449c2015-11-10 19:53:42667 } asl_message;
668
669 // By default, messages are only readable by the admin group. Explicitly
670 // make them readable by the user generating the messages.
671 char euid_string[12];
Avi Drissmane3b70bf2019-01-04 19:50:22672 snprintf(euid_string, base::size(euid_string), "%d", geteuid());
mark4c7449c2015-11-10 19:53:42673 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
674
675 // Map Chrome log severities to ASL log levels.
676 const char* const asl_level_string = [](LogSeverity severity) {
677 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
678 // non-obvious two-step macro trick achieves what's needed.
679 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
680#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
681#define ASL_LEVEL_STR_X(level) #level
682 switch (severity) {
683 case LOG_INFO:
684 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
685 case LOG_WARNING:
686 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
687 case LOG_ERROR:
688 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
689 case LOG_FATAL:
690 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
691 default:
692 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
693 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
694 }
695#undef ASL_LEVEL_STR
696#undef ASL_LEVEL_STR_X
697 }(severity_);
698 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
699
700 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
701
702 asl_send(asl_client.get(), asl_message.get());
Eric Noyaufce100702017-10-16 09:46:34703#else // !defined(USE_ASL)
704 const class OSLog {
705 public:
706 explicit OSLog(const char* subsystem)
707 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
708 : OS_LOG_DEFAULT) {}
David Bienvenub4b441e2020-09-23 05:49:57709 OSLog(const OSLog&) = delete;
710 OSLog& operator=(const OSLog&) = delete;
Eric Noyaufce100702017-10-16 09:46:34711 ~OSLog() {
712 if (os_log_ != OS_LOG_DEFAULT) {
713 os_release(os_log_);
714 }
715 }
716 os_log_t get() const { return os_log_; }
717
718 private:
719 os_log_t os_log_;
Eric Noyaufce100702017-10-16 09:46:34720 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
721 const os_log_type_t os_log_type = [](LogSeverity severity) {
722 switch (severity) {
723 case LOG_INFO:
724 return OS_LOG_TYPE_INFO;
725 case LOG_WARNING:
726 return OS_LOG_TYPE_DEFAULT;
727 case LOG_ERROR:
728 return OS_LOG_TYPE_ERROR;
729 case LOG_FATAL:
730 return OS_LOG_TYPE_FAULT;
731 default:
732 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
733 }
734 }(severity_);
735 os_log_with_type(log.get(), os_log_type, "%{public}s",
736 str_newline.c_str());
737#endif // defined(USE_ASL)
mark4c7449c2015-11-10 19:53:42738 }
[email protected]3132e35c2011-07-07 20:46:50739#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25740 android_LogPriority priority =
741 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50742 switch (severity_) {
743 case LOG_INFO:
744 priority = ANDROID_LOG_INFO;
745 break;
746 case LOG_WARNING:
747 priority = ANDROID_LOG_WARN;
748 break;
749 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50750 priority = ANDROID_LOG_ERROR;
751 break;
752 case LOG_FATAL:
753 priority = ANDROID_LOG_FATAL;
754 break;
755 }
Tomasz Śniatowski23dd15af2019-02-15 08:32:03756 const char kAndroidLogTag[] = "chromium";
Xianzhu Wangae8d96a32018-10-16 20:41:13757#if DCHECK_IS_ON()
758 // Split the output by new lines to prevent the Android system from
759 // truncating the log.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03760 std::vector<std::string> lines = base::SplitString(
761 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
762 // str_newline has an extra newline appended to it (at the top of this
763 // function), so skip the last split element to avoid needlessly
764 // logging an empty string.
765 lines.pop_back();
766 for (const auto& line : lines)
767 __android_log_write(priority, kAndroidLogTag, line.c_str());
Xianzhu Wangae8d96a32018-10-16 20:41:13768#else
769 // The Android system may truncate the string if it's too long.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03770 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18771#endif
Sharon Yanga4b908de2019-05-07 22:19:03772#elif defined(OS_FUCHSIA)
773 fx_log_severity_t severity = FX_LOG_INFO;
Wez224c0bf62019-05-24 19:26:13774 switch (severity_) {
Sharon Yanga4b908de2019-05-07 22:19:03775 case LOG_INFO:
776 severity = FX_LOG_INFO;
777 break;
778 case LOG_WARNING:
779 severity = FX_LOG_WARNING;
780 break;
781 case LOG_ERROR:
782 severity = FX_LOG_ERROR;
783 break;
784 case LOG_FATAL:
Wez224c0bf62019-05-24 19:26:13785 // Don't use FX_LOG_FATAL, otherwise fx_logger_log() will abort().
786 severity = FX_LOG_ERROR;
Sharon Yanga4b908de2019-05-07 22:19:03787 break;
788 }
789
790 fx_logger_t* logger = fx_log_get_logger();
791 if (logger) {
Kevin Marshall9873826d2019-10-14 20:09:35792 // Temporarily remove the trailing newline from |str_newline|'s C-string
793 // representation, since fx_logger will add a newline of its own.
Wez224c0bf62019-05-24 19:26:13794 str_newline.pop_back();
Kevin Marshall9873826d2019-10-14 20:09:35795 std::string message =
796 base::StringPrintf("%s(%d) %s", file_basename_, line_,
797 str_newline.c_str() + message_start_);
798 fx_logger_log(logger, severity, nullptr, message.data());
Wez224c0bf62019-05-24 19:26:13799 str_newline.push_back('\n');
Sharon Yanga4b908de2019-05-07 22:19:03800 }
801#endif // OS_FUCHSIA
Sharon Yang7cb919a2019-05-20 20:27:15802 }
803
Wez6c8acb82019-07-18 00:32:59804 if (ShouldLogToStderr(severity_)) {
[email protected]51105382014-03-14 17:02:15805 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02806 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28807 }
[email protected]52a261f2009-03-03 15:01:12808
thestig3e4787d2015-05-19 19:31:52809 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09810 // We can have multiple threads and/or processes, so try to prevent them
811 // from clobbering each other's writes.
812 // If the client app did not call InitLogging, and the lock has not
813 // been created do it now. We do this on demand, but if two threads try
814 // to do this at the same time, there will be a race condition to create
815 // the lock. This is why InitLogging should be called from the main
816 // thread at the beginning of execution.
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39817#if defined(OS_POSIX) || defined(OS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:01818 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09819#endif
[email protected]5b84fe32010-09-14 22:24:55820 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28821#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55822 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52823 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55824 static_cast<const void*>(str_newline.c_str()),
825 static_cast<DWORD>(str_newline.length()),
826 &num_written,
thestig3e4787d2015-05-19 19:31:52827 nullptr);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39828#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]51105382014-03-14 17:02:15829 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52830 str_newline.data(), str_newline.size(), 1, g_log_file));
831 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39832#else
833#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55834#endif
initial.commitd7cae122008-07-26 21:49:38835 }
836 }
837
838 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40839 // Write the log message to the global activity tracker, if running.
840 base::debug::GlobalActivityTracker* tracker =
841 base::debug::GlobalActivityTracker::Get();
842 if (tracker)
843 tracker->RecordLogMessage(str_newline);
844
Wezd78fee62020-09-11 18:29:14845 char str_stack[1024];
846 base::strlcpy(str_stack, str_newline.data(), base::size(str_stack));
Weze976b732018-10-20 03:37:31847 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05848
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45849 if (!GetLogAssertHandlerStack().empty()) {
alex-accc1bde62017-04-19 08:33:55850 LogAssertHandlerFunction log_assert_handler =
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45851 GetLogAssertHandlerStack().top();
alex-accc1bde62017-04-19 08:33:55852
853 if (log_assert_handler) {
854 log_assert_handler.Run(
855 file_, line_,
856 base::StringPiece(str_newline.c_str() + message_start_,
857 stack_start - message_start_),
858 base::StringPiece(str_newline.c_str() + stack_start));
859 }
[email protected]1ffe08c12008-08-13 11:15:11860 } else {
[email protected]82d89ab2014-02-28 18:25:34861 // Don't use the string with the newline, get a fresh version to send to
862 // the debug message process. We also don't display assertions to the
863 // user in release mode. The enduser can't do anything with this
864 // information, and displaying message boxes when the application is
865 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50866#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42867 if (!base::debug::BeingDebugged()) {
868 // Displaying a dialog is unnecessary when debugging and can complicate
869 // debugging.
870 DisplayDebugMessageInDialog(stream_.str());
871 }
[email protected]4d5901272008-11-06 00:33:50872#endif
[email protected]82d89ab2014-02-28 18:25:34873 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52874#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
875 IMMEDIATE_CRASH();
876#else
[email protected]82d89ab2014-02-28 18:25:34877 base::debug::BreakDebugger();
Torne (Richard Coles)54b86796a62018-07-24 14:59:52878#endif
initial.commitd7cae122008-07-26 21:49:38879 }
880 }
881}
882
[email protected]eae9c062011-01-11 00:50:59883// writes the common header info to the stream
884void LogMessage::Init(const char* file, int line) {
885 base::StringPiece filename(file);
886 size_t last_slash_pos = filename.find_last_of("\\/");
887 if (last_slash_pos != base::StringPiece::npos)
888 filename.remove_prefix(last_slash_pos + 1);
889
Kevin Marshall9873826d2019-10-14 20:09:35890 // Stores the base name as the null-terminated suffix substring of |filename|.
891 file_basename_ = filename.data();
892
Yuta Hijikata9b7279a2020-08-26 16:10:54893#if defined(OS_CHROMEOS)
894 if (g_log_format == LogFormat::LOG_FORMAT_SYSLOG) {
895 InitWithSyslogPrefix(
896 filename, line, TickCount(), log_severity_name(severity_), g_log_prefix,
897 g_log_process_id, g_log_thread_id, g_log_timestamp, g_log_tickcount);
898 } else
899#endif // defined(OS_CHROMEOS)
900 {
901 // TODO(darin): It might be nice if the columns were fixed width.
902 stream_ << '[';
903 if (g_log_prefix)
904 stream_ << g_log_prefix << ':';
905 if (g_log_process_id)
906 stream_ << base::GetUniqueIdForProcess() << ':';
907 if (g_log_thread_id)
908 stream_ << base::PlatformThread::CurrentId() << ':';
909 if (g_log_timestamp) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39910#if defined(OS_WIN)
Yuta Hijikata9b7279a2020-08-26 16:10:54911 SYSTEMTIME local_time;
912 GetLocalTime(&local_time);
913 stream_ << std::setfill('0')
914 << std::setw(2) << local_time.wMonth
915 << std::setw(2) << local_time.wDay
916 << '/'
917 << std::setw(2) << local_time.wHour
918 << std::setw(2) << local_time.wMinute
919 << std::setw(2) << local_time.wSecond
920 << '.'
921 << std::setw(3) << local_time.wMilliseconds
922 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39923#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Yuta Hijikata9b7279a2020-08-26 16:10:54924 timeval tv;
925 gettimeofday(&tv, nullptr);
926 time_t t = tv.tv_sec;
927 struct tm local_time;
928 localtime_r(&t, &local_time);
929 struct tm* tm_time = &local_time;
930 stream_ << std::setfill('0')
931 << std::setw(2) << 1 + tm_time->tm_mon
932 << std::setw(2) << tm_time->tm_mday
933 << '/'
934 << std::setw(2) << tm_time->tm_hour
935 << std::setw(2) << tm_time->tm_min
936 << std::setw(2) << tm_time->tm_sec
937 << '.'
938 << std::setw(6) << tv.tv_usec
939 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39940#else
941#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:34942#endif
Yuta Hijikata9b7279a2020-08-26 16:10:54943 }
944 if (g_log_tickcount)
945 stream_ << TickCount() << ':';
946 if (severity_ >= 0) {
947 stream_ << log_severity_name(severity_);
948 } else {
949 stream_ << "VERBOSE" << -severity_;
950 }
951 stream_ << ":" << filename << "(" << line << ")] ";
[email protected]eae9c062011-01-11 00:50:59952 }
pkasting9cf9b94a2014-10-01 22:18:43953 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59954}
955
[email protected]d8617a62009-10-09 23:52:20956#if defined(OS_WIN)
957// This has already been defined in the header, but defining it again as DWORD
958// ensures that the type used in the header is equivalent to DWORD. If not,
959// the redefinition is a compile error.
960typedef DWORD SystemErrorCode;
961#endif
962
963SystemErrorCode GetLastSystemErrorCode() {
964#if defined(OS_WIN)
965 return ::GetLastError();
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39966#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:20967 return errno;
[email protected]d8617a62009-10-09 23:52:20968#endif
969}
970
[email protected]c914d8a2014-04-23 01:11:01971BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39972#if defined(OS_WIN)
thestig75f87352014-12-03 21:42:27973 const int kErrorMessageBufferSize = 256;
974 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:01975 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:52976 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Avi Drissmane3b70bf2019-01-04 19:50:22977 base::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:01978 if (len) {
979 // Messages returned by system end with line breaks.
980 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:45981 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:01982 }
Bruce Dawson19175842017-08-02 17:00:45983 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:01984 GetLastError(), error_code);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39985#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:14986 return base::safe_strerror(error_code) +
987 base::StringPrintf(" (%d)", error_code);
thestig3e4787d2015-05-19 19:31:52988#endif // defined(OS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39989}
[email protected]d8617a62009-10-09 23:52:20990
[email protected]c914d8a2014-04-23 01:11:01991
992#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20993Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
994 int line,
995 LogSeverity severity,
996 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:00997 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:20998
999Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011000 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:061001 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1002 // field) and use Alias in hopes that it makes it into crash dumps.
1003 DWORD last_error = err_;
1004 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201005}
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391006#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201007ErrnoLogMessage::ErrnoLogMessage(const char* file,
1008 int line,
1009 LogSeverity severity,
1010 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001011 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201012
1013ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011014 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141015 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1016 // field) and use Alias in hopes that it makes it into crash dumps.
1017 int last_error = err_;
1018 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201019}
thestig3e4787d2015-05-19 19:31:521020#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:201021
initial.commitd7cae122008-07-26 21:49:381022void CloseLogFile() {
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391023#if defined(OS_POSIX) || defined(OS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:011024 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:091025#endif
[email protected]17dcf752013-07-15 21:47:091026 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381027}
1028
Robbie McElrath8bf49842019-08-20 22:22:531029#if defined(OS_CHROMEOS)
1030FILE* DuplicateLogFILE() {
1031 if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle())
1032 return nullptr;
1033
1034 int log_fd = fileno(g_log_file);
1035 if (log_fd == -1)
1036 return nullptr;
1037 base::ScopedFD dup_fd(dup(log_fd));
1038 if (dup_fd == -1)
1039 return nullptr;
1040 FILE* duplicate = fdopen(dup_fd.get(), "a");
1041 if (!duplicate)
1042 return nullptr;
1043 ignore_result(dup_fd.release());
1044 return duplicate;
1045}
1046#endif
1047
Yuta Hijikata9b7279a2020-08-26 16:10:541048// Used for testing. Declared in test/scoped_logging_settings.h.
1049ScopedLoggingSettings::ScopedLoggingSettings()
1050 : enable_process_id_(g_log_process_id),
1051 enable_thread_id_(g_log_thread_id),
1052 enable_timestamp_(g_log_timestamp),
1053 enable_tickcount_(g_log_tickcount),
1054 min_log_level_(GetMinLogLevel()),
1055 message_handler_(GetLogMessageHandler()) {
1056#if defined(OS_CHROMEOS)
1057 log_format_ = g_log_format;
1058#endif // defined(OS_CHROMEOS)
1059}
1060
1061ScopedLoggingSettings::~ScopedLoggingSettings() {
1062 g_log_process_id = enable_process_id_;
1063 g_log_thread_id = enable_thread_id_;
1064 g_log_timestamp = enable_timestamp_;
1065 g_log_tickcount = enable_tickcount_;
1066 SetMinLogLevel(min_log_level_);
1067 SetLogMessageHandler(message_handler_);
1068
1069#if defined(OS_CHROMEOS)
1070 g_log_format = log_format_;
1071#endif // defined(OS_CHROMEOS)
1072}
1073
1074#if defined(OS_CHROMEOS)
1075void ScopedLoggingSettings::SetLogFormat(LogFormat log_format) const {
1076 g_log_format = log_format;
1077}
1078#endif // defined(OS_CHROMEOS)
1079
[email protected]e36ddc82009-12-08 04:22:501080void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491081 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501082 size_t bytes_written = 0;
1083 const size_t message_len = strlen(message);
1084 int rv;
1085 while (bytes_written < message_len) {
1086 rv = HANDLE_EINTR(
1087 write(STDERR_FILENO, message + bytes_written,
1088 message_len - bytes_written));
1089 if (rv < 0) {
1090 // Give up, nothing we can do now.
1091 break;
1092 }
1093 bytes_written += rv;
1094 }
1095
1096 if (message_len > 0 && message[message_len - 1] != '\n') {
1097 do {
1098 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1099 if (rv < 0) {
1100 // Give up, nothing we can do now.
1101 break;
1102 }
1103 } while (rv != 1);
1104 }
1105 }
1106
1107 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:501108 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:501109}
1110
[email protected]34a907732012-01-20 06:33:271111// This was defined at the beginning of this file.
1112#undef write
1113
[email protected]f01b88a2013-02-27 22:04:001114#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:091115bool IsLoggingToFileEnabled() {
1116 return g_logging_destination & LOG_TO_FILE;
1117}
1118
Jan Wilken Dörrieb630aca2019-12-04 10:59:111119std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521120 if (g_log_file_name)
1121 return *g_log_file_name;
Jan Wilken Dörrieb630aca2019-12-04 10:59:111122 return std::wstring();
[email protected]f01b88a2013-02-27 22:04:001123}
1124#endif
1125
[email protected]96fd0032009-04-24 00:13:081126} // namespace logging
initial.commitd7cae122008-07-26 21:49:381127
[email protected]81411c62014-07-08 23:03:061128std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:491129 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:381130}