blob: b1b0af0710f28ecb5dce618b9f1a088264f51636 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
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"
Marshall Greenblatt280eb4f2023-02-28 00:18:4423#include "base/process/process_handle.h"
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:3924#include "base/strings/string_piece.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
Peter Boström871f916a2022-08-09 22:36:2729#if !BUILDFLAG(IS_NACL)
30#include "base/auto_reset.h"
31#include "base/debug/crash_logging.h"
32#endif // !BUILDFLAG(IS_NACL)
33
Hans Wennborged2126e2022-08-02 14:44:5834#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
35#include "base/debug/leak_annotations.h"
36#endif // defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
37
Xiaohan Wang38e4ebb2022-01-19 06:57:4338#if BUILDFLAG(IS_WIN)
[email protected]e36ddc82009-12-08 04:22:5039#include <io.h>
alex-accc1bde62017-04-19 08:33:5540#include <windows.h>
[email protected]f6abeba2008-08-08 13:27:2841typedef HANDLE FileHandle;
[email protected]e36ddc82009-12-08 04:22:5042// Windows warns on using write(). It prefers _write().
43#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
44// Windows doesn't define STDERR_FILENO. Define it here.
45#define STDERR_FILENO 2
Eric Noyaufce100702017-10-16 09:46:3446
Xiaohan Wang38e4ebb2022-01-19 06:57:4347#elif BUILDFLAG(IS_APPLE)
mark4c7449c2015-11-10 19:53:4248#include <CoreFoundation/CoreFoundation.h>
Avi Drissmanba195b32022-05-19 02:53:3449#include <mach-o/dyld.h>
[email protected]f6abeba2008-08-08 13:27:2850#include <mach/mach.h>
51#include <mach/mach_time.h>
Avi Drissmanba195b32022-05-19 02:53:3452#include <os/log.h>
Eric Noyaufce100702017-10-16 09:46:3453
Xiaohan Wang38e4ebb2022-01-19 06:57:4354#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
55#if BUILDFLAG(IS_NACL)
thestig75f87352014-12-03 21:42:2756#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0857#endif
[email protected]052f1b52008-11-06 21:43:0758#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5959#endif
60
Xiaohan Wang38e4ebb2022-01-19 06:57:4361#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:0262#include "base/fuchsia/scoped_fx_logger.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3963#endif
64
Xiaohan Wang38e4ebb2022-01-19 06:57:4365#if BUILDFLAG(IS_ANDROID)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3966#include <android/log.h>
67#endif
68
Xiaohan Wang38e4ebb2022-01-19 06:57:4369#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:2070#include <errno.h>
mark4c7449c2015-11-10 19:53:4271#include <paths.h>
[email protected]f6abeba2008-08-08 13:27:2872#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0073#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2874#include <string.h>
mark4c7449c2015-11-10 19:53:4275#include <sys/stat.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"
89#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:2890#include "base/containers/stack.h"
[email protected]eb4c4d032012-04-03 18:45:0591#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5092#include "base/debug/debugger.h"
93#include "base/debug/stack_trace.h"
Alan Cutter9b0e1ab2019-03-21 04:22:1694#include "base/debug/task_trace.h"
Avi Drissman63e1f992023-01-13 18:54:4395#include "base/functional/callback.h"
Yannic Bonenberger3dcd7fe2019-06-08 11:01:4596#include "base/no_destructor.h"
Sharon Yanga4b908de2019-05-07 22:19:0397#include "base/path_service.h"
[email protected]2025d002012-11-14 20:54:3598#include "base/posix/eintr_wrapper.h"
Xianzhu Wangae8d96a32018-10-16 20:41:1399#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:01100#include "base/strings/string_util.h"
101#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42102#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07103#include "base/strings/utf_string_conversions.h"
Benoit Lize5c98a832020-07-07 16:32:01104#include "base/synchronization/lock.h"
Yuta Hijikata9b7279a2020-08-26 16:10:54105#include "base/test/scoped_logging_settings.h"
[email protected]63e66802012-01-18 21:21:09106#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36107#include "base/vlog.h"
Yuta Hijikata000df18f2020-11-18 06:55:58108#include "build/chromeos_buildflags.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39109
Xiaohan Wang38e4ebb2022-01-19 06:57:43110#if BUILDFLAG(IS_WIN)
Cliff Smolinskyc5c52102019-05-03 20:51:54111#include "base/win/win_util.h"
112#endif
113
Xiaohan Wang38e4ebb2022-01-19 06:57:43114#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24115#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04116#endif
[email protected]52a261f2009-03-03 15:01:12117
Yuta Hijikata000df18f2020-11-18 06:55:58118#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:53119#include "base/files/scoped_file.h"
120#endif
121
initial.commitd7cae122008-07-26 21:49:38122namespace logging {
123
[email protected]064aa162011-12-03 00:30:08124namespace {
125
Fergal Dalyfacfaf92022-06-02 04:47:55126int g_min_log_level = 0;
127
Xiyuan Xiaa0559da2022-05-05 19:42:45128#if BUILDFLAG(USE_RUNTIME_VLOG)
Fergal Dalycac6ddc2022-05-24 17:42:03129// NOTE: Once |g_vlog_info| has been initialized, it might be in use
130// by another thread. Never delete the old VLogInfo, just create a second
131// one and overwrite. We need to use leak-san annotations on this intentional
132// leak.
133//
134// This can be read/written on multiple threads. In tests we don't see that
135// causing a problem as updates tend to happen early. Atomic ensures there are
136// no problems. To avoid some of the overhead of Atomic, we use
137// |load(std::memory_order_acquire)| and |store(...,
Fergal Daly432aa7c2022-06-14 07:30:54138// std::memory_order_release)| when reading or writing. This guarantees that the
139// referenced object is available at the time the |g_vlog_info| is read and that
140// |g_vlog_info| is updated atomically.
141//
142// Do not access this directly. You must use |GetVlogInfo|, |InitializeVlogInfo|
143// and/or |ExchangeVlogInfo|.
Fergal Dalycac6ddc2022-05-24 17:42:03144std::atomic<VlogInfo*> g_vlog_info = nullptr;
Fergal Dalyfacfaf92022-06-02 04:47:55145
Fergal Daly432aa7c2022-06-14 07:30:54146VlogInfo* GetVlogInfo() {
147 return g_vlog_info.load(std::memory_order_acquire);
148}
149
150// Sets g_vlog_info if it is not already set. Checking that it's not already set
151// prevents logging initialization (which can come late in test setup) from
152// overwriting values set via ScopedVmoduleSwitches.
153bool InitializeVlogInfo(VlogInfo* vlog_info) {
154 VlogInfo* previous_vlog_info = nullptr;
155 return g_vlog_info.compare_exchange_strong(previous_vlog_info, vlog_info);
156}
157
158VlogInfo* ExchangeVlogInfo(VlogInfo* vlog_info) {
159 return g_vlog_info.exchange(vlog_info);
160}
161
Fergal Dalyfacfaf92022-06-02 04:47:55162// Creates a VlogInfo from the commandline if it has been initialized and if it
163// contains relevant switches, otherwise this returns |nullptr|.
Fergal Daly432aa7c2022-06-14 07:30:54164std::unique_ptr<VlogInfo> VlogInfoFromCommandLine() {
Fergal Dalyfacfaf92022-06-02 04:47:55165 if (!base::CommandLine::InitializedForCurrentProcess())
166 return nullptr;
167 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
168 if (!command_line->HasSwitch(switches::kV) &&
169 !command_line->HasSwitch(switches::kVModule)) {
170 return nullptr;
171 }
172#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
173 // See comments on |g_vlog_info|.
174 ScopedLeakSanitizerDisabler lsan_disabler;
175#endif // defined(LEAK_SANITIZER)
Fergal Daly432aa7c2022-06-14 07:30:54176 return std::make_unique<VlogInfo>(
177 command_line->GetSwitchValueASCII(switches::kV),
178 command_line->GetSwitchValueASCII(switches::kVModule), &g_min_log_level);
179}
180
181// If the commandline is initialized for the current process this will
182// initialize g_vlog_info. If there are no VLOG switches, it will initialize it
183// to |nullptr|.
184void MaybeInitializeVlogInfo() {
185 if (base::CommandLine::InitializedForCurrentProcess()) {
186 std::unique_ptr<VlogInfo> vlog_info = VlogInfoFromCommandLine();
187 if (vlog_info) {
188 // VlogInfoFromCommandLine is annotated with ScopedLeakSanitizerDisabler
189 // so it's allowed to leak. If the object was installed, we release it.
190 if (InitializeVlogInfo(vlog_info.get())) {
191 vlog_info.release();
192 }
193 }
194 }
Fergal Dalyfacfaf92022-06-02 04:47:55195}
Xiyuan Xiaa0559da2022-05-05 19:42:45196#endif // BUILDFLAG(USE_RUNTIME_VLOG)
initial.commitd7cae122008-07-26 21:49:38197
Jeffrey Young551bce62022-06-24 19:08:17198#if !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
199
200// Warn developers that vlog command line settings are being ignored.
201void MaybeWarnVmodule() {
202 if (base::CommandLine::InitializedForCurrentProcess()) {
203 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
204 if (command_line->HasSwitch(switches::kV) ||
205 command_line->HasSwitch(switches::kVModule)) {
206 LOG(WARNING)
207 << "--" << switches::kV << " and --" << switches::kVModule
208 << " are currently ignored. See comments in base/logging.h on "
209 "proper usage of USE_RUNTIME_VLOG.";
210 }
211 }
212}
213
214#endif // !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
215
weza245bd072017-06-18 23:26:34216const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
Daniel Chengf45f47602022-02-28 22:38:32217static_assert(LOGGING_NUM_SEVERITIES == std::size(log_severity_names),
weza245bd072017-06-18 23:26:34218 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38219
thestig75f87352014-12-03 21:42:27220const char* log_severity_name(int severity) {
Lei Zhang93dd42572020-10-23 18:45:53221 if (severity >= 0 && severity < LOGGING_NUM_SEVERITIES)
[email protected]80f360a2014-01-23 01:36:19222 return log_severity_names[severity];
223 return "UNKNOWN";
224}
225
Sharon Yang7cb919a2019-05-20 20:27:15226// Specifies the process' logging sink(s), represented as a combination of
227// LoggingDestination values joined by bitwise OR.
Peter Kasting40cfeae2021-06-14 12:21:48228uint32_t g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38229
Georg Neisffe34f652021-12-27 21:42:36230#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata1fc8f6342020-09-01 03:25:56231// Specifies the format of log header for chrome os.
232LogFormat g_log_format = LogFormat::LOG_FORMAT_SYSLOG;
Yuta Hijikata9b7279a2020-08-26 16:10:54233#endif
234
Xiaohan Wang38e4ebb2022-01-19 06:57:43235#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02236// Retains system logging structures.
237base::ScopedFxLogger& GetScopedFxLogger() {
238 static base::NoDestructor<base::ScopedFxLogger> logger;
239 return *logger;
240}
241#endif
242
Lei Zhang93dd42572020-10-23 18:45:53243// For LOGGING_ERROR and above, always print to stderr.
244const int kAlwaysPrintErrorLevel = LOGGING_ERROR;
[email protected]a33c9892008-08-25 20:10:31245
[email protected]614e9fa2008-08-11 22:52:59246// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38247// will be lazily initialized to the default value when it is
248// first needed.
jdoerrie5c4dc4e2019-02-01 18:02:33249using PathString = base::FilePath::StringType;
thestig3e4787d2015-05-19 19:31:52250PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38251
thestig3e4787d2015-05-19 19:31:52252// This file is lazily opened and the handle may be nullptr
253FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38254
thestig3e4787d2015-05-19 19:31:52255// What should be prepended to each message?
256bool g_log_process_id = false;
257bool g_log_thread_id = false;
258bool g_log_timestamp = true;
259bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31260const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38261
[email protected]81e0a852010-08-17 00:38:12262// Should we pop up fatal debug messages in a dialog?
263bool show_error_dialogs = false;
264
initial.commitd7cae122008-07-26 21:49:38265// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55266// the debug message dialog and process termination. Assert handlers are stored
267// in stack to allow overriding and restoring.
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45268base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() {
269 static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance;
270 return *instance;
271}
alex-accc1bde62017-04-19 08:33:55272
[email protected]2b07b8412009-11-25 15:26:34273// A log message handler that gets notified of every log message we process.
Wez244270362021-05-04 22:50:58274LogMessageHandlerFunction g_log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38275
avi9b6f42932015-12-26 22:15:14276uint64_t TickCount() {
Xiaohan Wang38e4ebb2022-01-19 06:57:43277#if BUILDFLAG(IS_WIN)
[email protected]f8588472008-11-05 23:17:24278 return GetTickCount();
Xiaohan Wang38e4ebb2022-01-19 06:57:43279#elif BUILDFLAG(IS_FUCHSIA)
Peter Kasting2f61c8b2022-07-19 23:43:46280 return static_cast<uint64_t>(
281 zx_clock_get_monotonic() /
282 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond));
Xiaohan Wang38e4ebb2022-01-19 06:57:43283#elif BUILDFLAG(IS_APPLE)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39284 return mach_absolute_time();
Xiaohan Wang38e4ebb2022-01-19 06:57:43285#elif BUILDFLAG(IS_NACL)
[email protected]19ea84ca2010-11-12 08:37:08286 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
287 // So we have to use clock() for now.
288 return clock();
Xiaohan Wang38e4ebb2022-01-19 06:57:43289#elif BUILDFLAG(IS_POSIX)
[email protected]052f1b52008-11-06 21:43:07290 struct timespec ts;
291 clock_gettime(CLOCK_MONOTONIC, &ts);
292
Peter Kastingaca170a2022-06-30 17:18:48293 uint64_t absolute_micro = static_cast<uint64_t>(ts.tv_sec) * 1000000 +
294 static_cast<uint64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07295
296 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24297#endif
298}
299
[email protected]614e9fa2008-08-11 22:52:59300void DeleteFilePath(const PathString& log_name) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43301#if BUILDFLAG(IS_WIN)
Jan Wilken Dörrieb630aca2019-12-04 10:59:11302 DeleteFile(log_name.c_str());
Xiaohan Wang38e4ebb2022-01-19 06:57:43303#elif BUILDFLAG(IS_NACL)
[email protected]ac07ec52013-04-22 17:32:45304 // Do nothing; unlink() isn't supported on NaCl.
Xiaohan Wang38e4ebb2022-01-19 06:57:43305#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59306 unlink(log_name.c_str());
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39307#else
308#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28309#endif
310}
initial.commitd7cae122008-07-26 21:49:38311
[email protected]5f95d532010-10-01 17:16:58312PathString GetDefaultLogFile() {
Xiaohan Wang38e4ebb2022-01-19 06:57:43313#if BUILDFLAG(IS_WIN)
[email protected]5b84fe32010-09-14 22:24:55314 // On Windows we use the same path as the exe.
Jan Wilken Dörrieb630aca2019-12-04 10:59:11315 wchar_t module_name[MAX_PATH];
316 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58317
scottmgfc5b7072015-01-27 21:46:28318 PathString log_name = module_name;
319 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58320 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28321 log_name.erase(last_backslash + 1);
Jan Wilken Dörrieb630aca2019-12-04 10:59:11322 log_name += FILE_PATH_LITERAL("debug.log");
scottmgfc5b7072015-01-27 21:46:28323 return log_name;
Xiaohan Wang38e4ebb2022-01-19 06:57:43324#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55325 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58326 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55327#endif
328}
329
ananta61762fb2015-09-18 01:00:09330// We don't need locks on Windows for atomically appending to files. The OS
331// provides this functionality.
Xiaohan Wang38e4ebb2022-01-19 06:57:43332#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55333
Olivier Lice976792022-09-27 21:35:24334// Provides a lock to synchronize appending to the log file across
335// threads. This can be required to support NFS file systems even on OSes that
336// provide atomic append operations in most cases. It should be noted that this
337// lock is not not shared across processes. When using NFS filesystems
338// protection against clobbering between different processes will be best-effort
339// and provided by the OS. See
340// https://man7.org/linux/man-pages/man2/open.2.html.
341//
342// The lock also protects initializing and closing the log file which can
343// happen concurrently with logging on some platforms like ChromeOS that need to
344// redirect logging by calling BaseInitLoggingImpl() twice.
Benoit Lize5c98a832020-07-07 16:32:01345base::Lock& GetLoggingLock() {
346 static base::NoDestructor<base::Lock> lock;
347 return *lock;
348}
[email protected]5b84fe32010-09-14 22:24:55349
Xiaohan Wang38e4ebb2022-01-19 06:57:43350#endif // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
ananta61762fb2015-09-18 01:00:09351
thestig3e4787d2015-05-19 19:31:52352// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38353// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52354// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38355bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52356 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38357 return true;
358
thestig3e4787d2015-05-19 19:31:52359 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59360 // Nobody has called InitLogging to specify a debug log file, so here we
361 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52362 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38363 }
364
Robbie McElrath8bf49842019-08-20 22:22:53365 if ((g_logging_destination & LOG_TO_FILE) == 0)
366 return true;
367
Xiaohan Wang38e4ebb2022-01-19 06:57:43368#if BUILDFLAG(IS_WIN)
Robbie McElrath8bf49842019-08-20 22:22:53369 // The FILE_APPEND_DATA access mask ensures that the file is atomically
370 // appended to across accesses from multiple threads.
371 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
372 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
Jan Wilken Dörrieb630aca2019-12-04 10:59:11373 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
Robbie McElrath8bf49842019-08-20 22:22:53374 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
375 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
376 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
377 // We are intentionally not using FilePath or FileUtil here to reduce the
378 // dependencies of the logging implementation. For e.g. FilePath and
379 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
380 // some consumers of base logging like chrome_elf, etc.
381 // Please don't change the code below to use FilePath.
382 // try the current directory
Jan Wilken Dörrieb630aca2019-12-04 10:59:11383 wchar_t system_buffer[MAX_PATH];
Robbie McElrath8bf49842019-08-20 22:22:53384 system_buffer[0] = 0;
Daniel Chengf45f47602022-02-28 22:38:32385 DWORD len = ::GetCurrentDirectory(std::size(system_buffer), system_buffer);
386 if (len == 0 || len > std::size(system_buffer))
Robbie McElrath8bf49842019-08-20 22:22:53387 return false;
388
389 *g_log_file_name = system_buffer;
390 // Append a trailing backslash if needed.
391 if (g_log_file_name->back() != L'\\')
Jan Wilken Dörrieb630aca2019-12-04 10:59:11392 *g_log_file_name += FILE_PATH_LITERAL("\\");
393 *g_log_file_name += FILE_PATH_LITERAL("debug.log");
Robbie McElrath8bf49842019-08-20 22:22:53394
Jan Wilken Dörrieb630aca2019-12-04 10:59:11395 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52396 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
397 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
398 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
Robbie McElrath8bf49842019-08-20 22:22:53399 g_log_file = nullptr;
[email protected]78c6dd62009-06-08 23:29:11400 return false;
Robbie McElrath8bf49842019-08-20 22:22:53401 }
402 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43403#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Robbie McElrath8bf49842019-08-20 22:22:53404 g_log_file = fopen(g_log_file_name->c_str(), "a");
405 if (g_log_file == nullptr)
406 return false;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39407#else
408#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28409#endif
[email protected]1d8c2702008-08-19 23:39:32410
initial.commitd7cae122008-07-26 21:49:38411 return true;
412}
413
[email protected]17dcf752013-07-15 21:47:09414void CloseFile(FileHandle log) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43415#if BUILDFLAG(IS_WIN)
[email protected]17dcf752013-07-15 21:47:09416 CloseHandle(log);
Xiaohan Wang38e4ebb2022-01-19 06:57:43417#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09418 fclose(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39419#else
420#error Unsupported platform
[email protected]17dcf752013-07-15 21:47:09421#endif
422}
423
424void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52425 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09426 return;
427
thestig3e4787d2015-05-19 19:31:52428 CloseFile(g_log_file);
429 g_log_file = nullptr;
Robbie McElrath8bf49842019-08-20 22:22:53430
431 // If we initialized logging via an externally-provided file descriptor, we
432 // won't have a log path set and shouldn't try to reopen the log file.
433 if (!g_log_file_name)
434 g_logging_destination &= ~LOG_TO_FILE;
[email protected]17dcf752013-07-15 21:47:09435}
436
Xiaohan Wang38e4ebb2022-01-19 06:57:43437#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02438inline FuchsiaLogSeverity LogSeverityToFuchsiaLogSeverity(
439 LogSeverity severity) {
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38440 switch (severity) {
441 case LOGGING_INFO:
Wez45e3ffe2021-09-24 02:10:02442 return FUCHSIA_LOG_INFO;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38443 case LOGGING_WARNING:
Wez45e3ffe2021-09-24 02:10:02444 return FUCHSIA_LOG_WARNING;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38445 case LOGGING_ERROR:
Wez45e3ffe2021-09-24 02:10:02446 return FUCHSIA_LOG_ERROR;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38447 case LOGGING_FATAL:
448 // Don't use FX_LOG_FATAL, otherwise fx_logger_log() will abort().
Wez45e3ffe2021-09-24 02:10:02449 return FUCHSIA_LOG_ERROR;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38450 }
451 if (severity > -3) {
452 // LOGGING_VERBOSE levels 1 and 2.
Wez45e3ffe2021-09-24 02:10:02453 return FUCHSIA_LOG_DEBUG;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38454 }
455 // LOGGING_VERBOSE levels 3 and higher, or incorrect levels.
Wez45e3ffe2021-09-24 02:10:02456 return FUCHSIA_LOG_TRACE;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38457}
Peter Boström3ed27e82022-11-17 01:13:23458#endif // BUILDFLAG(IS_FUCHSIA)
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38459
Benoit Lizeed678192022-01-20 10:14:54460void WriteToFd(int fd, const char* data, size_t length) {
461 size_t bytes_written = 0;
Peter Kastingaca170a2022-06-30 17:18:48462 long rv;
Benoit Lizeed678192022-01-20 10:14:54463 while (bytes_written < length) {
464 rv = HANDLE_EINTR(write(fd, data + bytes_written, length - bytes_written));
465 if (rv < 0) {
466 // Give up, nothing we can do now.
467 break;
468 }
Peter Kastingde85e742022-06-01 17:41:54469 bytes_written += static_cast<size_t>(rv);
Benoit Lizeed678192022-01-20 10:14:54470 }
471}
472
Peter Boström871f916a2022-08-09 22:36:27473void SetLogFatalCrashKey(LogMessage* log_message) {
474#if !BUILDFLAG(IS_NACL)
475 // In case of an out-of-memory condition, this code could be reentered when
476 // constructing and storing the key. Using a static is not thread-safe, but if
477 // multiple threads are in the process of a fatal crash at the same time, this
478 // should work.
479 static bool guarded = false;
480 if (guarded)
481 return;
482
483 base::AutoReset<bool> guard(&guarded, true);
484
485 static auto* const crash_key = base::debug::AllocateCrashKeyString(
486 "LOG_FATAL", base::debug::CrashKeySize::Size1024);
487 base::debug::SetCrashKeyString(crash_key, log_message->BuildCrashString());
488
489#endif // !BUILDFLAG(IS_NACL)
490}
491
492std::string BuildCrashString(const char* file,
493 int line,
494 const char* message_without_prefix) {
495 // Only log last path component.
496 if (file) {
Peter Boström39dd8c82022-08-12 00:39:37497 const char* slash = strrchr(file,
498#if BUILDFLAG(IS_WIN)
499 '\\'
500#else
501 '/'
502#endif // BUILDFLAG(IS_WIN)
503 );
Peter Boström871f916a2022-08-09 22:36:27504 if (slash) {
505 file = slash + 1;
506 }
507 }
508
509 return base::StringPrintf("%s:%d: %s", file, line, message_without_prefix);
510}
511
Rasika Navarange45b5f602023-01-03 12:05:56512// Invokes macro to record trace event when a log message is emitted.
513void traceLogMessage(const char* file, int line, const std::string& message) {
514 TRACE_EVENT_INSTANT("log", "LogMessage", [&](perfetto::EventContext ctx) {
515 perfetto::protos::pbzero::LogMessage* log = ctx.event()->set_log_message();
516 log->set_source_location_iid(base::trace_event::InternedSourceLocation::Get(
517 &ctx, base::trace_event::TraceSourceLocation(/*function_name=*/nullptr,
518 file, line)));
519 log->set_body_iid(
520 base::trace_event::InternedLogMessage::Get(&ctx, message));
521 });
522}
523
[email protected]064aa162011-12-03 00:30:08524} // namespace
525
Wez02cedeba2022-07-26 12:48:38526#if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
Lei Zhang93dd42572020-10-23 18:45:53527// In DCHECK-enabled Chrome builds, allow the meaning of LOGGING_DCHECK to be
Wez289477f2017-08-24 20:51:30528// determined at run-time. We default it to INFO, to avoid it triggering
529// crashes before the run-time has explicitly chosen the behaviour.
Lei Zhang93dd42572020-10-23 18:45:53530BASE_EXPORT logging::LogSeverity LOGGING_DCHECK = LOGGING_INFO;
Wez02cedeba2022-07-26 12:48:38531#endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30532
scottmg3c957a52016-12-10 20:57:59533// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
534// an object of the correct type on the LHS of the unused part of the ternary
535// operator.
536std::ostream* g_swallow_stream;
537
[email protected]5e3f7c22013-06-21 21:15:33538bool BaseInitLoggingImpl(const LoggingSettings& settings) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43539#if BUILDFLAG(IS_NACL)
Sharon Yang7cb919a2019-05-20 20:27:15540 // Can log only to the system debug log and stderr.
541 CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR),
542 0u);
[email protected]ac07ec52013-04-22 17:32:45543#endif
Robbie McElrath8bf49842019-08-20 22:22:53544
Georg Neisffe34f652021-12-27 21:42:36545#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata8a93e522020-09-25 08:59:57546 g_log_format = settings.log_format;
547#endif
548
Xiyuan Xiaa0559da2022-05-05 19:42:45549#if BUILDFLAG(USE_RUNTIME_VLOG)
Fergal Daly432aa7c2022-06-14 07:30:54550 MaybeInitializeVlogInfo();
Fergal Dalycac6ddc2022-05-24 17:42:03551#endif // BUILDFLAG(USE_RUNTIME_VLOG)
[email protected]99b7c57f2010-09-29 19:26:36552
Jeffrey Young551bce62022-06-24 19:08:17553#if !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
554 MaybeWarnVmodule();
555#endif // !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
556
thestig3e4787d2015-05-19 19:31:52557 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38558
Xiaohan Wang38e4ebb2022-01-19 06:57:43559#if BUILDFLAG(IS_FUCHSIA)
Wez224c0bf62019-05-24 19:26:13560 if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) {
Wez5d4a666c2021-10-04 16:41:36561 GetScopedFxLogger() = base::ScopedFxLogger::CreateForProcess();
Wez224c0bf62019-05-24 19:26:13562 }
563#endif
564
[email protected]5e3f7c22013-06-21 21:15:33565 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52566 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21567 return true;
initial.commitd7cae122008-07-26 21:49:38568
Xiaohan Wang38e4ebb2022-01-19 06:57:43569#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:01570 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09571#endif
[email protected]17dcf752013-07-15 21:47:09572
573 // Calling InitLogging twice or after some log call has already opened the
574 // default log file will re-initialize to the new options.
575 CloseLogFileUnlocked();
576
Yuta Hijikata000df18f2020-11-18 06:55:58577#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:53578 if (settings.log_file) {
579 DCHECK(!settings.log_file_path);
580 g_log_file = settings.log_file;
581 return true;
582 }
583#endif
Lei Zhang93dd42572020-10-23 18:45:53584
Xiaohan Wang5411974b2020-10-10 19:36:12585 DCHECK(settings.log_file_path) << "LOG_TO_FILE set but no log_file_path!";
Robbie McElrath8bf49842019-08-20 22:22:53586
thestig3e4787d2015-05-19 19:31:52587 if (!g_log_file_name)
588 g_log_file_name = new PathString();
Robbie McElrath8bf49842019-08-20 22:22:53589 *g_log_file_name = settings.log_file_path;
[email protected]5e3f7c22013-06-21 21:15:33590 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52591 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38592
[email protected]c7d5da992010-10-28 00:20:21593 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38594}
595
596void SetMinLogLevel(int level) {
Lei Zhang93dd42572020-10-23 18:45:53597 g_min_log_level = std::min(LOGGING_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38598}
599
600int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52601 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38602}
603
skobesc78c0ad72015-12-07 20:21:23604bool ShouldCreateLogMessage(int severity) {
605 if (severity < g_min_log_level)
606 return false;
607
Wez6c8acb82019-07-18 00:32:59608 // Return true here unless we know ~LogMessage won't do anything.
Wez244270362021-05-04 22:50:58609 return g_logging_destination != LOG_NONE || g_log_message_handler ||
skobesc78c0ad72015-12-07 20:21:23610 severity >= kAlwaysPrintErrorLevel;
611}
612
Wez6c8acb82019-07-18 00:32:59613// Returns true when LOG_TO_STDERR flag is set, or |severity| is high.
614// If |severity| is high then true will be returned when no log destinations are
615// set, or only LOG_TO_FILE is set, since that is useful for local development
616// and debugging.
617bool ShouldLogToStderr(int severity) {
618 if (g_logging_destination & LOG_TO_STDERR)
619 return true;
Wez82ba0502022-05-11 08:50:08620
621#if BUILDFLAG(IS_FUCHSIA)
622 // Fuchsia will persist data logged to stdio by a component, so do not emit
623 // logs to stderr unless explicitly configured to do so.
624 return false;
625#else
Wez6c8acb82019-07-18 00:32:59626 if (severity >= kAlwaysPrintErrorLevel)
627 return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
628 return false;
Wez82ba0502022-05-11 08:50:08629#endif
Wez6c8acb82019-07-18 00:32:59630}
631
[email protected]162ac0f2010-11-04 15:50:49632int GetVlogVerbosity() {
633 return std::max(-1, LOG_INFO - GetMinLogLevel());
634}
635
[email protected]99b7c57f2010-09-29 19:26:36636int GetVlogLevelHelper(const char* file, size_t N) {
637 DCHECK_GT(N, 0U);
Xiyuan Xiaa0559da2022-05-05 19:42:45638
639#if BUILDFLAG(USE_RUNTIME_VLOG)
thestig3e4787d2015-05-19 19:31:52640 // Note: |g_vlog_info| may change on a different thread during startup
641 // (but will always be valid or nullptr).
Fergal Daly432aa7c2022-06-14 07:30:54642 VlogInfo* vlog_info = GetVlogInfo();
[email protected]064aa162011-12-03 00:30:08643 return vlog_info ?
644 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49645 GetVlogVerbosity();
Xiyuan Xiaa0559da2022-05-05 19:42:45646#else
647 return GetVlogVerbosity();
648#endif // BUILDFLAG(USE_RUNTIME_VLOG)
[email protected]99b7c57f2010-09-29 19:26:36649}
650
initial.commitd7cae122008-07-26 21:49:38651void SetLogItems(bool enable_process_id, bool enable_thread_id,
652 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52653 g_log_process_id = enable_process_id;
654 g_log_thread_id = enable_thread_id;
655 g_log_timestamp = enable_timestamp;
656 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38657}
658
James Cooka0536c32018-08-01 20:13:31659void SetLogPrefix(const char* prefix) {
660 DCHECK(!prefix ||
661 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
662 g_log_prefix = prefix;
663}
664
[email protected]81e0a852010-08-17 00:38:12665void SetShowErrorDialogs(bool enable_dialogs) {
666 show_error_dialogs = enable_dialogs;
667}
668
alex-accc1bde62017-04-19 08:33:55669ScopedLogAssertHandler::ScopedLogAssertHandler(
670 LogAssertHandlerFunction handler) {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45671 GetLogAssertHandlerStack().push(std::move(handler));
alex-accc1bde62017-04-19 08:33:55672}
673
674ScopedLogAssertHandler::~ScopedLogAssertHandler() {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45675 GetLogAssertHandlerStack().pop();
initial.commitd7cae122008-07-26 21:49:38676}
677
[email protected]2b07b8412009-11-25 15:26:34678void SetLogMessageHandler(LogMessageHandlerFunction handler) {
Wez244270362021-05-04 22:50:58679 g_log_message_handler = handler;
[email protected]2b07b8412009-11-25 15:26:34680}
681
[email protected]64e5cc02010-11-03 19:20:27682LogMessageHandlerFunction GetLogMessageHandler() {
Wez244270362021-05-04 22:50:58683 return g_log_message_handler;
[email protected]64e5cc02010-11-03 19:20:27684}
685
[email protected]f2c05492014-06-17 12:04:23686#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22687// Displays a message box to the user with the error message in it.
688// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25689// This is for developers only; we don't use this in circumstances
690// (like release builds) where users could see it, since users don't
691// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22692void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38693 if (str.empty())
694 return;
695
[email protected]81e0a852010-08-17 00:38:12696 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44697 return;
698
Xiaohan Wang38e4ebb2022-01-19 06:57:43699#if BUILDFLAG(IS_WIN)
[email protected]561513f2010-12-16 23:29:25700 // We intentionally don't implement a dialog on other platforms.
701 // You can just look at stderr.
Cliff Smolinskyc5c52102019-05-03 20:51:54702 if (base::win::IsUser32AndGdi32Available()) {
703 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
704 MB_OK | MB_ICONHAND | MB_TOPMOST);
705 } else {
706 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
707 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43708#endif // BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38709}
[email protected]f2c05492014-06-17 12:04:23710#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38711
[email protected]eae9c062011-01-11 00:50:59712LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
713 : severity_(severity), file_(file), line_(line) {
714 Init(file, line);
715}
716
tnagel4a045d3f2015-07-12 14:19:28717LogMessage::LogMessage(const char* file, int line, const char* condition)
Lei Zhang93dd42572020-10-23 18:45:53718 : severity_(LOGGING_FATAL), file_(file), line_(line) {
tnagel4a045d3f2015-07-12 14:19:28719 Init(file, line);
720 stream_ << "Check failed: " << condition << ". ";
721}
722
initial.commitd7cae122008-07-26 21:49:38723LogMessage::~LogMessage() {
Peter Kasting28b51cf2022-06-28 15:02:43724 size_t stack_start = stream_.str().length();
Sven Zhengb11f397e2022-08-30 01:18:51725#if !defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_NACL) && !defined(__UCLIBC__) && \
726 !BUILDFLAG(IS_AIX)
Lei Zhang93dd42572020-10-23 18:45:53727 if (severity_ == LOGGING_FATAL && !base::debug::BeingDebugged()) {
brucedawson7c559eb2015-09-05 00:34:42728 // Include a stack trace on a fatal, unless a debugger is attached.
Sven Zhengb11f397e2022-08-30 01:18:51729 base::debug::StackTrace stack_trace;
730 stream_ << std::endl; // Newline to separate from log message.
731 stack_trace.OutputToStream(&stream_);
732 base::debug::TaskTrace task_trace;
733 if (!task_trace.empty())
734 task_trace.OutputToStream(&stream_);
735
736 // Include the IPC context, if any.
737 // TODO(chrisha): Integrate with symbolization once those tools exist!
738 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
739 if (task && task->ipc_hash) {
740 stream_ << "IPC message handler context: "
741 << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
742 }
743
744 // Include the crash keys, if any.
745 base::debug::OutputCrashKeysToStream(stream_);
[email protected]d1ccc35a2010-03-24 05:03:24746 }
[email protected]1d8c2702008-08-19 23:39:32747#endif
Sven Zhengb11f397e2022-08-30 01:18:51748 stream_ << std::endl;
[email protected]d1ccc35a2010-03-24 05:03:24749 std::string str_newline(stream_.str());
Rasika Navarange45b5f602023-01-03 12:05:56750 traceLogMessage(
751 file_, line_,
752 std::string(base::StringPiece(str_newline).substr(message_start_)));
[email protected]d1ccc35a2010-03-24 05:03:24753
Peter Boström871f916a2022-08-09 22:36:27754 if (severity_ == LOGGING_FATAL)
755 SetLogFatalCrashKey(this);
756
[email protected]2b07b8412009-11-25 15:26:34757 // Give any log message handler first dibs on the message.
Wez244270362021-05-04 22:50:58758 if (g_log_message_handler &&
759 g_log_message_handler(severity_, file_, line_, message_start_,
760 str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49761 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34762 return;
[email protected]162ac0f2010-11-04 15:50:49763 }
initial.commitd7cae122008-07-26 21:49:38764
thestig3e4787d2015-05-19 19:31:52765 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43766#if BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38767 OutputDebugStringA(str_newline.c_str());
Xiaohan Wang38e4ebb2022-01-19 06:57:43768#elif BUILDFLAG(IS_APPLE)
mark4c7449c2015-11-10 19:53:42769 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Avi Drissmanba195b32022-05-19 02:53:34770 // stderr. If stderr is /dev/null, also log via os_log. If there's something
771 // weird about stderr, assume that log messages are going nowhere and log
772 // via os_log too. Messages logged via os_log show up in Console.app.
mark4c7449c2015-11-10 19:53:42773 //
774 // Programs started by launchd, as UI applications normally are, have had
775 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
776 // a pipe to launchd, which logged what it received (see log_redirect_fd in
777 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
778 //
779 // Another alternative would be to determine whether stderr is a pipe to
Avi Drissmanba195b32022-05-19 02:53:34780 // launchd and avoid logging via os_log only in that case. See 10.7.5
mark4c7449c2015-11-10 19:53:42781 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Avi Drissmanba195b32022-05-19 02:53:34782 // both stderr and os_log even in tests, where it's undesirable to log to
783 // the system log at all.
Eric Noyaufce100702017-10-16 09:46:34784 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42785 struct stat stderr_stat;
786 if (fstat(fileno(stderr), &stderr_stat) == -1) {
787 return true;
788 }
789 if (!S_ISCHR(stderr_stat.st_mode)) {
790 return false;
791 }
792
793 struct stat dev_null_stat;
794 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
795 return true;
796 }
797
798 return !S_ISCHR(dev_null_stat.st_mode) ||
799 stderr_stat.st_rdev == dev_null_stat.st_rdev;
800 }();
801
Eric Noyaufce100702017-10-16 09:46:34802 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42803 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
804 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42805 CFBundleRef main_bundle = CFBundleGetMainBundle();
806 CFStringRef main_bundle_id_cf =
807 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34808 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42809 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34810 : std::string("");
mark4c7449c2015-11-10 19:53:42811
Eric Noyaufce100702017-10-16 09:46:34812 const class OSLog {
813 public:
814 explicit OSLog(const char* subsystem)
815 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
816 : OS_LOG_DEFAULT) {}
David Bienvenub4b441e2020-09-23 05:49:57817 OSLog(const OSLog&) = delete;
818 OSLog& operator=(const OSLog&) = delete;
Eric Noyaufce100702017-10-16 09:46:34819 ~OSLog() {
820 if (os_log_ != OS_LOG_DEFAULT) {
821 os_release(os_log_);
822 }
823 }
824 os_log_t get() const { return os_log_; }
825
826 private:
827 os_log_t os_log_;
Eric Noyaufce100702017-10-16 09:46:34828 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
829 const os_log_type_t os_log_type = [](LogSeverity severity) {
830 switch (severity) {
Lei Zhang93dd42572020-10-23 18:45:53831 case LOGGING_INFO:
Eric Noyaufce100702017-10-16 09:46:34832 return OS_LOG_TYPE_INFO;
Lei Zhang93dd42572020-10-23 18:45:53833 case LOGGING_WARNING:
Eric Noyaufce100702017-10-16 09:46:34834 return OS_LOG_TYPE_DEFAULT;
Lei Zhang93dd42572020-10-23 18:45:53835 case LOGGING_ERROR:
Eric Noyaufce100702017-10-16 09:46:34836 return OS_LOG_TYPE_ERROR;
Lei Zhang93dd42572020-10-23 18:45:53837 case LOGGING_FATAL:
Eric Noyaufce100702017-10-16 09:46:34838 return OS_LOG_TYPE_FAULT;
Avi Drissmana1d016c2022-05-12 21:58:20839 case LOGGING_VERBOSE:
840 return OS_LOG_TYPE_DEBUG;
Eric Noyaufce100702017-10-16 09:46:34841 default:
Avi Drissmana1d016c2022-05-12 21:58:20842 return OS_LOG_TYPE_DEFAULT;
Eric Noyaufce100702017-10-16 09:46:34843 }
844 }(severity_);
845 os_log_with_type(log.get(), os_log_type, "%{public}s",
846 str_newline.c_str());
mark4c7449c2015-11-10 19:53:42847 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43848#elif BUILDFLAG(IS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25849 android_LogPriority priority =
850 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50851 switch (severity_) {
Lei Zhang93dd42572020-10-23 18:45:53852 case LOGGING_INFO:
[email protected]3132e35c2011-07-07 20:46:50853 priority = ANDROID_LOG_INFO;
854 break;
Lei Zhang93dd42572020-10-23 18:45:53855 case LOGGING_WARNING:
[email protected]3132e35c2011-07-07 20:46:50856 priority = ANDROID_LOG_WARN;
857 break;
Lei Zhang93dd42572020-10-23 18:45:53858 case LOGGING_ERROR:
[email protected]3132e35c2011-07-07 20:46:50859 priority = ANDROID_LOG_ERROR;
860 break;
Lei Zhang93dd42572020-10-23 18:45:53861 case LOGGING_FATAL:
[email protected]3132e35c2011-07-07 20:46:50862 priority = ANDROID_LOG_FATAL;
863 break;
864 }
Tomasz Śniatowski23dd15af2019-02-15 08:32:03865 const char kAndroidLogTag[] = "chromium";
Xianzhu Wangae8d96a32018-10-16 20:41:13866#if DCHECK_IS_ON()
867 // Split the output by new lines to prevent the Android system from
868 // truncating the log.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03869 std::vector<std::string> lines = base::SplitString(
870 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
871 // str_newline has an extra newline appended to it (at the top of this
872 // function), so skip the last split element to avoid needlessly
873 // logging an empty string.
874 lines.pop_back();
875 for (const auto& line : lines)
876 __android_log_write(priority, kAndroidLogTag, line.c_str());
Xianzhu Wangae8d96a32018-10-16 20:41:13877#else
878 // The Android system may truncate the string if it's too long.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03879 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18880#endif
Xiaohan Wang38e4ebb2022-01-19 06:57:43881#elif BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02882 // LogMessage() will silently drop the message if the logger is not valid.
Weza38cc532021-12-16 22:58:20883 // Skip the final character of |str_newline|, since LogMessage() will add
884 // a newline.
885 const auto message = base::StringPiece(str_newline).substr(message_start_);
Peter Kasting2f61c8b2022-07-19 23:43:46886 GetScopedFxLogger().LogMessage(file_, static_cast<uint32_t>(line_),
Weza38cc532021-12-16 22:58:20887 message.substr(0, message.size() - 1),
888 LogSeverityToFuchsiaLogSeverity(severity_));
Xiaohan Wang38e4ebb2022-01-19 06:57:43889#endif // BUILDFLAG(IS_FUCHSIA)
Sharon Yang7cb919a2019-05-20 20:27:15890 }
891
Wez6c8acb82019-07-18 00:32:59892 if (ShouldLogToStderr(severity_)) {
Benoit Lizeed678192022-01-20 10:14:54893 // Not using fwrite() here, as there are crashes on Windows when CRT calls
894 // malloc() internally, triggering an OOM crash. This likely means that the
895 // process is close to OOM, but at least get the proper error message out,
896 // and give the caller a chance to free() up some resources. For instance if
897 // the calling code is:
898 //
899 // allocate_something();
900 // if (!TryToDoSomething()) {
901 // LOG(ERROR) << "Something went wrong";
902 // free_something();
903 // }
904 WriteToFd(STDERR_FILENO, str_newline.data(), str_newline.size());
[email protected]f6abeba2008-08-08 13:27:28905 }
[email protected]52a261f2009-03-03 15:01:12906
thestig3e4787d2015-05-19 19:31:52907 if ((g_logging_destination & LOG_TO_FILE) != 0) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43908#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Olivier Lice976792022-09-27 21:35:24909 // If the client app did not call InitLogging() and the lock has not
910 // been created it will be done now on calling GetLoggingLock(). We do this
911 // on demand, but if two threads try to do this at the same time, there will
912 // be a race condition to create the lock. This is why InitLogging should be
913 // called from the main thread at the beginning of execution.
Benoit Lize5c98a832020-07-07 16:32:01914 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09915#endif
[email protected]5b84fe32010-09-14 22:24:55916 if (InitializeLogFileHandle()) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43917#if BUILDFLAG(IS_WIN)
[email protected]5b84fe32010-09-14 22:24:55918 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52919 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55920 static_cast<const void*>(str_newline.c_str()),
921 static_cast<DWORD>(str_newline.length()),
922 &num_written,
thestig3e4787d2015-05-19 19:31:52923 nullptr);
Xiaohan Wang38e4ebb2022-01-19 06:57:43924#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Avi Drissman933398e2022-01-22 00:55:42925 std::ignore =
926 fwrite(str_newline.data(), str_newline.size(), 1, g_log_file);
thestig3e4787d2015-05-19 19:31:52927 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39928#else
929#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55930#endif
initial.commitd7cae122008-07-26 21:49:38931 }
932 }
933
Lei Zhang93dd42572020-10-23 18:45:53934 if (severity_ == LOGGING_FATAL) {
Wezd78fee62020-09-11 18:29:14935 char str_stack[1024];
Daniel Chengf45f47602022-02-28 22:38:32936 base::strlcpy(str_stack, str_newline.data(), std::size(str_stack));
Weze976b732018-10-20 03:37:31937 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05938
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45939 if (!GetLogAssertHandlerStack().empty()) {
alex-accc1bde62017-04-19 08:33:55940 LogAssertHandlerFunction log_assert_handler =
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45941 GetLogAssertHandlerStack().top();
alex-accc1bde62017-04-19 08:33:55942
943 if (log_assert_handler) {
944 log_assert_handler.Run(
945 file_, line_,
946 base::StringPiece(str_newline.c_str() + message_start_,
947 stack_start - message_start_),
948 base::StringPiece(str_newline.c_str() + stack_start));
949 }
[email protected]1ffe08c12008-08-13 11:15:11950 } else {
[email protected]82d89ab2014-02-28 18:25:34951 // Don't use the string with the newline, get a fresh version to send to
952 // the debug message process. We also don't display assertions to the
953 // user in release mode. The enduser can't do anything with this
954 // information, and displaying message boxes when the application is
955 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50956#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42957 if (!base::debug::BeingDebugged()) {
958 // Displaying a dialog is unnecessary when debugging and can complicate
959 // debugging.
960 DisplayDebugMessageInDialog(stream_.str());
961 }
[email protected]4d5901272008-11-06 00:33:50962#endif
Daniel Cheng4f5034d2022-03-04 18:34:31963
[email protected]82d89ab2014-02-28 18:25:34964 // Crash the process to generate a dump.
Peter Boström25c6ec72022-11-02 23:25:19965 base::ImmediateCrash();
initial.commitd7cae122008-07-26 21:49:38966 }
967 }
968}
969
Peter Boström37482962022-07-14 16:09:54970std::string LogMessage::BuildCrashString() const {
Peter Boström871f916a2022-08-09 22:36:27971 return logging::BuildCrashString(file(), line(),
972 str().c_str() + message_start_);
Peter Boström6c0094d12022-07-07 16:03:39973}
974
[email protected]eae9c062011-01-11 00:50:59975// writes the common header info to the stream
976void LogMessage::Init(const char* file, int line) {
977 base::StringPiece filename(file);
978 size_t last_slash_pos = filename.find_last_of("\\/");
979 if (last_slash_pos != base::StringPiece::npos)
980 filename.remove_prefix(last_slash_pos + 1);
981
Georg Neisffe34f652021-12-27 21:42:36982#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54983 if (g_log_format == LogFormat::LOG_FORMAT_SYSLOG) {
984 InitWithSyslogPrefix(
985 filename, line, TickCount(), log_severity_name(severity_), g_log_prefix,
986 g_log_process_id, g_log_thread_id, g_log_timestamp, g_log_tickcount);
987 } else
Georg Neisffe34f652021-12-27 21:42:36988#endif // BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54989 {
990 // TODO(darin): It might be nice if the columns were fixed width.
991 stream_ << '[';
992 if (g_log_prefix)
993 stream_ << g_log_prefix << ':';
994 if (g_log_process_id)
995 stream_ << base::GetUniqueIdForProcess() << ':';
996 if (g_log_thread_id)
997 stream_ << base::PlatformThread::CurrentId() << ':';
998 if (g_log_timestamp) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43999#if BUILDFLAG(IS_WIN)
Yuta Hijikata9b7279a2020-08-26 16:10:541000 SYSTEMTIME local_time;
1001 GetLocalTime(&local_time);
1002 stream_ << std::setfill('0')
1003 << std::setw(2) << local_time.wMonth
1004 << std::setw(2) << local_time.wDay
1005 << '/'
1006 << std::setw(2) << local_time.wHour
1007 << std::setw(2) << local_time.wMinute
1008 << std::setw(2) << local_time.wSecond
1009 << '.'
1010 << std::setw(3) << local_time.wMilliseconds
1011 << ':';
Xiaohan Wang38e4ebb2022-01-19 06:57:431012#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Yuta Hijikata9b7279a2020-08-26 16:10:541013 timeval tv;
1014 gettimeofday(&tv, nullptr);
1015 time_t t = tv.tv_sec;
1016 struct tm local_time;
1017 localtime_r(&t, &local_time);
1018 struct tm* tm_time = &local_time;
1019 stream_ << std::setfill('0')
1020 << std::setw(2) << 1 + tm_time->tm_mon
1021 << std::setw(2) << tm_time->tm_mday
1022 << '/'
1023 << std::setw(2) << tm_time->tm_hour
1024 << std::setw(2) << tm_time->tm_min
1025 << std::setw(2) << tm_time->tm_sec
1026 << '.'
1027 << std::setw(6) << tv.tv_usec
1028 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391029#else
1030#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:341031#endif
Yuta Hijikata9b7279a2020-08-26 16:10:541032 }
1033 if (g_log_tickcount)
1034 stream_ << TickCount() << ':';
1035 if (severity_ >= 0) {
1036 stream_ << log_severity_name(severity_);
1037 } else {
1038 stream_ << "VERBOSE" << -severity_;
1039 }
1040 stream_ << ":" << filename << "(" << line << ")] ";
[email protected]eae9c062011-01-11 00:50:591041 }
pkasting9cf9b94a2014-10-01 22:18:431042 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:591043}
1044
Xiaohan Wang38e4ebb2022-01-19 06:57:431045#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201046// This has already been defined in the header, but defining it again as DWORD
1047// ensures that the type used in the header is equivalent to DWORD. If not,
1048// the redefinition is a compile error.
1049typedef DWORD SystemErrorCode;
1050#endif
1051
1052SystemErrorCode GetLastSystemErrorCode() {
Xiaohan Wang38e4ebb2022-01-19 06:57:431053#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201054 return ::GetLastError();
Xiaohan Wang38e4ebb2022-01-19 06:57:431055#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201056 return errno;
[email protected]d8617a62009-10-09 23:52:201057#endif
1058}
1059
[email protected]c914d8a2014-04-23 01:11:011060BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Xiaohan Wang38e4ebb2022-01-19 06:57:431061#if BUILDFLAG(IS_WIN)
thestig75f87352014-12-03 21:42:271062 const int kErrorMessageBufferSize = 256;
1063 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:011064 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:521065 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Daniel Chengf45f47602022-02-28 22:38:321066 std::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:011067 if (len) {
1068 // Messages returned by system end with line breaks.
1069 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:451070 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:011071 }
Bruce Dawson19175842017-08-02 17:00:451072 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:011073 GetLastError(), error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431074#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:141075 return base::safe_strerror(error_code) +
1076 base::StringPrintf(" (%d)", error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431077#endif // BUILDFLAG(IS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391078}
[email protected]d8617a62009-10-09 23:52:201079
Xiaohan Wang38e4ebb2022-01-19 06:57:431080#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201081Win32ErrorLogMessage::Win32ErrorLogMessage(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
1087Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011088 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:061089 // 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 DWORD last_error = err_;
1092 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201093}
Xiaohan Wang38e4ebb2022-01-19 06:57:431094#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201095ErrnoLogMessage::ErrnoLogMessage(const char* file,
1096 int line,
1097 LogSeverity severity,
1098 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001099 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201100
1101ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011102 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141103 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1104 // field) and use Alias in hopes that it makes it into crash dumps.
1105 int last_error = err_;
1106 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201107}
Xiaohan Wang38e4ebb2022-01-19 06:57:431108#endif // BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201109
initial.commitd7cae122008-07-26 21:49:381110void CloseLogFile() {
Xiaohan Wang38e4ebb2022-01-19 06:57:431111#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:011112 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:091113#endif
[email protected]17dcf752013-07-15 21:47:091114 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381115}
1116
Yuta Hijikata000df18f2020-11-18 06:55:581117#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:531118FILE* DuplicateLogFILE() {
1119 if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle())
1120 return nullptr;
1121
1122 int log_fd = fileno(g_log_file);
1123 if (log_fd == -1)
1124 return nullptr;
1125 base::ScopedFD dup_fd(dup(log_fd));
1126 if (dup_fd == -1)
1127 return nullptr;
1128 FILE* duplicate = fdopen(dup_fd.get(), "a");
1129 if (!duplicate)
1130 return nullptr;
Avi Drissman933398e2022-01-22 00:55:421131 std::ignore = dup_fd.release();
Robbie McElrath8bf49842019-08-20 22:22:531132 return duplicate;
1133}
1134#endif
1135
Yuta Hijikata9b7279a2020-08-26 16:10:541136// Used for testing. Declared in test/scoped_logging_settings.h.
1137ScopedLoggingSettings::ScopedLoggingSettings()
Wez244270362021-05-04 22:50:581138 : min_log_level_(g_min_log_level),
1139 logging_destination_(g_logging_destination),
Georg Neisffe34f652021-12-27 21:42:361140#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581141 log_format_(g_log_format),
1142#endif // BUILDFLAG(IS_CHROMEOS_ASH)
1143 enable_process_id_(g_log_process_id),
Yuta Hijikata9b7279a2020-08-26 16:10:541144 enable_thread_id_(g_log_thread_id),
1145 enable_timestamp_(g_log_timestamp),
1146 enable_tickcount_(g_log_tickcount),
Wez244270362021-05-04 22:50:581147 log_prefix_(g_log_prefix),
1148 message_handler_(g_log_message_handler) {
1149 if (g_log_file_name)
1150 log_file_name_ = std::make_unique<PathString>(*g_log_file_name);
1151 // Duplicating |g_log_file| is complex & unnecessary for this test helpers'
1152 // use-cases, and so long as |g_log_file_name| is set, it will be re-opened
1153 // automatically anyway, when required, so just close the existing one.
1154 if (g_log_file) {
1155 CHECK(g_log_file_name) << "Un-named |log_file| is not supported.";
1156 CloseLogFileUnlocked();
1157 }
Yuta Hijikata9b7279a2020-08-26 16:10:541158}
1159
1160ScopedLoggingSettings::~ScopedLoggingSettings() {
Wez244270362021-05-04 22:50:581161 // Re-initialize logging via the normal path. This will clean up old file
1162 // name and handle state, including re-initializing the VLOG internal state.
1163 CHECK(InitLogging({
1164 .logging_dest = logging_destination_,
1165 .log_file_path = log_file_name_ ? log_file_name_->data() : nullptr,
Georg Neisffe34f652021-12-27 21:42:361166#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581167 .log_format = log_format_
1168#endif
1169 })) << "~ScopedLoggingSettings() failed to restore settings.";
1170
1171 // Restore plain data settings.
1172 SetMinLogLevel(min_log_level_);
1173 SetLogItems(enable_process_id_, enable_thread_id_, enable_timestamp_,
1174 enable_tickcount_);
1175 SetLogPrefix(log_prefix_);
1176 SetLogMessageHandler(message_handler_);
Yuta Hijikata9b7279a2020-08-26 16:10:541177}
1178
Georg Neisffe34f652021-12-27 21:42:361179#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:541180void ScopedLoggingSettings::SetLogFormat(LogFormat log_format) const {
1181 g_log_format = log_format;
1182}
Yuta Hijikata000df18f2020-11-18 06:55:581183#endif // BUILDFLAG(IS_CHROMEOS_ASH)
Yuta Hijikata9b7279a2020-08-26 16:10:541184
[email protected]e36ddc82009-12-08 04:22:501185void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491186 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501187 const size_t message_len = strlen(message);
Benoit Lizeed678192022-01-20 10:14:541188 WriteToFd(STDERR_FILENO, message, message_len);
[email protected]e36ddc82009-12-08 04:22:501189
1190 if (message_len > 0 && message[message_len - 1] != '\n') {
Peter Kastingaca170a2022-06-30 17:18:481191 long rv;
[email protected]e36ddc82009-12-08 04:22:501192 do {
1193 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1194 if (rv < 0) {
1195 // Give up, nothing we can do now.
1196 break;
1197 }
1198 } while (rv != 1);
1199 }
1200 }
1201
Lei Zhang93dd42572020-10-23 18:45:531202 if (level == LOGGING_FATAL)
Peter Boström25c6ec72022-11-02 23:25:191203 base::ImmediateCrash();
[email protected]e36ddc82009-12-08 04:22:501204}
1205
[email protected]34a907732012-01-20 06:33:271206// This was defined at the beginning of this file.
1207#undef write
1208
Xiaohan Wang38e4ebb2022-01-19 06:57:431209#if BUILDFLAG(IS_WIN)
ananta61762fb2015-09-18 01:00:091210bool IsLoggingToFileEnabled() {
1211 return g_logging_destination & LOG_TO_FILE;
1212}
1213
Jan Wilken Dörrieb630aca2019-12-04 10:59:111214std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521215 if (g_log_file_name)
1216 return *g_log_file_name;
Jan Wilken Dörrieb630aca2019-12-04 10:59:111217 return std::wstring();
[email protected]f01b88a2013-02-27 22:04:001218}
1219#endif
1220
Xiyuan Xiaa0559da2022-05-05 19:42:451221#if !BUILDFLAG(USE_RUNTIME_VLOG)
1222int GetDisableAllVLogLevel() {
1223 return -1;
1224}
1225#endif // !BUILDFLAG(USE_RUNTIME_VLOG)
1226
Fergal Daly432aa7c2022-06-14 07:30:541227// Used for testing. Declared in test/scoped_logging_settings.h.
1228ScopedVmoduleSwitches::ScopedVmoduleSwitches() = default;
1229#if BUILDFLAG(USE_RUNTIME_VLOG)
1230VlogInfo* ScopedVmoduleSwitches::CreateVlogInfoWithSwitches(
1231 const std::string& vmodule_switch) {
1232 // Try get a VlogInfo on which to base this.
1233 // First ensure that VLOG has been initialized.
1234 MaybeInitializeVlogInfo();
1235
1236 // Getting this now and setting it later is racy, however if a
1237 // ScopedVmoduleSwitches is being used on multiple threads that requires
1238 // further coordination and avoids this race.
1239 VlogInfo* base_vlog_info = GetVlogInfo();
1240 if (!base_vlog_info) {
1241 // Base is |nullptr|, so just create it from scratch.
1242 return new VlogInfo(/*v_switch_=*/"", vmodule_switch, &g_min_log_level);
1243 }
1244 return base_vlog_info->WithSwitches(vmodule_switch);
1245}
1246
1247void ScopedVmoduleSwitches::InitWithSwitches(
1248 const std::string& vmodule_switch) {
1249 // Make sure we are only initialized once.
1250 CHECK(!scoped_vlog_info_);
1251 {
1252#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
1253 // See comments on |g_vlog_info|.
1254 ScopedLeakSanitizerDisabler lsan_disabler;
1255#endif // defined(LEAK_SANITIZER)
1256 scoped_vlog_info_ = CreateVlogInfoWithSwitches(vmodule_switch);
1257 }
1258 previous_vlog_info_ = ExchangeVlogInfo(scoped_vlog_info_);
1259}
1260
1261ScopedVmoduleSwitches::~ScopedVmoduleSwitches() {
1262 VlogInfo* replaced_vlog_info = ExchangeVlogInfo(previous_vlog_info_);
1263 // Make sure something didn't replace our scoped VlogInfo while we weren't
1264 // looking.
1265 CHECK_EQ(replaced_vlog_info, scoped_vlog_info_);
1266}
1267#else
1268void ScopedVmoduleSwitches::InitWithSwitches(
1269 const std::string& vmodule_switch) {}
1270
1271ScopedVmoduleSwitches::~ScopedVmoduleSwitches() = default;
1272#endif // BUILDFLAG(USE_RUNTIME_VLOG)
1273
[email protected]96fd0032009-04-24 00:13:081274} // namespace logging
initial.commitd7cae122008-07-26 21:49:381275
[email protected]81411c62014-07-08 23:03:061276std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391277 return out << (wstr ? base::WStringPiece(wstr) : base::WStringPiece());
1278}
1279
1280std::ostream& std::operator<<(std::ostream& out, const std::wstring& wstr) {
1281 return out << base::WStringPiece(wstr);
1282}
1283
1284std::ostream& std::operator<<(std::ostream& out, const char16_t* str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461285 return out << (str16 ? base::StringPiece16(str16) : base::StringPiece16());
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391286}
1287
1288std::ostream& std::operator<<(std::ostream& out, const std::u16string& str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461289 return out << base::StringPiece16(str16);
initial.commitd7cae122008-07-26 21:49:381290}