blob: e69cad5e5577f7126944067c1c563666a7aab4ac [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"
Hans Wennborg12aea3e2020-04-14 15:29:006
Hans Wennborg944479f2020-06-25 21:39:257#ifdef BASE_CHECK_H_
8#error "logging.h should not include check.h"
9#endif
10
avi51ba3e692015-12-26 17:30:5011#include <limits.h>
avi9b6f42932015-12-26 22:15:1412#include <stdint.h>
13
Hans Wennborged2126e2022-08-02 14:44:5814#include <atomic>
15#include <memory>
Avi Drissman933398e2022-01-22 00:55:4216#include <tuple>
David Bienvenub4b441e2020-09-23 05:49:5717#include <vector>
18
David Sanders6e709942022-04-05 06:49:2619#include "base/base_export.h"
Lukasz Anforowicz872567d2021-09-08 19:49:2220#include "base/debug/crash_logging.h"
Kalvin Lee70699ccd2022-04-28 17:27:3621#include "base/immediate_crash.h"
Chris Hamilton306740d2019-04-25 18:48:3622#include "base/pending_task.h"
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:3923#include "base/strings/string_piece.h"
Chris Hamilton306740d2019-04-25 18:48:3624#include "base/task/common/task_annotator.h"
Eric Secklerf6c544f2020-06-02 10:49:2125#include "base/trace_event/base_tracing.h"
avi9b6f42932015-12-26 22:15:1426#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5027
Peter Boström871f916a2022-08-09 22:36:2728#if !BUILDFLAG(IS_NACL)
29#include "base/auto_reset.h"
30#include "base/debug/crash_logging.h"
31#endif // !BUILDFLAG(IS_NACL)
32
Hans Wennborged2126e2022-08-02 14:44:5833#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
34#include "base/debug/leak_annotations.h"
35#endif // defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
36
Xiaohan Wang38e4ebb2022-01-19 06:57:4337#if BUILDFLAG(IS_WIN)
[email protected]e36ddc82009-12-08 04:22:5038#include <io.h>
alex-accc1bde62017-04-19 08:33:5539#include <windows.h>
[email protected]f6abeba2008-08-08 13:27:2840typedef HANDLE FileHandle;
[email protected]e36ddc82009-12-08 04:22:5041// Windows warns on using write(). It prefers _write().
42#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
43// Windows doesn't define STDERR_FILENO. Define it here.
44#define STDERR_FILENO 2
Eric Noyaufce100702017-10-16 09:46:3445
Xiaohan Wang38e4ebb2022-01-19 06:57:4346#elif BUILDFLAG(IS_APPLE)
mark4c7449c2015-11-10 19:53:4247#include <CoreFoundation/CoreFoundation.h>
Avi Drissmanba195b32022-05-19 02:53:3448#include <mach-o/dyld.h>
[email protected]f6abeba2008-08-08 13:27:2849#include <mach/mach.h>
50#include <mach/mach_time.h>
Avi Drissmanba195b32022-05-19 02:53:3451#include <os/log.h>
Eric Noyaufce100702017-10-16 09:46:3452
Xiaohan Wang38e4ebb2022-01-19 06:57:4353#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
54#if BUILDFLAG(IS_NACL)
thestig75f87352014-12-03 21:42:2755#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0856#endif
[email protected]052f1b52008-11-06 21:43:0757#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5958#endif
59
Xiaohan Wang38e4ebb2022-01-19 06:57:4360#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:0261#include "base/fuchsia/scoped_fx_logger.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3962#endif
63
Xiaohan Wang38e4ebb2022-01-19 06:57:4364#if BUILDFLAG(IS_ANDROID)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3965#include <android/log.h>
66#endif
67
Xiaohan Wang38e4ebb2022-01-19 06:57:4368#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:2069#include <errno.h>
mark4c7449c2015-11-10 19:53:4270#include <paths.h>
[email protected]f6abeba2008-08-08 13:27:2871#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0072#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2873#include <string.h>
mark4c7449c2015-11-10 19:53:4274#include <sys/stat.h>
Chris Findeisen2a373a2d2019-08-15 19:44:3075#include "base/process/process_handle.h"
[email protected]f6abeba2008-08-08 13:27:2876#define MAX_PATH PATH_MAX
77typedef FILE* FileHandle;
[email protected]f6abeba2008-08-08 13:27:2878#endif
79
[email protected]1f88b5162011-04-01 00:02:2980#include <algorithm>
81#include <cstring>
initial.commitd7cae122008-07-26 21:49:3882#include <ctime>
83#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2984#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0185#include <string>
alex-accc1bde62017-04-19 08:33:5586#include <utility>
[email protected]b16ef312008-08-19 18:36:2387
initial.commitd7cae122008-07-26 21:49:3888#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:5589#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:3890#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:2891#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:5592#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:0593#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5094#include "base/debug/debugger.h"
95#include "base/debug/stack_trace.h"
Alan Cutter9b0e1ab2019-03-21 04:22:1696#include "base/debug/task_trace.h"
Yannic Bonenberger3dcd7fe2019-06-08 11:01:4597#include "base/no_destructor.h"
Sharon Yanga4b908de2019-05-07 22:19:0398#include "base/path_service.h"
[email protected]2025d002012-11-14 20:54:3599#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:00100#include "base/strings/string_piece.h"
Xianzhu Wangae8d96a32018-10-16 20:41:13101#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:01102#include "base/strings/string_util.h"
103#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42104#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07105#include "base/strings/utf_string_conversions.h"
Benoit Lize5c98a832020-07-07 16:32:01106#include "base/synchronization/lock.h"
Yuta Hijikata9b7279a2020-08-26 16:10:54107#include "base/test/scoped_logging_settings.h"
[email protected]63e66802012-01-18 21:21:09108#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36109#include "base/vlog.h"
Yuta Hijikata000df18f2020-11-18 06:55:58110#include "build/chromeos_buildflags.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39111
Xiaohan Wang38e4ebb2022-01-19 06:57:43112#if BUILDFLAG(IS_WIN)
Cliff Smolinskyc5c52102019-05-03 20:51:54113#include "base/win/win_util.h"
114#endif
115
Xiaohan Wang38e4ebb2022-01-19 06:57:43116#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24117#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04118#endif
[email protected]52a261f2009-03-03 15:01:12119
Yuta Hijikata000df18f2020-11-18 06:55:58120#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:53121#include "base/files/scoped_file.h"
122#endif
123
initial.commitd7cae122008-07-26 21:49:38124namespace logging {
125
[email protected]064aa162011-12-03 00:30:08126namespace {
127
Fergal Dalyfacfaf92022-06-02 04:47:55128int g_min_log_level = 0;
129
Xiyuan Xiaa0559da2022-05-05 19:42:45130#if BUILDFLAG(USE_RUNTIME_VLOG)
Fergal Dalycac6ddc2022-05-24 17:42:03131// NOTE: Once |g_vlog_info| has been initialized, it might be in use
132// by another thread. Never delete the old VLogInfo, just create a second
133// one and overwrite. We need to use leak-san annotations on this intentional
134// leak.
135//
136// This can be read/written on multiple threads. In tests we don't see that
137// causing a problem as updates tend to happen early. Atomic ensures there are
138// no problems. To avoid some of the overhead of Atomic, we use
139// |load(std::memory_order_acquire)| and |store(...,
Fergal Daly432aa7c2022-06-14 07:30:54140// std::memory_order_release)| when reading or writing. This guarantees that the
141// referenced object is available at the time the |g_vlog_info| is read and that
142// |g_vlog_info| is updated atomically.
143//
144// Do not access this directly. You must use |GetVlogInfo|, |InitializeVlogInfo|
145// and/or |ExchangeVlogInfo|.
Fergal Dalycac6ddc2022-05-24 17:42:03146std::atomic<VlogInfo*> g_vlog_info = nullptr;
Fergal Dalyfacfaf92022-06-02 04:47:55147
Fergal Daly432aa7c2022-06-14 07:30:54148VlogInfo* GetVlogInfo() {
149 return g_vlog_info.load(std::memory_order_acquire);
150}
151
152// Sets g_vlog_info if it is not already set. Checking that it's not already set
153// prevents logging initialization (which can come late in test setup) from
154// overwriting values set via ScopedVmoduleSwitches.
155bool InitializeVlogInfo(VlogInfo* vlog_info) {
156 VlogInfo* previous_vlog_info = nullptr;
157 return g_vlog_info.compare_exchange_strong(previous_vlog_info, vlog_info);
158}
159
160VlogInfo* ExchangeVlogInfo(VlogInfo* vlog_info) {
161 return g_vlog_info.exchange(vlog_info);
162}
163
Fergal Dalyfacfaf92022-06-02 04:47:55164// Creates a VlogInfo from the commandline if it has been initialized and if it
165// contains relevant switches, otherwise this returns |nullptr|.
Fergal Daly432aa7c2022-06-14 07:30:54166std::unique_ptr<VlogInfo> VlogInfoFromCommandLine() {
Fergal Dalyfacfaf92022-06-02 04:47:55167 if (!base::CommandLine::InitializedForCurrentProcess())
168 return nullptr;
169 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
170 if (!command_line->HasSwitch(switches::kV) &&
171 !command_line->HasSwitch(switches::kVModule)) {
172 return nullptr;
173 }
174#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
175 // See comments on |g_vlog_info|.
176 ScopedLeakSanitizerDisabler lsan_disabler;
177#endif // defined(LEAK_SANITIZER)
Fergal Daly432aa7c2022-06-14 07:30:54178 return std::make_unique<VlogInfo>(
179 command_line->GetSwitchValueASCII(switches::kV),
180 command_line->GetSwitchValueASCII(switches::kVModule), &g_min_log_level);
181}
182
183// If the commandline is initialized for the current process this will
184// initialize g_vlog_info. If there are no VLOG switches, it will initialize it
185// to |nullptr|.
186void MaybeInitializeVlogInfo() {
187 if (base::CommandLine::InitializedForCurrentProcess()) {
188 std::unique_ptr<VlogInfo> vlog_info = VlogInfoFromCommandLine();
189 if (vlog_info) {
190 // VlogInfoFromCommandLine is annotated with ScopedLeakSanitizerDisabler
191 // so it's allowed to leak. If the object was installed, we release it.
192 if (InitializeVlogInfo(vlog_info.get())) {
193 vlog_info.release();
194 }
195 }
196 }
Fergal Dalyfacfaf92022-06-02 04:47:55197}
Xiyuan Xiaa0559da2022-05-05 19:42:45198#endif // BUILDFLAG(USE_RUNTIME_VLOG)
initial.commitd7cae122008-07-26 21:49:38199
Jeffrey Young551bce62022-06-24 19:08:17200#if !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
201
202// Warn developers that vlog command line settings are being ignored.
203void MaybeWarnVmodule() {
204 if (base::CommandLine::InitializedForCurrentProcess()) {
205 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
206 if (command_line->HasSwitch(switches::kV) ||
207 command_line->HasSwitch(switches::kVModule)) {
208 LOG(WARNING)
209 << "--" << switches::kV << " and --" << switches::kVModule
210 << " are currently ignored. See comments in base/logging.h on "
211 "proper usage of USE_RUNTIME_VLOG.";
212 }
213 }
214}
215
216#endif // !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
217
weza245bd072017-06-18 23:26:34218const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
Daniel Chengf45f47602022-02-28 22:38:32219static_assert(LOGGING_NUM_SEVERITIES == std::size(log_severity_names),
weza245bd072017-06-18 23:26:34220 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38221
thestig75f87352014-12-03 21:42:27222const char* log_severity_name(int severity) {
Lei Zhang93dd42572020-10-23 18:45:53223 if (severity >= 0 && severity < LOGGING_NUM_SEVERITIES)
[email protected]80f360a2014-01-23 01:36:19224 return log_severity_names[severity];
225 return "UNKNOWN";
226}
227
Sharon Yang7cb919a2019-05-20 20:27:15228// Specifies the process' logging sink(s), represented as a combination of
229// LoggingDestination values joined by bitwise OR.
Peter Kasting40cfeae2021-06-14 12:21:48230uint32_t g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38231
Georg Neisffe34f652021-12-27 21:42:36232#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata1fc8f6342020-09-01 03:25:56233// Specifies the format of log header for chrome os.
234LogFormat g_log_format = LogFormat::LOG_FORMAT_SYSLOG;
Yuta Hijikata9b7279a2020-08-26 16:10:54235#endif
236
Xiaohan Wang38e4ebb2022-01-19 06:57:43237#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02238// Retains system logging structures.
239base::ScopedFxLogger& GetScopedFxLogger() {
240 static base::NoDestructor<base::ScopedFxLogger> logger;
241 return *logger;
242}
243#endif
244
Lei Zhang93dd42572020-10-23 18:45:53245// For LOGGING_ERROR and above, always print to stderr.
246const int kAlwaysPrintErrorLevel = LOGGING_ERROR;
[email protected]a33c9892008-08-25 20:10:31247
[email protected]614e9fa2008-08-11 22:52:59248// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38249// will be lazily initialized to the default value when it is
250// first needed.
jdoerrie5c4dc4e2019-02-01 18:02:33251using PathString = base::FilePath::StringType;
thestig3e4787d2015-05-19 19:31:52252PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38253
thestig3e4787d2015-05-19 19:31:52254// This file is lazily opened and the handle may be nullptr
255FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38256
thestig3e4787d2015-05-19 19:31:52257// What should be prepended to each message?
258bool g_log_process_id = false;
259bool g_log_thread_id = false;
260bool g_log_timestamp = true;
261bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31262const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38263
[email protected]81e0a852010-08-17 00:38:12264// Should we pop up fatal debug messages in a dialog?
265bool show_error_dialogs = false;
266
initial.commitd7cae122008-07-26 21:49:38267// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55268// the debug message dialog and process termination. Assert handlers are stored
269// in stack to allow overriding and restoring.
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45270base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() {
271 static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance;
272 return *instance;
273}
alex-accc1bde62017-04-19 08:33:55274
[email protected]2b07b8412009-11-25 15:26:34275// A log message handler that gets notified of every log message we process.
Wez244270362021-05-04 22:50:58276LogMessageHandlerFunction g_log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38277
avi9b6f42932015-12-26 22:15:14278uint64_t TickCount() {
Xiaohan Wang38e4ebb2022-01-19 06:57:43279#if BUILDFLAG(IS_WIN)
[email protected]f8588472008-11-05 23:17:24280 return GetTickCount();
Xiaohan Wang38e4ebb2022-01-19 06:57:43281#elif BUILDFLAG(IS_FUCHSIA)
Peter Kasting2f61c8b2022-07-19 23:43:46282 return static_cast<uint64_t>(
283 zx_clock_get_monotonic() /
284 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond));
Xiaohan Wang38e4ebb2022-01-19 06:57:43285#elif BUILDFLAG(IS_APPLE)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39286 return mach_absolute_time();
Xiaohan Wang38e4ebb2022-01-19 06:57:43287#elif BUILDFLAG(IS_NACL)
[email protected]19ea84ca2010-11-12 08:37:08288 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
289 // So we have to use clock() for now.
290 return clock();
Xiaohan Wang38e4ebb2022-01-19 06:57:43291#elif BUILDFLAG(IS_POSIX)
[email protected]052f1b52008-11-06 21:43:07292 struct timespec ts;
293 clock_gettime(CLOCK_MONOTONIC, &ts);
294
Peter Kastingaca170a2022-06-30 17:18:48295 uint64_t absolute_micro = static_cast<uint64_t>(ts.tv_sec) * 1000000 +
296 static_cast<uint64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07297
298 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24299#endif
300}
301
[email protected]614e9fa2008-08-11 22:52:59302void DeleteFilePath(const PathString& log_name) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43303#if BUILDFLAG(IS_WIN)
Jan Wilken Dörrieb630aca2019-12-04 10:59:11304 DeleteFile(log_name.c_str());
Xiaohan Wang38e4ebb2022-01-19 06:57:43305#elif BUILDFLAG(IS_NACL)
[email protected]ac07ec52013-04-22 17:32:45306 // Do nothing; unlink() isn't supported on NaCl.
Xiaohan Wang38e4ebb2022-01-19 06:57:43307#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59308 unlink(log_name.c_str());
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39309#else
310#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28311#endif
312}
initial.commitd7cae122008-07-26 21:49:38313
[email protected]5f95d532010-10-01 17:16:58314PathString GetDefaultLogFile() {
Xiaohan Wang38e4ebb2022-01-19 06:57:43315#if BUILDFLAG(IS_WIN)
[email protected]5b84fe32010-09-14 22:24:55316 // On Windows we use the same path as the exe.
Jan Wilken Dörrieb630aca2019-12-04 10:59:11317 wchar_t module_name[MAX_PATH];
318 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58319
scottmgfc5b7072015-01-27 21:46:28320 PathString log_name = module_name;
321 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58322 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28323 log_name.erase(last_backslash + 1);
Jan Wilken Dörrieb630aca2019-12-04 10:59:11324 log_name += FILE_PATH_LITERAL("debug.log");
scottmgfc5b7072015-01-27 21:46:28325 return log_name;
Xiaohan Wang38e4ebb2022-01-19 06:57:43326#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55327 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58328 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55329#endif
330}
331
ananta61762fb2015-09-18 01:00:09332// We don't need locks on Windows for atomically appending to files. The OS
333// provides this functionality.
Xiaohan Wang38e4ebb2022-01-19 06:57:43334#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55335
Benoit Lize5c98a832020-07-07 16:32:01336base::Lock& GetLoggingLock() {
337 static base::NoDestructor<base::Lock> lock;
338 return *lock;
339}
[email protected]5b84fe32010-09-14 22:24:55340
Xiaohan Wang38e4ebb2022-01-19 06:57:43341#endif // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
ananta61762fb2015-09-18 01:00:09342
thestig3e4787d2015-05-19 19:31:52343// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38344// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52345// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38346bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52347 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38348 return true;
349
thestig3e4787d2015-05-19 19:31:52350 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59351 // Nobody has called InitLogging to specify a debug log file, so here we
352 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52353 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38354 }
355
Robbie McElrath8bf49842019-08-20 22:22:53356 if ((g_logging_destination & LOG_TO_FILE) == 0)
357 return true;
358
Xiaohan Wang38e4ebb2022-01-19 06:57:43359#if BUILDFLAG(IS_WIN)
Robbie McElrath8bf49842019-08-20 22:22:53360 // The FILE_APPEND_DATA access mask ensures that the file is atomically
361 // appended to across accesses from multiple threads.
362 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
363 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
Jan Wilken Dörrieb630aca2019-12-04 10:59:11364 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
Robbie McElrath8bf49842019-08-20 22:22:53365 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
366 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
367 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
368 // We are intentionally not using FilePath or FileUtil here to reduce the
369 // dependencies of the logging implementation. For e.g. FilePath and
370 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
371 // some consumers of base logging like chrome_elf, etc.
372 // Please don't change the code below to use FilePath.
373 // try the current directory
Jan Wilken Dörrieb630aca2019-12-04 10:59:11374 wchar_t system_buffer[MAX_PATH];
Robbie McElrath8bf49842019-08-20 22:22:53375 system_buffer[0] = 0;
Daniel Chengf45f47602022-02-28 22:38:32376 DWORD len = ::GetCurrentDirectory(std::size(system_buffer), system_buffer);
377 if (len == 0 || len > std::size(system_buffer))
Robbie McElrath8bf49842019-08-20 22:22:53378 return false;
379
380 *g_log_file_name = system_buffer;
381 // Append a trailing backslash if needed.
382 if (g_log_file_name->back() != L'\\')
Jan Wilken Dörrieb630aca2019-12-04 10:59:11383 *g_log_file_name += FILE_PATH_LITERAL("\\");
384 *g_log_file_name += FILE_PATH_LITERAL("debug.log");
Robbie McElrath8bf49842019-08-20 22:22:53385
Jan Wilken Dörrieb630aca2019-12-04 10:59:11386 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52387 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
388 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
389 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
Robbie McElrath8bf49842019-08-20 22:22:53390 g_log_file = nullptr;
[email protected]78c6dd62009-06-08 23:29:11391 return false;
Robbie McElrath8bf49842019-08-20 22:22:53392 }
393 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43394#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Robbie McElrath8bf49842019-08-20 22:22:53395 g_log_file = fopen(g_log_file_name->c_str(), "a");
396 if (g_log_file == nullptr)
397 return false;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39398#else
399#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28400#endif
[email protected]1d8c2702008-08-19 23:39:32401
initial.commitd7cae122008-07-26 21:49:38402 return true;
403}
404
[email protected]17dcf752013-07-15 21:47:09405void CloseFile(FileHandle log) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43406#if BUILDFLAG(IS_WIN)
[email protected]17dcf752013-07-15 21:47:09407 CloseHandle(log);
Xiaohan Wang38e4ebb2022-01-19 06:57:43408#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09409 fclose(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39410#else
411#error Unsupported platform
[email protected]17dcf752013-07-15 21:47:09412#endif
413}
414
415void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52416 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09417 return;
418
thestig3e4787d2015-05-19 19:31:52419 CloseFile(g_log_file);
420 g_log_file = nullptr;
Robbie McElrath8bf49842019-08-20 22:22:53421
422 // If we initialized logging via an externally-provided file descriptor, we
423 // won't have a log path set and shouldn't try to reopen the log file.
424 if (!g_log_file_name)
425 g_logging_destination &= ~LOG_TO_FILE;
[email protected]17dcf752013-07-15 21:47:09426}
427
Xiaohan Wang38e4ebb2022-01-19 06:57:43428#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02429inline FuchsiaLogSeverity LogSeverityToFuchsiaLogSeverity(
430 LogSeverity severity) {
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38431 switch (severity) {
432 case LOGGING_INFO:
Wez45e3ffe2021-09-24 02:10:02433 return FUCHSIA_LOG_INFO;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38434 case LOGGING_WARNING:
Wez45e3ffe2021-09-24 02:10:02435 return FUCHSIA_LOG_WARNING;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38436 case LOGGING_ERROR:
Wez45e3ffe2021-09-24 02:10:02437 return FUCHSIA_LOG_ERROR;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38438 case LOGGING_FATAL:
439 // Don't use FX_LOG_FATAL, otherwise fx_logger_log() will abort().
Wez45e3ffe2021-09-24 02:10:02440 return FUCHSIA_LOG_ERROR;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38441 }
442 if (severity > -3) {
443 // LOGGING_VERBOSE levels 1 and 2.
Wez45e3ffe2021-09-24 02:10:02444 return FUCHSIA_LOG_DEBUG;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38445 }
446 // LOGGING_VERBOSE levels 3 and higher, or incorrect levels.
Wez45e3ffe2021-09-24 02:10:02447 return FUCHSIA_LOG_TRACE;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38448}
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38449#endif // defined (OS_FUCHSIA)
450
Benoit Lizeed678192022-01-20 10:14:54451void WriteToFd(int fd, const char* data, size_t length) {
452 size_t bytes_written = 0;
Peter Kastingaca170a2022-06-30 17:18:48453 long rv;
Benoit Lizeed678192022-01-20 10:14:54454 while (bytes_written < length) {
455 rv = HANDLE_EINTR(write(fd, data + bytes_written, length - bytes_written));
456 if (rv < 0) {
457 // Give up, nothing we can do now.
458 break;
459 }
Peter Kastingde85e742022-06-01 17:41:54460 bytes_written += static_cast<size_t>(rv);
Benoit Lizeed678192022-01-20 10:14:54461 }
462}
463
Peter Boström871f916a2022-08-09 22:36:27464void SetLogFatalCrashKey(LogMessage* log_message) {
465#if !BUILDFLAG(IS_NACL)
466 // In case of an out-of-memory condition, this code could be reentered when
467 // constructing and storing the key. Using a static is not thread-safe, but if
468 // multiple threads are in the process of a fatal crash at the same time, this
469 // should work.
470 static bool guarded = false;
471 if (guarded)
472 return;
473
474 base::AutoReset<bool> guard(&guarded, true);
475
476 static auto* const crash_key = base::debug::AllocateCrashKeyString(
477 "LOG_FATAL", base::debug::CrashKeySize::Size1024);
478 base::debug::SetCrashKeyString(crash_key, log_message->BuildCrashString());
479
480#endif // !BUILDFLAG(IS_NACL)
481}
482
483std::string BuildCrashString(const char* file,
484 int line,
485 const char* message_without_prefix) {
486 // Only log last path component.
487 if (file) {
Peter Boström39dd8c82022-08-12 00:39:37488 const char* slash = strrchr(file,
489#if BUILDFLAG(IS_WIN)
490 '\\'
491#else
492 '/'
493#endif // BUILDFLAG(IS_WIN)
494 );
Peter Boström871f916a2022-08-09 22:36:27495 if (slash) {
496 file = slash + 1;
497 }
498 }
499
500 return base::StringPrintf("%s:%d: %s", file, line, message_without_prefix);
501}
502
[email protected]064aa162011-12-03 00:30:08503} // namespace
504
Wez02cedeba2022-07-26 12:48:38505#if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
Lei Zhang93dd42572020-10-23 18:45:53506// In DCHECK-enabled Chrome builds, allow the meaning of LOGGING_DCHECK to be
Wez289477f2017-08-24 20:51:30507// determined at run-time. We default it to INFO, to avoid it triggering
508// crashes before the run-time has explicitly chosen the behaviour.
Lei Zhang93dd42572020-10-23 18:45:53509BASE_EXPORT logging::LogSeverity LOGGING_DCHECK = LOGGING_INFO;
Wez02cedeba2022-07-26 12:48:38510#endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30511
scottmg3c957a52016-12-10 20:57:59512// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
513// an object of the correct type on the LHS of the unused part of the ternary
514// operator.
515std::ostream* g_swallow_stream;
516
[email protected]5e3f7c22013-06-21 21:15:33517bool BaseInitLoggingImpl(const LoggingSettings& settings) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43518#if BUILDFLAG(IS_NACL)
Sharon Yang7cb919a2019-05-20 20:27:15519 // Can log only to the system debug log and stderr.
520 CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR),
521 0u);
[email protected]ac07ec52013-04-22 17:32:45522#endif
Robbie McElrath8bf49842019-08-20 22:22:53523
Georg Neisffe34f652021-12-27 21:42:36524#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata8a93e522020-09-25 08:59:57525 g_log_format = settings.log_format;
526#endif
527
Xiyuan Xiaa0559da2022-05-05 19:42:45528#if BUILDFLAG(USE_RUNTIME_VLOG)
Fergal Daly432aa7c2022-06-14 07:30:54529 MaybeInitializeVlogInfo();
Fergal Dalycac6ddc2022-05-24 17:42:03530#endif // BUILDFLAG(USE_RUNTIME_VLOG)
[email protected]99b7c57f2010-09-29 19:26:36531
Jeffrey Young551bce62022-06-24 19:08:17532#if !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
533 MaybeWarnVmodule();
534#endif // !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
535
thestig3e4787d2015-05-19 19:31:52536 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38537
Xiaohan Wang38e4ebb2022-01-19 06:57:43538#if BUILDFLAG(IS_FUCHSIA)
Wez224c0bf62019-05-24 19:26:13539 if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) {
Wez5d4a666c2021-10-04 16:41:36540 GetScopedFxLogger() = base::ScopedFxLogger::CreateForProcess();
Wez224c0bf62019-05-24 19:26:13541 }
542#endif
543
[email protected]5e3f7c22013-06-21 21:15:33544 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52545 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21546 return true;
initial.commitd7cae122008-07-26 21:49:38547
Xiaohan Wang38e4ebb2022-01-19 06:57:43548#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:01549 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09550#endif
[email protected]17dcf752013-07-15 21:47:09551
552 // Calling InitLogging twice or after some log call has already opened the
553 // default log file will re-initialize to the new options.
554 CloseLogFileUnlocked();
555
Yuta Hijikata000df18f2020-11-18 06:55:58556#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:53557 if (settings.log_file) {
558 DCHECK(!settings.log_file_path);
559 g_log_file = settings.log_file;
560 return true;
561 }
562#endif
Lei Zhang93dd42572020-10-23 18:45:53563
Xiaohan Wang5411974b2020-10-10 19:36:12564 DCHECK(settings.log_file_path) << "LOG_TO_FILE set but no log_file_path!";
Robbie McElrath8bf49842019-08-20 22:22:53565
thestig3e4787d2015-05-19 19:31:52566 if (!g_log_file_name)
567 g_log_file_name = new PathString();
Robbie McElrath8bf49842019-08-20 22:22:53568 *g_log_file_name = settings.log_file_path;
[email protected]5e3f7c22013-06-21 21:15:33569 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52570 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38571
[email protected]c7d5da992010-10-28 00:20:21572 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38573}
574
575void SetMinLogLevel(int level) {
Lei Zhang93dd42572020-10-23 18:45:53576 g_min_log_level = std::min(LOGGING_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38577}
578
579int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52580 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38581}
582
skobesc78c0ad72015-12-07 20:21:23583bool ShouldCreateLogMessage(int severity) {
584 if (severity < g_min_log_level)
585 return false;
586
Wez6c8acb82019-07-18 00:32:59587 // Return true here unless we know ~LogMessage won't do anything.
Wez244270362021-05-04 22:50:58588 return g_logging_destination != LOG_NONE || g_log_message_handler ||
skobesc78c0ad72015-12-07 20:21:23589 severity >= kAlwaysPrintErrorLevel;
590}
591
Wez6c8acb82019-07-18 00:32:59592// Returns true when LOG_TO_STDERR flag is set, or |severity| is high.
593// If |severity| is high then true will be returned when no log destinations are
594// set, or only LOG_TO_FILE is set, since that is useful for local development
595// and debugging.
596bool ShouldLogToStderr(int severity) {
597 if (g_logging_destination & LOG_TO_STDERR)
598 return true;
Wez82ba0502022-05-11 08:50:08599
600#if BUILDFLAG(IS_FUCHSIA)
601 // Fuchsia will persist data logged to stdio by a component, so do not emit
602 // logs to stderr unless explicitly configured to do so.
603 return false;
604#else
Wez6c8acb82019-07-18 00:32:59605 if (severity >= kAlwaysPrintErrorLevel)
606 return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
607 return false;
Wez82ba0502022-05-11 08:50:08608#endif
Wez6c8acb82019-07-18 00:32:59609}
610
[email protected]162ac0f2010-11-04 15:50:49611int GetVlogVerbosity() {
612 return std::max(-1, LOG_INFO - GetMinLogLevel());
613}
614
[email protected]99b7c57f2010-09-29 19:26:36615int GetVlogLevelHelper(const char* file, size_t N) {
616 DCHECK_GT(N, 0U);
Xiyuan Xiaa0559da2022-05-05 19:42:45617
618#if BUILDFLAG(USE_RUNTIME_VLOG)
thestig3e4787d2015-05-19 19:31:52619 // Note: |g_vlog_info| may change on a different thread during startup
620 // (but will always be valid or nullptr).
Fergal Daly432aa7c2022-06-14 07:30:54621 VlogInfo* vlog_info = GetVlogInfo();
[email protected]064aa162011-12-03 00:30:08622 return vlog_info ?
623 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49624 GetVlogVerbosity();
Xiyuan Xiaa0559da2022-05-05 19:42:45625#else
626 return GetVlogVerbosity();
627#endif // BUILDFLAG(USE_RUNTIME_VLOG)
[email protected]99b7c57f2010-09-29 19:26:36628}
629
initial.commitd7cae122008-07-26 21:49:38630void SetLogItems(bool enable_process_id, bool enable_thread_id,
631 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52632 g_log_process_id = enable_process_id;
633 g_log_thread_id = enable_thread_id;
634 g_log_timestamp = enable_timestamp;
635 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38636}
637
James Cooka0536c32018-08-01 20:13:31638void SetLogPrefix(const char* prefix) {
639 DCHECK(!prefix ||
640 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
641 g_log_prefix = prefix;
642}
643
[email protected]81e0a852010-08-17 00:38:12644void SetShowErrorDialogs(bool enable_dialogs) {
645 show_error_dialogs = enable_dialogs;
646}
647
alex-accc1bde62017-04-19 08:33:55648ScopedLogAssertHandler::ScopedLogAssertHandler(
649 LogAssertHandlerFunction handler) {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45650 GetLogAssertHandlerStack().push(std::move(handler));
alex-accc1bde62017-04-19 08:33:55651}
652
653ScopedLogAssertHandler::~ScopedLogAssertHandler() {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45654 GetLogAssertHandlerStack().pop();
initial.commitd7cae122008-07-26 21:49:38655}
656
[email protected]2b07b8412009-11-25 15:26:34657void SetLogMessageHandler(LogMessageHandlerFunction handler) {
Wez244270362021-05-04 22:50:58658 g_log_message_handler = handler;
[email protected]2b07b8412009-11-25 15:26:34659}
660
[email protected]64e5cc02010-11-03 19:20:27661LogMessageHandlerFunction GetLogMessageHandler() {
Wez244270362021-05-04 22:50:58662 return g_log_message_handler;
[email protected]64e5cc02010-11-03 19:20:27663}
664
[email protected]f2c05492014-06-17 12:04:23665#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22666// Displays a message box to the user with the error message in it.
667// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25668// This is for developers only; we don't use this in circumstances
669// (like release builds) where users could see it, since users don't
670// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22671void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38672 if (str.empty())
673 return;
674
[email protected]81e0a852010-08-17 00:38:12675 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44676 return;
677
Xiaohan Wang38e4ebb2022-01-19 06:57:43678#if BUILDFLAG(IS_WIN)
[email protected]561513f2010-12-16 23:29:25679 // We intentionally don't implement a dialog on other platforms.
680 // You can just look at stderr.
Cliff Smolinskyc5c52102019-05-03 20:51:54681 if (base::win::IsUser32AndGdi32Available()) {
682 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
683 MB_OK | MB_ICONHAND | MB_TOPMOST);
684 } else {
685 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
686 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43687#endif // BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38688}
[email protected]f2c05492014-06-17 12:04:23689#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38690
[email protected]eae9c062011-01-11 00:50:59691LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
692 : severity_(severity), file_(file), line_(line) {
693 Init(file, line);
694}
695
tnagel4a045d3f2015-07-12 14:19:28696LogMessage::LogMessage(const char* file, int line, const char* condition)
Lei Zhang93dd42572020-10-23 18:45:53697 : severity_(LOGGING_FATAL), file_(file), line_(line) {
tnagel4a045d3f2015-07-12 14:19:28698 Init(file, line);
699 stream_ << "Check failed: " << condition << ". ";
700}
701
initial.commitd7cae122008-07-26 21:49:38702LogMessage::~LogMessage() {
Peter Kasting28b51cf2022-06-28 15:02:43703 size_t stack_start = stream_.str().length();
Sven Zhengb11f397e2022-08-30 01:18:51704#if !defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_NACL) && !defined(__UCLIBC__) && \
705 !BUILDFLAG(IS_AIX)
Lei Zhang93dd42572020-10-23 18:45:53706 if (severity_ == LOGGING_FATAL && !base::debug::BeingDebugged()) {
brucedawson7c559eb2015-09-05 00:34:42707 // Include a stack trace on a fatal, unless a debugger is attached.
Sven Zhengb11f397e2022-08-30 01:18:51708 base::debug::StackTrace stack_trace;
709 stream_ << std::endl; // Newline to separate from log message.
710 stack_trace.OutputToStream(&stream_);
711 base::debug::TaskTrace task_trace;
712 if (!task_trace.empty())
713 task_trace.OutputToStream(&stream_);
714
715 // Include the IPC context, if any.
716 // TODO(chrisha): Integrate with symbolization once those tools exist!
717 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
718 if (task && task->ipc_hash) {
719 stream_ << "IPC message handler context: "
720 << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
721 }
722
723 // Include the crash keys, if any.
724 base::debug::OutputCrashKeysToStream(stream_);
[email protected]d1ccc35a2010-03-24 05:03:24725 }
[email protected]1d8c2702008-08-19 23:39:32726#endif
Sven Zhengb11f397e2022-08-30 01:18:51727 stream_ << std::endl;
[email protected]d1ccc35a2010-03-24 05:03:24728 std::string str_newline(stream_.str());
Nicolò Mazzucato6c278d9b2019-08-02 16:25:44729 TRACE_LOG_MESSAGE(
730 file_, base::StringPiece(str_newline).substr(message_start_), line_);
[email protected]d1ccc35a2010-03-24 05:03:24731
Peter Boström871f916a2022-08-09 22:36:27732 if (severity_ == LOGGING_FATAL)
733 SetLogFatalCrashKey(this);
734
[email protected]2b07b8412009-11-25 15:26:34735 // Give any log message handler first dibs on the message.
Wez244270362021-05-04 22:50:58736 if (g_log_message_handler &&
737 g_log_message_handler(severity_, file_, line_, message_start_,
738 str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49739 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34740 return;
[email protected]162ac0f2010-11-04 15:50:49741 }
initial.commitd7cae122008-07-26 21:49:38742
thestig3e4787d2015-05-19 19:31:52743 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43744#if BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38745 OutputDebugStringA(str_newline.c_str());
Xiaohan Wang38e4ebb2022-01-19 06:57:43746#elif BUILDFLAG(IS_APPLE)
mark4c7449c2015-11-10 19:53:42747 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Avi Drissmanba195b32022-05-19 02:53:34748 // stderr. If stderr is /dev/null, also log via os_log. If there's something
749 // weird about stderr, assume that log messages are going nowhere and log
750 // via os_log too. Messages logged via os_log show up in Console.app.
mark4c7449c2015-11-10 19:53:42751 //
752 // Programs started by launchd, as UI applications normally are, have had
753 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
754 // a pipe to launchd, which logged what it received (see log_redirect_fd in
755 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
756 //
757 // Another alternative would be to determine whether stderr is a pipe to
Avi Drissmanba195b32022-05-19 02:53:34758 // launchd and avoid logging via os_log only in that case. See 10.7.5
mark4c7449c2015-11-10 19:53:42759 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Avi Drissmanba195b32022-05-19 02:53:34760 // both stderr and os_log even in tests, where it's undesirable to log to
761 // the system log at all.
Eric Noyaufce100702017-10-16 09:46:34762 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42763 struct stat stderr_stat;
764 if (fstat(fileno(stderr), &stderr_stat) == -1) {
765 return true;
766 }
767 if (!S_ISCHR(stderr_stat.st_mode)) {
768 return false;
769 }
770
771 struct stat dev_null_stat;
772 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
773 return true;
774 }
775
776 return !S_ISCHR(dev_null_stat.st_mode) ||
777 stderr_stat.st_rdev == dev_null_stat.st_rdev;
778 }();
779
Eric Noyaufce100702017-10-16 09:46:34780 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42781 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
782 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42783 CFBundleRef main_bundle = CFBundleGetMainBundle();
784 CFStringRef main_bundle_id_cf =
785 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34786 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42787 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34788 : std::string("");
mark4c7449c2015-11-10 19:53:42789
Eric Noyaufce100702017-10-16 09:46:34790 const class OSLog {
791 public:
792 explicit OSLog(const char* subsystem)
793 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
794 : OS_LOG_DEFAULT) {}
David Bienvenub4b441e2020-09-23 05:49:57795 OSLog(const OSLog&) = delete;
796 OSLog& operator=(const OSLog&) = delete;
Eric Noyaufce100702017-10-16 09:46:34797 ~OSLog() {
798 if (os_log_ != OS_LOG_DEFAULT) {
799 os_release(os_log_);
800 }
801 }
802 os_log_t get() const { return os_log_; }
803
804 private:
805 os_log_t os_log_;
Eric Noyaufce100702017-10-16 09:46:34806 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
807 const os_log_type_t os_log_type = [](LogSeverity severity) {
808 switch (severity) {
Lei Zhang93dd42572020-10-23 18:45:53809 case LOGGING_INFO:
Eric Noyaufce100702017-10-16 09:46:34810 return OS_LOG_TYPE_INFO;
Lei Zhang93dd42572020-10-23 18:45:53811 case LOGGING_WARNING:
Eric Noyaufce100702017-10-16 09:46:34812 return OS_LOG_TYPE_DEFAULT;
Lei Zhang93dd42572020-10-23 18:45:53813 case LOGGING_ERROR:
Eric Noyaufce100702017-10-16 09:46:34814 return OS_LOG_TYPE_ERROR;
Lei Zhang93dd42572020-10-23 18:45:53815 case LOGGING_FATAL:
Eric Noyaufce100702017-10-16 09:46:34816 return OS_LOG_TYPE_FAULT;
Avi Drissmana1d016c2022-05-12 21:58:20817 case LOGGING_VERBOSE:
818 return OS_LOG_TYPE_DEBUG;
Eric Noyaufce100702017-10-16 09:46:34819 default:
Avi Drissmana1d016c2022-05-12 21:58:20820 return OS_LOG_TYPE_DEFAULT;
Eric Noyaufce100702017-10-16 09:46:34821 }
822 }(severity_);
823 os_log_with_type(log.get(), os_log_type, "%{public}s",
824 str_newline.c_str());
mark4c7449c2015-11-10 19:53:42825 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43826#elif BUILDFLAG(IS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25827 android_LogPriority priority =
828 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50829 switch (severity_) {
Lei Zhang93dd42572020-10-23 18:45:53830 case LOGGING_INFO:
[email protected]3132e35c2011-07-07 20:46:50831 priority = ANDROID_LOG_INFO;
832 break;
Lei Zhang93dd42572020-10-23 18:45:53833 case LOGGING_WARNING:
[email protected]3132e35c2011-07-07 20:46:50834 priority = ANDROID_LOG_WARN;
835 break;
Lei Zhang93dd42572020-10-23 18:45:53836 case LOGGING_ERROR:
[email protected]3132e35c2011-07-07 20:46:50837 priority = ANDROID_LOG_ERROR;
838 break;
Lei Zhang93dd42572020-10-23 18:45:53839 case LOGGING_FATAL:
[email protected]3132e35c2011-07-07 20:46:50840 priority = ANDROID_LOG_FATAL;
841 break;
842 }
Tomasz Śniatowski23dd15af2019-02-15 08:32:03843 const char kAndroidLogTag[] = "chromium";
Xianzhu Wangae8d96a32018-10-16 20:41:13844#if DCHECK_IS_ON()
845 // Split the output by new lines to prevent the Android system from
846 // truncating the log.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03847 std::vector<std::string> lines = base::SplitString(
848 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
849 // str_newline has an extra newline appended to it (at the top of this
850 // function), so skip the last split element to avoid needlessly
851 // logging an empty string.
852 lines.pop_back();
853 for (const auto& line : lines)
854 __android_log_write(priority, kAndroidLogTag, line.c_str());
Xianzhu Wangae8d96a32018-10-16 20:41:13855#else
856 // The Android system may truncate the string if it's too long.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03857 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18858#endif
Xiaohan Wang38e4ebb2022-01-19 06:57:43859#elif BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02860 // LogMessage() will silently drop the message if the logger is not valid.
Weza38cc532021-12-16 22:58:20861 // Skip the final character of |str_newline|, since LogMessage() will add
862 // a newline.
863 const auto message = base::StringPiece(str_newline).substr(message_start_);
Peter Kasting2f61c8b2022-07-19 23:43:46864 GetScopedFxLogger().LogMessage(file_, static_cast<uint32_t>(line_),
Weza38cc532021-12-16 22:58:20865 message.substr(0, message.size() - 1),
866 LogSeverityToFuchsiaLogSeverity(severity_));
Xiaohan Wang38e4ebb2022-01-19 06:57:43867#endif // BUILDFLAG(IS_FUCHSIA)
Sharon Yang7cb919a2019-05-20 20:27:15868 }
869
Wez6c8acb82019-07-18 00:32:59870 if (ShouldLogToStderr(severity_)) {
Benoit Lizeed678192022-01-20 10:14:54871 // Not using fwrite() here, as there are crashes on Windows when CRT calls
872 // malloc() internally, triggering an OOM crash. This likely means that the
873 // process is close to OOM, but at least get the proper error message out,
874 // and give the caller a chance to free() up some resources. For instance if
875 // the calling code is:
876 //
877 // allocate_something();
878 // if (!TryToDoSomething()) {
879 // LOG(ERROR) << "Something went wrong";
880 // free_something();
881 // }
882 WriteToFd(STDERR_FILENO, str_newline.data(), str_newline.size());
[email protected]f6abeba2008-08-08 13:27:28883 }
[email protected]52a261f2009-03-03 15:01:12884
thestig3e4787d2015-05-19 19:31:52885 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09886 // We can have multiple threads and/or processes, so try to prevent them
887 // from clobbering each other's writes.
888 // If the client app did not call InitLogging, and the lock has not
889 // been created do it now. We do this on demand, but if two threads try
890 // to do this at the same time, there will be a race condition to create
891 // the lock. This is why InitLogging should be called from the main
892 // thread at the beginning of execution.
Xiaohan Wang38e4ebb2022-01-19 06:57:43893#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:01894 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09895#endif
[email protected]5b84fe32010-09-14 22:24:55896 if (InitializeLogFileHandle()) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43897#if BUILDFLAG(IS_WIN)
[email protected]5b84fe32010-09-14 22:24:55898 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52899 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55900 static_cast<const void*>(str_newline.c_str()),
901 static_cast<DWORD>(str_newline.length()),
902 &num_written,
thestig3e4787d2015-05-19 19:31:52903 nullptr);
Xiaohan Wang38e4ebb2022-01-19 06:57:43904#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Avi Drissman933398e2022-01-22 00:55:42905 std::ignore =
906 fwrite(str_newline.data(), str_newline.size(), 1, g_log_file);
thestig3e4787d2015-05-19 19:31:52907 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39908#else
909#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55910#endif
initial.commitd7cae122008-07-26 21:49:38911 }
912 }
913
Lei Zhang93dd42572020-10-23 18:45:53914 if (severity_ == LOGGING_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40915 // Write the log message to the global activity tracker, if running.
916 base::debug::GlobalActivityTracker* tracker =
917 base::debug::GlobalActivityTracker::Get();
918 if (tracker)
919 tracker->RecordLogMessage(str_newline);
920
Wezd78fee62020-09-11 18:29:14921 char str_stack[1024];
Daniel Chengf45f47602022-02-28 22:38:32922 base::strlcpy(str_stack, str_newline.data(), std::size(str_stack));
Weze976b732018-10-20 03:37:31923 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05924
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45925 if (!GetLogAssertHandlerStack().empty()) {
alex-accc1bde62017-04-19 08:33:55926 LogAssertHandlerFunction log_assert_handler =
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45927 GetLogAssertHandlerStack().top();
alex-accc1bde62017-04-19 08:33:55928
929 if (log_assert_handler) {
930 log_assert_handler.Run(
931 file_, line_,
932 base::StringPiece(str_newline.c_str() + message_start_,
933 stack_start - message_start_),
934 base::StringPiece(str_newline.c_str() + stack_start));
935 }
[email protected]1ffe08c12008-08-13 11:15:11936 } else {
[email protected]82d89ab2014-02-28 18:25:34937 // Don't use the string with the newline, get a fresh version to send to
938 // the debug message process. We also don't display assertions to the
939 // user in release mode. The enduser can't do anything with this
940 // information, and displaying message boxes when the application is
941 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50942#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42943 if (!base::debug::BeingDebugged()) {
944 // Displaying a dialog is unnecessary when debugging and can complicate
945 // debugging.
946 DisplayDebugMessageInDialog(stream_.str());
947 }
[email protected]4d5901272008-11-06 00:33:50948#endif
Daniel Cheng4f5034d2022-03-04 18:34:31949
[email protected]82d89ab2014-02-28 18:25:34950 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52951 IMMEDIATE_CRASH();
initial.commitd7cae122008-07-26 21:49:38952 }
953 }
954}
955
Peter Boström37482962022-07-14 16:09:54956std::string LogMessage::BuildCrashString() const {
Peter Boström871f916a2022-08-09 22:36:27957 return logging::BuildCrashString(file(), line(),
958 str().c_str() + message_start_);
Peter Boström6c0094d12022-07-07 16:03:39959}
960
[email protected]eae9c062011-01-11 00:50:59961// writes the common header info to the stream
962void LogMessage::Init(const char* file, int line) {
963 base::StringPiece filename(file);
964 size_t last_slash_pos = filename.find_last_of("\\/");
965 if (last_slash_pos != base::StringPiece::npos)
966 filename.remove_prefix(last_slash_pos + 1);
967
Georg Neisffe34f652021-12-27 21:42:36968#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54969 if (g_log_format == LogFormat::LOG_FORMAT_SYSLOG) {
970 InitWithSyslogPrefix(
971 filename, line, TickCount(), log_severity_name(severity_), g_log_prefix,
972 g_log_process_id, g_log_thread_id, g_log_timestamp, g_log_tickcount);
973 } else
Georg Neisffe34f652021-12-27 21:42:36974#endif // BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54975 {
976 // TODO(darin): It might be nice if the columns were fixed width.
977 stream_ << '[';
978 if (g_log_prefix)
979 stream_ << g_log_prefix << ':';
980 if (g_log_process_id)
981 stream_ << base::GetUniqueIdForProcess() << ':';
982 if (g_log_thread_id)
983 stream_ << base::PlatformThread::CurrentId() << ':';
984 if (g_log_timestamp) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43985#if BUILDFLAG(IS_WIN)
Yuta Hijikata9b7279a2020-08-26 16:10:54986 SYSTEMTIME local_time;
987 GetLocalTime(&local_time);
988 stream_ << std::setfill('0')
989 << std::setw(2) << local_time.wMonth
990 << std::setw(2) << local_time.wDay
991 << '/'
992 << std::setw(2) << local_time.wHour
993 << std::setw(2) << local_time.wMinute
994 << std::setw(2) << local_time.wSecond
995 << '.'
996 << std::setw(3) << local_time.wMilliseconds
997 << ':';
Xiaohan Wang38e4ebb2022-01-19 06:57:43998#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Yuta Hijikata9b7279a2020-08-26 16:10:54999 timeval tv;
1000 gettimeofday(&tv, nullptr);
1001 time_t t = tv.tv_sec;
1002 struct tm local_time;
1003 localtime_r(&t, &local_time);
1004 struct tm* tm_time = &local_time;
1005 stream_ << std::setfill('0')
1006 << std::setw(2) << 1 + tm_time->tm_mon
1007 << std::setw(2) << tm_time->tm_mday
1008 << '/'
1009 << std::setw(2) << tm_time->tm_hour
1010 << std::setw(2) << tm_time->tm_min
1011 << std::setw(2) << tm_time->tm_sec
1012 << '.'
1013 << std::setw(6) << tv.tv_usec
1014 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391015#else
1016#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:341017#endif
Yuta Hijikata9b7279a2020-08-26 16:10:541018 }
1019 if (g_log_tickcount)
1020 stream_ << TickCount() << ':';
1021 if (severity_ >= 0) {
1022 stream_ << log_severity_name(severity_);
1023 } else {
1024 stream_ << "VERBOSE" << -severity_;
1025 }
1026 stream_ << ":" << filename << "(" << line << ")] ";
[email protected]eae9c062011-01-11 00:50:591027 }
pkasting9cf9b94a2014-10-01 22:18:431028 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:591029}
1030
Xiaohan Wang38e4ebb2022-01-19 06:57:431031#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201032// This has already been defined in the header, but defining it again as DWORD
1033// ensures that the type used in the header is equivalent to DWORD. If not,
1034// the redefinition is a compile error.
1035typedef DWORD SystemErrorCode;
1036#endif
1037
1038SystemErrorCode GetLastSystemErrorCode() {
Xiaohan Wang38e4ebb2022-01-19 06:57:431039#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201040 return ::GetLastError();
Xiaohan Wang38e4ebb2022-01-19 06:57:431041#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201042 return errno;
[email protected]d8617a62009-10-09 23:52:201043#endif
1044}
1045
[email protected]c914d8a2014-04-23 01:11:011046BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Xiaohan Wang38e4ebb2022-01-19 06:57:431047#if BUILDFLAG(IS_WIN)
thestig75f87352014-12-03 21:42:271048 const int kErrorMessageBufferSize = 256;
1049 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:011050 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:521051 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Daniel Chengf45f47602022-02-28 22:38:321052 std::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:011053 if (len) {
1054 // Messages returned by system end with line breaks.
1055 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:451056 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:011057 }
Bruce Dawson19175842017-08-02 17:00:451058 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:011059 GetLastError(), error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431060#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:141061 return base::safe_strerror(error_code) +
1062 base::StringPrintf(" (%d)", error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431063#endif // BUILDFLAG(IS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391064}
[email protected]d8617a62009-10-09 23:52:201065
Xiaohan Wang38e4ebb2022-01-19 06:57:431066#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201067Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1068 int line,
1069 LogSeverity severity,
1070 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001071 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201072
1073Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011074 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:061075 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1076 // field) and use Alias in hopes that it makes it into crash dumps.
1077 DWORD last_error = err_;
1078 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201079}
Xiaohan Wang38e4ebb2022-01-19 06:57:431080#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201081ErrnoLogMessage::ErrnoLogMessage(const char* file,
1082 int line,
1083 LogSeverity severity,
1084 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001085 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201086
1087ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011088 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141089 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1090 // field) and use Alias in hopes that it makes it into crash dumps.
1091 int last_error = err_;
1092 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201093}
Xiaohan Wang38e4ebb2022-01-19 06:57:431094#endif // BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201095
initial.commitd7cae122008-07-26 21:49:381096void CloseLogFile() {
Xiaohan Wang38e4ebb2022-01-19 06:57:431097#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:011098 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:091099#endif
[email protected]17dcf752013-07-15 21:47:091100 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381101}
1102
Yuta Hijikata000df18f2020-11-18 06:55:581103#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:531104FILE* DuplicateLogFILE() {
1105 if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle())
1106 return nullptr;
1107
1108 int log_fd = fileno(g_log_file);
1109 if (log_fd == -1)
1110 return nullptr;
1111 base::ScopedFD dup_fd(dup(log_fd));
1112 if (dup_fd == -1)
1113 return nullptr;
1114 FILE* duplicate = fdopen(dup_fd.get(), "a");
1115 if (!duplicate)
1116 return nullptr;
Avi Drissman933398e2022-01-22 00:55:421117 std::ignore = dup_fd.release();
Robbie McElrath8bf49842019-08-20 22:22:531118 return duplicate;
1119}
1120#endif
1121
Yuta Hijikata9b7279a2020-08-26 16:10:541122// Used for testing. Declared in test/scoped_logging_settings.h.
1123ScopedLoggingSettings::ScopedLoggingSettings()
Wez244270362021-05-04 22:50:581124 : min_log_level_(g_min_log_level),
1125 logging_destination_(g_logging_destination),
Georg Neisffe34f652021-12-27 21:42:361126#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581127 log_format_(g_log_format),
1128#endif // BUILDFLAG(IS_CHROMEOS_ASH)
1129 enable_process_id_(g_log_process_id),
Yuta Hijikata9b7279a2020-08-26 16:10:541130 enable_thread_id_(g_log_thread_id),
1131 enable_timestamp_(g_log_timestamp),
1132 enable_tickcount_(g_log_tickcount),
Wez244270362021-05-04 22:50:581133 log_prefix_(g_log_prefix),
1134 message_handler_(g_log_message_handler) {
1135 if (g_log_file_name)
1136 log_file_name_ = std::make_unique<PathString>(*g_log_file_name);
1137 // Duplicating |g_log_file| is complex & unnecessary for this test helpers'
1138 // use-cases, and so long as |g_log_file_name| is set, it will be re-opened
1139 // automatically anyway, when required, so just close the existing one.
1140 if (g_log_file) {
1141 CHECK(g_log_file_name) << "Un-named |log_file| is not supported.";
1142 CloseLogFileUnlocked();
1143 }
Yuta Hijikata9b7279a2020-08-26 16:10:541144}
1145
1146ScopedLoggingSettings::~ScopedLoggingSettings() {
Wez244270362021-05-04 22:50:581147 // Re-initialize logging via the normal path. This will clean up old file
1148 // name and handle state, including re-initializing the VLOG internal state.
1149 CHECK(InitLogging({
1150 .logging_dest = logging_destination_,
1151 .log_file_path = log_file_name_ ? log_file_name_->data() : nullptr,
Georg Neisffe34f652021-12-27 21:42:361152#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581153 .log_format = log_format_
1154#endif
1155 })) << "~ScopedLoggingSettings() failed to restore settings.";
1156
1157 // Restore plain data settings.
1158 SetMinLogLevel(min_log_level_);
1159 SetLogItems(enable_process_id_, enable_thread_id_, enable_timestamp_,
1160 enable_tickcount_);
1161 SetLogPrefix(log_prefix_);
1162 SetLogMessageHandler(message_handler_);
Yuta Hijikata9b7279a2020-08-26 16:10:541163}
1164
Georg Neisffe34f652021-12-27 21:42:361165#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:541166void ScopedLoggingSettings::SetLogFormat(LogFormat log_format) const {
1167 g_log_format = log_format;
1168}
Yuta Hijikata000df18f2020-11-18 06:55:581169#endif // BUILDFLAG(IS_CHROMEOS_ASH)
Yuta Hijikata9b7279a2020-08-26 16:10:541170
[email protected]e36ddc82009-12-08 04:22:501171void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491172 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501173 const size_t message_len = strlen(message);
Benoit Lizeed678192022-01-20 10:14:541174 WriteToFd(STDERR_FILENO, message, message_len);
[email protected]e36ddc82009-12-08 04:22:501175
1176 if (message_len > 0 && message[message_len - 1] != '\n') {
Peter Kastingaca170a2022-06-30 17:18:481177 long rv;
[email protected]e36ddc82009-12-08 04:22:501178 do {
1179 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1180 if (rv < 0) {
1181 // Give up, nothing we can do now.
1182 break;
1183 }
1184 } while (rv != 1);
1185 }
1186 }
1187
Lei Zhang93dd42572020-10-23 18:45:531188 if (level == LOGGING_FATAL)
Daniel Cheng4f5034d2022-03-04 18:34:311189 IMMEDIATE_CRASH();
[email protected]e36ddc82009-12-08 04:22:501190}
1191
[email protected]34a907732012-01-20 06:33:271192// This was defined at the beginning of this file.
1193#undef write
1194
Xiaohan Wang38e4ebb2022-01-19 06:57:431195#if BUILDFLAG(IS_WIN)
ananta61762fb2015-09-18 01:00:091196bool IsLoggingToFileEnabled() {
1197 return g_logging_destination & LOG_TO_FILE;
1198}
1199
Jan Wilken Dörrieb630aca2019-12-04 10:59:111200std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521201 if (g_log_file_name)
1202 return *g_log_file_name;
Jan Wilken Dörrieb630aca2019-12-04 10:59:111203 return std::wstring();
[email protected]f01b88a2013-02-27 22:04:001204}
1205#endif
1206
Xiyuan Xiaa0559da2022-05-05 19:42:451207#if !BUILDFLAG(USE_RUNTIME_VLOG)
1208int GetDisableAllVLogLevel() {
1209 return -1;
1210}
1211#endif // !BUILDFLAG(USE_RUNTIME_VLOG)
1212
Fergal Daly432aa7c2022-06-14 07:30:541213// Used for testing. Declared in test/scoped_logging_settings.h.
1214ScopedVmoduleSwitches::ScopedVmoduleSwitches() = default;
1215#if BUILDFLAG(USE_RUNTIME_VLOG)
1216VlogInfo* ScopedVmoduleSwitches::CreateVlogInfoWithSwitches(
1217 const std::string& vmodule_switch) {
1218 // Try get a VlogInfo on which to base this.
1219 // First ensure that VLOG has been initialized.
1220 MaybeInitializeVlogInfo();
1221
1222 // Getting this now and setting it later is racy, however if a
1223 // ScopedVmoduleSwitches is being used on multiple threads that requires
1224 // further coordination and avoids this race.
1225 VlogInfo* base_vlog_info = GetVlogInfo();
1226 if (!base_vlog_info) {
1227 // Base is |nullptr|, so just create it from scratch.
1228 return new VlogInfo(/*v_switch_=*/"", vmodule_switch, &g_min_log_level);
1229 }
1230 return base_vlog_info->WithSwitches(vmodule_switch);
1231}
1232
1233void ScopedVmoduleSwitches::InitWithSwitches(
1234 const std::string& vmodule_switch) {
1235 // Make sure we are only initialized once.
1236 CHECK(!scoped_vlog_info_);
1237 {
1238#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
1239 // See comments on |g_vlog_info|.
1240 ScopedLeakSanitizerDisabler lsan_disabler;
1241#endif // defined(LEAK_SANITIZER)
1242 scoped_vlog_info_ = CreateVlogInfoWithSwitches(vmodule_switch);
1243 }
1244 previous_vlog_info_ = ExchangeVlogInfo(scoped_vlog_info_);
1245}
1246
1247ScopedVmoduleSwitches::~ScopedVmoduleSwitches() {
1248 VlogInfo* replaced_vlog_info = ExchangeVlogInfo(previous_vlog_info_);
1249 // Make sure something didn't replace our scoped VlogInfo while we weren't
1250 // looking.
1251 CHECK_EQ(replaced_vlog_info, scoped_vlog_info_);
1252}
1253#else
1254void ScopedVmoduleSwitches::InitWithSwitches(
1255 const std::string& vmodule_switch) {}
1256
1257ScopedVmoduleSwitches::~ScopedVmoduleSwitches() = default;
1258#endif // BUILDFLAG(USE_RUNTIME_VLOG)
1259
[email protected]96fd0032009-04-24 00:13:081260} // namespace logging
initial.commitd7cae122008-07-26 21:49:381261
[email protected]81411c62014-07-08 23:03:061262std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391263 return out << (wstr ? base::WStringPiece(wstr) : base::WStringPiece());
1264}
1265
1266std::ostream& std::operator<<(std::ostream& out, const std::wstring& wstr) {
1267 return out << base::WStringPiece(wstr);
1268}
1269
1270std::ostream& std::operator<<(std::ostream& out, const char16_t* str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461271 return out << (str16 ? base::StringPiece16(str16) : base::StringPiece16());
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391272}
1273
1274std::ostream& std::operator<<(std::ostream& out, const std::u16string& str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461275 return out << base::StringPiece16(str16);
initial.commitd7cae122008-07-26 21:49:381276}