blob: 99c7556fa9e64de3061e4c1738c0a0f02ab3d2bc [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"
Fergal Dalycac6ddc2022-05-24 17:42:036#include <atomic>
Fergal Daly432aa7c2022-06-14 07:30:547#include <memory>
[email protected]f6abeba2008-08-08 13:27:288
Hans Wennborg12aea3e2020-04-14 15:29:009// logging.h is a widely included header and its size has significant impact on
10// build time. Try not to raise this limit unless absolutely necessary. See
11// https://chromium.googlesource.com/chromium/src/+/HEAD/docs/wmax_tokens.md
12#ifndef NACL_TC_REV
Hans Wennborg944479f2020-06-25 21:39:2513#pragma clang max_tokens_here 350000
Hans Wennborg12aea3e2020-04-14 15:29:0014#endif // NACL_TC_REV
15
Hans Wennborg944479f2020-06-25 21:39:2516#ifdef BASE_CHECK_H_
17#error "logging.h should not include check.h"
18#endif
19
avi51ba3e692015-12-26 17:30:5020#include <limits.h>
avi9b6f42932015-12-26 22:15:1421#include <stdint.h>
22
Avi Drissman933398e2022-01-22 00:55:4223#include <tuple>
David Bienvenub4b441e2020-09-23 05:49:5724#include <vector>
25
David Sanders6e709942022-04-05 06:49:2626#include "base/base_export.h"
Lukasz Anforowicz872567d2021-09-08 19:49:2227#include "base/debug/crash_logging.h"
Fergal Dalycac6ddc2022-05-24 17:42:0328#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
29#include "base/debug/leak_annotations.h"
30#endif // defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
Kalvin Lee70699ccd2022-04-28 17:27:3631#include "base/immediate_crash.h"
Chris Hamilton306740d2019-04-25 18:48:3632#include "base/pending_task.h"
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:3933#include "base/strings/string_piece.h"
Chris Hamilton306740d2019-04-25 18:48:3634#include "base/task/common/task_annotator.h"
Eric Secklerf6c544f2020-06-02 10:49:2135#include "base/trace_event/base_tracing.h"
avi9b6f42932015-12-26 22:15:1436#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5037
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>
Chris Findeisen2a373a2d2019-08-15 19:44:3076#include "base/process/process_handle.h"
[email protected]f6abeba2008-08-08 13:27:2877#define MAX_PATH PATH_MAX
78typedef FILE* FileHandle;
[email protected]f6abeba2008-08-08 13:27:2879#endif
80
[email protected]1f88b5162011-04-01 00:02:2981#include <algorithm>
82#include <cstring>
initial.commitd7cae122008-07-26 21:49:3883#include <ctime>
84#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2985#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0186#include <string>
alex-accc1bde62017-04-19 08:33:5587#include <utility>
[email protected]b16ef312008-08-19 18:36:2388
initial.commitd7cae122008-07-26 21:49:3889#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:5590#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:3891#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:2892#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:5593#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:0594#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5095#include "base/debug/debugger.h"
96#include "base/debug/stack_trace.h"
Alan Cutter9b0e1ab2019-03-21 04:22:1697#include "base/debug/task_trace.h"
Yannic Bonenberger3dcd7fe2019-06-08 11:01:4598#include "base/no_destructor.h"
Sharon Yanga4b908de2019-05-07 22:19:0399#include "base/path_service.h"
[email protected]2025d002012-11-14 20:54:35100#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:00101#include "base/strings/string_piece.h"
Xianzhu Wangae8d96a32018-10-16 20:41:13102#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:01103#include "base/strings/string_util.h"
104#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42105#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07106#include "base/strings/utf_string_conversions.h"
Benoit Lize5c98a832020-07-07 16:32:01107#include "base/synchronization/lock.h"
Yuta Hijikata9b7279a2020-08-26 16:10:54108#include "base/test/scoped_logging_settings.h"
[email protected]63e66802012-01-18 21:21:09109#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36110#include "base/vlog.h"
Yuta Hijikata000df18f2020-11-18 06:55:58111#include "build/chromeos_buildflags.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39112
Xiaohan Wang38e4ebb2022-01-19 06:57:43113#if BUILDFLAG(IS_WIN)
Cliff Smolinskyc5c52102019-05-03 20:51:54114#include "base/win/win_util.h"
115#endif
116
Xiaohan Wang38e4ebb2022-01-19 06:57:43117#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24118#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04119#endif
[email protected]52a261f2009-03-03 15:01:12120
Yuta Hijikata000df18f2020-11-18 06:55:58121#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:53122#include "base/files/scoped_file.h"
123#endif
124
initial.commitd7cae122008-07-26 21:49:38125namespace logging {
126
[email protected]064aa162011-12-03 00:30:08127namespace {
128
Fergal Dalyfacfaf92022-06-02 04:47:55129int g_min_log_level = 0;
130
Xiyuan Xiaa0559da2022-05-05 19:42:45131#if BUILDFLAG(USE_RUNTIME_VLOG)
Fergal Dalycac6ddc2022-05-24 17:42:03132// NOTE: Once |g_vlog_info| has been initialized, it might be in use
133// by another thread. Never delete the old VLogInfo, just create a second
134// one and overwrite. We need to use leak-san annotations on this intentional
135// leak.
136//
137// This can be read/written on multiple threads. In tests we don't see that
138// causing a problem as updates tend to happen early. Atomic ensures there are
139// no problems. To avoid some of the overhead of Atomic, we use
140// |load(std::memory_order_acquire)| and |store(...,
Fergal Daly432aa7c2022-06-14 07:30:54141// std::memory_order_release)| when reading or writing. This guarantees that the
142// referenced object is available at the time the |g_vlog_info| is read and that
143// |g_vlog_info| is updated atomically.
144//
145// Do not access this directly. You must use |GetVlogInfo|, |InitializeVlogInfo|
146// and/or |ExchangeVlogInfo|.
Fergal Dalycac6ddc2022-05-24 17:42:03147std::atomic<VlogInfo*> g_vlog_info = nullptr;
Fergal Dalyfacfaf92022-06-02 04:47:55148
Fergal Daly432aa7c2022-06-14 07:30:54149VlogInfo* GetVlogInfo() {
150 return g_vlog_info.load(std::memory_order_acquire);
151}
152
153// Sets g_vlog_info if it is not already set. Checking that it's not already set
154// prevents logging initialization (which can come late in test setup) from
155// overwriting values set via ScopedVmoduleSwitches.
156bool InitializeVlogInfo(VlogInfo* vlog_info) {
157 VlogInfo* previous_vlog_info = nullptr;
158 return g_vlog_info.compare_exchange_strong(previous_vlog_info, vlog_info);
159}
160
161VlogInfo* ExchangeVlogInfo(VlogInfo* vlog_info) {
162 return g_vlog_info.exchange(vlog_info);
163}
164
Fergal Dalyfacfaf92022-06-02 04:47:55165// Creates a VlogInfo from the commandline if it has been initialized and if it
166// contains relevant switches, otherwise this returns |nullptr|.
Fergal Daly432aa7c2022-06-14 07:30:54167std::unique_ptr<VlogInfo> VlogInfoFromCommandLine() {
Fergal Dalyfacfaf92022-06-02 04:47:55168 if (!base::CommandLine::InitializedForCurrentProcess())
169 return nullptr;
170 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
171 if (!command_line->HasSwitch(switches::kV) &&
172 !command_line->HasSwitch(switches::kVModule)) {
173 return nullptr;
174 }
175#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
176 // See comments on |g_vlog_info|.
177 ScopedLeakSanitizerDisabler lsan_disabler;
178#endif // defined(LEAK_SANITIZER)
Fergal Daly432aa7c2022-06-14 07:30:54179 return std::make_unique<VlogInfo>(
180 command_line->GetSwitchValueASCII(switches::kV),
181 command_line->GetSwitchValueASCII(switches::kVModule), &g_min_log_level);
182}
183
184// If the commandline is initialized for the current process this will
185// initialize g_vlog_info. If there are no VLOG switches, it will initialize it
186// to |nullptr|.
187void MaybeInitializeVlogInfo() {
188 if (base::CommandLine::InitializedForCurrentProcess()) {
189 std::unique_ptr<VlogInfo> vlog_info = VlogInfoFromCommandLine();
190 if (vlog_info) {
191 // VlogInfoFromCommandLine is annotated with ScopedLeakSanitizerDisabler
192 // so it's allowed to leak. If the object was installed, we release it.
193 if (InitializeVlogInfo(vlog_info.get())) {
194 vlog_info.release();
195 }
196 }
197 }
Fergal Dalyfacfaf92022-06-02 04:47:55198}
Xiyuan Xiaa0559da2022-05-05 19:42:45199#endif // BUILDFLAG(USE_RUNTIME_VLOG)
initial.commitd7cae122008-07-26 21:49:38200
Jeffrey Young551bce62022-06-24 19:08:17201#if !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
202
203// Warn developers that vlog command line settings are being ignored.
204void MaybeWarnVmodule() {
205 if (base::CommandLine::InitializedForCurrentProcess()) {
206 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
207 if (command_line->HasSwitch(switches::kV) ||
208 command_line->HasSwitch(switches::kVModule)) {
209 LOG(WARNING)
210 << "--" << switches::kV << " and --" << switches::kVModule
211 << " are currently ignored. See comments in base/logging.h on "
212 "proper usage of USE_RUNTIME_VLOG.";
213 }
214 }
215}
216
217#endif // !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
218
weza245bd072017-06-18 23:26:34219const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
Daniel Chengf45f47602022-02-28 22:38:32220static_assert(LOGGING_NUM_SEVERITIES == std::size(log_severity_names),
weza245bd072017-06-18 23:26:34221 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38222
thestig75f87352014-12-03 21:42:27223const char* log_severity_name(int severity) {
Lei Zhang93dd42572020-10-23 18:45:53224 if (severity >= 0 && severity < LOGGING_NUM_SEVERITIES)
[email protected]80f360a2014-01-23 01:36:19225 return log_severity_names[severity];
226 return "UNKNOWN";
227}
228
Sharon Yang7cb919a2019-05-20 20:27:15229// Specifies the process' logging sink(s), represented as a combination of
230// LoggingDestination values joined by bitwise OR.
Peter Kasting40cfeae2021-06-14 12:21:48231uint32_t g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38232
Georg Neisffe34f652021-12-27 21:42:36233#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata1fc8f6342020-09-01 03:25:56234// Specifies the format of log header for chrome os.
235LogFormat g_log_format = LogFormat::LOG_FORMAT_SYSLOG;
Yuta Hijikata9b7279a2020-08-26 16:10:54236#endif
237
Xiaohan Wang38e4ebb2022-01-19 06:57:43238#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02239// Retains system logging structures.
240base::ScopedFxLogger& GetScopedFxLogger() {
241 static base::NoDestructor<base::ScopedFxLogger> logger;
242 return *logger;
243}
244#endif
245
Lei Zhang93dd42572020-10-23 18:45:53246// For LOGGING_ERROR and above, always print to stderr.
247const int kAlwaysPrintErrorLevel = LOGGING_ERROR;
[email protected]a33c9892008-08-25 20:10:31248
[email protected]614e9fa2008-08-11 22:52:59249// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38250// will be lazily initialized to the default value when it is
251// first needed.
jdoerrie5c4dc4e2019-02-01 18:02:33252using PathString = base::FilePath::StringType;
thestig3e4787d2015-05-19 19:31:52253PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38254
thestig3e4787d2015-05-19 19:31:52255// This file is lazily opened and the handle may be nullptr
256FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38257
thestig3e4787d2015-05-19 19:31:52258// What should be prepended to each message?
259bool g_log_process_id = false;
260bool g_log_thread_id = false;
261bool g_log_timestamp = true;
262bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31263const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38264
[email protected]81e0a852010-08-17 00:38:12265// Should we pop up fatal debug messages in a dialog?
266bool show_error_dialogs = false;
267
initial.commitd7cae122008-07-26 21:49:38268// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55269// the debug message dialog and process termination. Assert handlers are stored
270// in stack to allow overriding and restoring.
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45271base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() {
272 static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance;
273 return *instance;
274}
alex-accc1bde62017-04-19 08:33:55275
[email protected]2b07b8412009-11-25 15:26:34276// A log message handler that gets notified of every log message we process.
Wez244270362021-05-04 22:50:58277LogMessageHandlerFunction g_log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38278
avi9b6f42932015-12-26 22:15:14279uint64_t TickCount() {
Xiaohan Wang38e4ebb2022-01-19 06:57:43280#if BUILDFLAG(IS_WIN)
[email protected]f8588472008-11-05 23:17:24281 return GetTickCount();
Xiaohan Wang38e4ebb2022-01-19 06:57:43282#elif BUILDFLAG(IS_FUCHSIA)
Sharon Yang52c60992019-05-16 22:41:35283 return zx_clock_get_monotonic() /
Wezb0501302018-03-09 05:18:45284 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
avi9b6f42932015-12-26 22:15:14295 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
296 static_cast<int64_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;
453 int rv;
454 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
[email protected]064aa162011-12-03 00:30:08464} // namespace
465
Tomas Popelaafffa972018-11-13 20:42:05466#if defined(DCHECK_IS_CONFIGURABLE)
Lei Zhang93dd42572020-10-23 18:45:53467// In DCHECK-enabled Chrome builds, allow the meaning of LOGGING_DCHECK to be
Wez289477f2017-08-24 20:51:30468// determined at run-time. We default it to INFO, to avoid it triggering
469// crashes before the run-time has explicitly chosen the behaviour.
Lei Zhang93dd42572020-10-23 18:45:53470BASE_EXPORT logging::LogSeverity LOGGING_DCHECK = LOGGING_INFO;
Tomas Popelaafffa972018-11-13 20:42:05471#endif // defined(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30472
scottmg3c957a52016-12-10 20:57:59473// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
474// an object of the correct type on the LHS of the unused part of the ternary
475// operator.
476std::ostream* g_swallow_stream;
477
[email protected]5e3f7c22013-06-21 21:15:33478bool BaseInitLoggingImpl(const LoggingSettings& settings) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43479#if BUILDFLAG(IS_NACL)
Sharon Yang7cb919a2019-05-20 20:27:15480 // Can log only to the system debug log and stderr.
481 CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR),
482 0u);
[email protected]ac07ec52013-04-22 17:32:45483#endif
Robbie McElrath8bf49842019-08-20 22:22:53484
Georg Neisffe34f652021-12-27 21:42:36485#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata8a93e522020-09-25 08:59:57486 g_log_format = settings.log_format;
487#endif
488
Xiyuan Xiaa0559da2022-05-05 19:42:45489#if BUILDFLAG(USE_RUNTIME_VLOG)
Fergal Daly432aa7c2022-06-14 07:30:54490 MaybeInitializeVlogInfo();
Fergal Dalycac6ddc2022-05-24 17:42:03491#endif // BUILDFLAG(USE_RUNTIME_VLOG)
[email protected]99b7c57f2010-09-29 19:26:36492
Jeffrey Young551bce62022-06-24 19:08:17493#if !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
494 MaybeWarnVmodule();
495#endif // !BUILDFLAG(USE_RUNTIME_VLOG) && DCHECK_IS_ON()
496
thestig3e4787d2015-05-19 19:31:52497 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38498
Xiaohan Wang38e4ebb2022-01-19 06:57:43499#if BUILDFLAG(IS_FUCHSIA)
Wez224c0bf62019-05-24 19:26:13500 if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) {
Wez5d4a666c2021-10-04 16:41:36501 GetScopedFxLogger() = base::ScopedFxLogger::CreateForProcess();
Wez224c0bf62019-05-24 19:26:13502 }
503#endif
504
[email protected]5e3f7c22013-06-21 21:15:33505 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52506 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21507 return true;
initial.commitd7cae122008-07-26 21:49:38508
Xiaohan Wang38e4ebb2022-01-19 06:57:43509#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:01510 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09511#endif
[email protected]17dcf752013-07-15 21:47:09512
513 // Calling InitLogging twice or after some log call has already opened the
514 // default log file will re-initialize to the new options.
515 CloseLogFileUnlocked();
516
Yuta Hijikata000df18f2020-11-18 06:55:58517#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:53518 if (settings.log_file) {
519 DCHECK(!settings.log_file_path);
520 g_log_file = settings.log_file;
521 return true;
522 }
523#endif
Lei Zhang93dd42572020-10-23 18:45:53524
Xiaohan Wang5411974b2020-10-10 19:36:12525 DCHECK(settings.log_file_path) << "LOG_TO_FILE set but no log_file_path!";
Robbie McElrath8bf49842019-08-20 22:22:53526
thestig3e4787d2015-05-19 19:31:52527 if (!g_log_file_name)
528 g_log_file_name = new PathString();
Robbie McElrath8bf49842019-08-20 22:22:53529 *g_log_file_name = settings.log_file_path;
[email protected]5e3f7c22013-06-21 21:15:33530 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52531 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38532
[email protected]c7d5da992010-10-28 00:20:21533 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38534}
535
536void SetMinLogLevel(int level) {
Lei Zhang93dd42572020-10-23 18:45:53537 g_min_log_level = std::min(LOGGING_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38538}
539
540int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52541 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38542}
543
skobesc78c0ad72015-12-07 20:21:23544bool ShouldCreateLogMessage(int severity) {
545 if (severity < g_min_log_level)
546 return false;
547
Wez6c8acb82019-07-18 00:32:59548 // Return true here unless we know ~LogMessage won't do anything.
Wez244270362021-05-04 22:50:58549 return g_logging_destination != LOG_NONE || g_log_message_handler ||
skobesc78c0ad72015-12-07 20:21:23550 severity >= kAlwaysPrintErrorLevel;
551}
552
Wez6c8acb82019-07-18 00:32:59553// Returns true when LOG_TO_STDERR flag is set, or |severity| is high.
554// If |severity| is high then true will be returned when no log destinations are
555// set, or only LOG_TO_FILE is set, since that is useful for local development
556// and debugging.
557bool ShouldLogToStderr(int severity) {
558 if (g_logging_destination & LOG_TO_STDERR)
559 return true;
Wez82ba0502022-05-11 08:50:08560
561#if BUILDFLAG(IS_FUCHSIA)
562 // Fuchsia will persist data logged to stdio by a component, so do not emit
563 // logs to stderr unless explicitly configured to do so.
564 return false;
565#else
Wez6c8acb82019-07-18 00:32:59566 if (severity >= kAlwaysPrintErrorLevel)
567 return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
568 return false;
Wez82ba0502022-05-11 08:50:08569#endif
Wez6c8acb82019-07-18 00:32:59570}
571
[email protected]162ac0f2010-11-04 15:50:49572int GetVlogVerbosity() {
573 return std::max(-1, LOG_INFO - GetMinLogLevel());
574}
575
[email protected]99b7c57f2010-09-29 19:26:36576int GetVlogLevelHelper(const char* file, size_t N) {
577 DCHECK_GT(N, 0U);
Xiyuan Xiaa0559da2022-05-05 19:42:45578
579#if BUILDFLAG(USE_RUNTIME_VLOG)
thestig3e4787d2015-05-19 19:31:52580 // Note: |g_vlog_info| may change on a different thread during startup
581 // (but will always be valid or nullptr).
Fergal Daly432aa7c2022-06-14 07:30:54582 VlogInfo* vlog_info = GetVlogInfo();
[email protected]064aa162011-12-03 00:30:08583 return vlog_info ?
584 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49585 GetVlogVerbosity();
Xiyuan Xiaa0559da2022-05-05 19:42:45586#else
587 return GetVlogVerbosity();
588#endif // BUILDFLAG(USE_RUNTIME_VLOG)
[email protected]99b7c57f2010-09-29 19:26:36589}
590
initial.commitd7cae122008-07-26 21:49:38591void SetLogItems(bool enable_process_id, bool enable_thread_id,
592 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52593 g_log_process_id = enable_process_id;
594 g_log_thread_id = enable_thread_id;
595 g_log_timestamp = enable_timestamp;
596 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38597}
598
James Cooka0536c32018-08-01 20:13:31599void SetLogPrefix(const char* prefix) {
600 DCHECK(!prefix ||
601 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
602 g_log_prefix = prefix;
603}
604
[email protected]81e0a852010-08-17 00:38:12605void SetShowErrorDialogs(bool enable_dialogs) {
606 show_error_dialogs = enable_dialogs;
607}
608
alex-accc1bde62017-04-19 08:33:55609ScopedLogAssertHandler::ScopedLogAssertHandler(
610 LogAssertHandlerFunction handler) {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45611 GetLogAssertHandlerStack().push(std::move(handler));
alex-accc1bde62017-04-19 08:33:55612}
613
614ScopedLogAssertHandler::~ScopedLogAssertHandler() {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45615 GetLogAssertHandlerStack().pop();
initial.commitd7cae122008-07-26 21:49:38616}
617
[email protected]2b07b8412009-11-25 15:26:34618void SetLogMessageHandler(LogMessageHandlerFunction handler) {
Wez244270362021-05-04 22:50:58619 g_log_message_handler = handler;
[email protected]2b07b8412009-11-25 15:26:34620}
621
[email protected]64e5cc02010-11-03 19:20:27622LogMessageHandlerFunction GetLogMessageHandler() {
Wez244270362021-05-04 22:50:58623 return g_log_message_handler;
[email protected]64e5cc02010-11-03 19:20:27624}
625
[email protected]f2c05492014-06-17 12:04:23626#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22627// Displays a message box to the user with the error message in it.
628// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25629// This is for developers only; we don't use this in circumstances
630// (like release builds) where users could see it, since users don't
631// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22632void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38633 if (str.empty())
634 return;
635
[email protected]81e0a852010-08-17 00:38:12636 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44637 return;
638
Xiaohan Wang38e4ebb2022-01-19 06:57:43639#if BUILDFLAG(IS_WIN)
[email protected]561513f2010-12-16 23:29:25640 // We intentionally don't implement a dialog on other platforms.
641 // You can just look at stderr.
Cliff Smolinskyc5c52102019-05-03 20:51:54642 if (base::win::IsUser32AndGdi32Available()) {
643 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
644 MB_OK | MB_ICONHAND | MB_TOPMOST);
645 } else {
646 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
647 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43648#endif // BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38649}
[email protected]f2c05492014-06-17 12:04:23650#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38651
[email protected]eae9c062011-01-11 00:50:59652LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
653 : severity_(severity), file_(file), line_(line) {
654 Init(file, line);
655}
656
tnagel4a045d3f2015-07-12 14:19:28657LogMessage::LogMessage(const char* file, int line, const char* condition)
Lei Zhang93dd42572020-10-23 18:45:53658 : severity_(LOGGING_FATAL), file_(file), line_(line) {
tnagel4a045d3f2015-07-12 14:19:28659 Init(file, line);
660 stream_ << "Check failed: " << condition << ". ";
661}
662
initial.commitd7cae122008-07-26 21:49:38663LogMessage::~LogMessage() {
Peter Kasting28b51cf2022-06-28 15:02:43664 size_t stack_start = stream_.str().length();
Xiaohan Wang38e4ebb2022-01-19 06:57:43665#if !defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_NACL) && !defined(__UCLIBC__) && \
666 !BUILDFLAG(IS_AIX)
Lei Zhang93dd42572020-10-23 18:45:53667 if (severity_ == LOGGING_FATAL && !base::debug::BeingDebugged()) {
brucedawson7c559eb2015-09-05 00:34:42668 // Include a stack trace on a fatal, unless a debugger is attached.
Alan Cutter9b0e1ab2019-03-21 04:22:16669 base::debug::StackTrace stack_trace;
[email protected]d1ccc35a2010-03-24 05:03:24670 stream_ << std::endl; // Newline to separate from log message.
Alan Cutter9b0e1ab2019-03-21 04:22:16671 stack_trace.OutputToStream(&stream_);
672 base::debug::TaskTrace task_trace;
673 if (!task_trace.empty())
674 task_trace.OutputToStream(&stream_);
Chris Hamilton306740d2019-04-25 18:48:36675
Chris Hamilton888085312019-05-30 00:53:30676 // Include the IPC context, if any.
677 // TODO(chrisha): Integrate with symbolization once those tools exist!
Chris Hamilton306740d2019-04-25 18:48:36678 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
Chris Hamilton888085312019-05-30 00:53:30679 if (task && task->ipc_hash) {
680 stream_ << "IPC message handler context: "
681 << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
Chris Hamilton306740d2019-04-25 18:48:36682 }
Lukasz Anforowicz872567d2021-09-08 19:49:22683
684 // Include the crash keys, if any.
685 base::debug::OutputCrashKeysToStream(stream_);
[email protected]d1ccc35a2010-03-24 05:03:24686 }
[email protected]1d8c2702008-08-19 23:39:32687#endif
[email protected]d1ccc35a2010-03-24 05:03:24688 stream_ << std::endl;
689 std::string str_newline(stream_.str());
Nicolò Mazzucato6c278d9b2019-08-02 16:25:44690 TRACE_LOG_MESSAGE(
691 file_, base::StringPiece(str_newline).substr(message_start_), line_);
[email protected]d1ccc35a2010-03-24 05:03:24692
[email protected]2b07b8412009-11-25 15:26:34693 // Give any log message handler first dibs on the message.
Wez244270362021-05-04 22:50:58694 if (g_log_message_handler &&
695 g_log_message_handler(severity_, file_, line_, message_start_,
696 str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49697 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34698 return;
[email protected]162ac0f2010-11-04 15:50:49699 }
initial.commitd7cae122008-07-26 21:49:38700
thestig3e4787d2015-05-19 19:31:52701 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43702#if BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38703 OutputDebugStringA(str_newline.c_str());
Xiaohan Wang38e4ebb2022-01-19 06:57:43704#elif BUILDFLAG(IS_APPLE)
mark4c7449c2015-11-10 19:53:42705 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Avi Drissmanba195b32022-05-19 02:53:34706 // stderr. If stderr is /dev/null, also log via os_log. If there's something
707 // weird about stderr, assume that log messages are going nowhere and log
708 // via os_log too. Messages logged via os_log show up in Console.app.
mark4c7449c2015-11-10 19:53:42709 //
710 // Programs started by launchd, as UI applications normally are, have had
711 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
712 // a pipe to launchd, which logged what it received (see log_redirect_fd in
713 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
714 //
715 // Another alternative would be to determine whether stderr is a pipe to
Avi Drissmanba195b32022-05-19 02:53:34716 // launchd and avoid logging via os_log only in that case. See 10.7.5
mark4c7449c2015-11-10 19:53:42717 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Avi Drissmanba195b32022-05-19 02:53:34718 // both stderr and os_log even in tests, where it's undesirable to log to
719 // the system log at all.
Eric Noyaufce100702017-10-16 09:46:34720 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42721 struct stat stderr_stat;
722 if (fstat(fileno(stderr), &stderr_stat) == -1) {
723 return true;
724 }
725 if (!S_ISCHR(stderr_stat.st_mode)) {
726 return false;
727 }
728
729 struct stat dev_null_stat;
730 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
731 return true;
732 }
733
734 return !S_ISCHR(dev_null_stat.st_mode) ||
735 stderr_stat.st_rdev == dev_null_stat.st_rdev;
736 }();
737
Eric Noyaufce100702017-10-16 09:46:34738 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42739 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
740 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42741 CFBundleRef main_bundle = CFBundleGetMainBundle();
742 CFStringRef main_bundle_id_cf =
743 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34744 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42745 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34746 : std::string("");
mark4c7449c2015-11-10 19:53:42747
Eric Noyaufce100702017-10-16 09:46:34748 const class OSLog {
749 public:
750 explicit OSLog(const char* subsystem)
751 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
752 : OS_LOG_DEFAULT) {}
David Bienvenub4b441e2020-09-23 05:49:57753 OSLog(const OSLog&) = delete;
754 OSLog& operator=(const OSLog&) = delete;
Eric Noyaufce100702017-10-16 09:46:34755 ~OSLog() {
756 if (os_log_ != OS_LOG_DEFAULT) {
757 os_release(os_log_);
758 }
759 }
760 os_log_t get() const { return os_log_; }
761
762 private:
763 os_log_t os_log_;
Eric Noyaufce100702017-10-16 09:46:34764 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
765 const os_log_type_t os_log_type = [](LogSeverity severity) {
766 switch (severity) {
Lei Zhang93dd42572020-10-23 18:45:53767 case LOGGING_INFO:
Eric Noyaufce100702017-10-16 09:46:34768 return OS_LOG_TYPE_INFO;
Lei Zhang93dd42572020-10-23 18:45:53769 case LOGGING_WARNING:
Eric Noyaufce100702017-10-16 09:46:34770 return OS_LOG_TYPE_DEFAULT;
Lei Zhang93dd42572020-10-23 18:45:53771 case LOGGING_ERROR:
Eric Noyaufce100702017-10-16 09:46:34772 return OS_LOG_TYPE_ERROR;
Lei Zhang93dd42572020-10-23 18:45:53773 case LOGGING_FATAL:
Eric Noyaufce100702017-10-16 09:46:34774 return OS_LOG_TYPE_FAULT;
Avi Drissmana1d016c2022-05-12 21:58:20775 case LOGGING_VERBOSE:
776 return OS_LOG_TYPE_DEBUG;
Eric Noyaufce100702017-10-16 09:46:34777 default:
Avi Drissmana1d016c2022-05-12 21:58:20778 return OS_LOG_TYPE_DEFAULT;
Eric Noyaufce100702017-10-16 09:46:34779 }
780 }(severity_);
781 os_log_with_type(log.get(), os_log_type, "%{public}s",
782 str_newline.c_str());
mark4c7449c2015-11-10 19:53:42783 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43784#elif BUILDFLAG(IS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25785 android_LogPriority priority =
786 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50787 switch (severity_) {
Lei Zhang93dd42572020-10-23 18:45:53788 case LOGGING_INFO:
[email protected]3132e35c2011-07-07 20:46:50789 priority = ANDROID_LOG_INFO;
790 break;
Lei Zhang93dd42572020-10-23 18:45:53791 case LOGGING_WARNING:
[email protected]3132e35c2011-07-07 20:46:50792 priority = ANDROID_LOG_WARN;
793 break;
Lei Zhang93dd42572020-10-23 18:45:53794 case LOGGING_ERROR:
[email protected]3132e35c2011-07-07 20:46:50795 priority = ANDROID_LOG_ERROR;
796 break;
Lei Zhang93dd42572020-10-23 18:45:53797 case LOGGING_FATAL:
[email protected]3132e35c2011-07-07 20:46:50798 priority = ANDROID_LOG_FATAL;
799 break;
800 }
Tomasz Śniatowski23dd15af2019-02-15 08:32:03801 const char kAndroidLogTag[] = "chromium";
Xianzhu Wangae8d96a32018-10-16 20:41:13802#if DCHECK_IS_ON()
803 // Split the output by new lines to prevent the Android system from
804 // truncating the log.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03805 std::vector<std::string> lines = base::SplitString(
806 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
807 // str_newline has an extra newline appended to it (at the top of this
808 // function), so skip the last split element to avoid needlessly
809 // logging an empty string.
810 lines.pop_back();
811 for (const auto& line : lines)
812 __android_log_write(priority, kAndroidLogTag, line.c_str());
Xianzhu Wangae8d96a32018-10-16 20:41:13813#else
814 // The Android system may truncate the string if it's too long.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03815 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18816#endif
Xiaohan Wang38e4ebb2022-01-19 06:57:43817#elif BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02818 // LogMessage() will silently drop the message if the logger is not valid.
Weza38cc532021-12-16 22:58:20819 // Skip the final character of |str_newline|, since LogMessage() will add
820 // a newline.
821 const auto message = base::StringPiece(str_newline).substr(message_start_);
822 GetScopedFxLogger().LogMessage(file_, line_,
823 message.substr(0, message.size() - 1),
824 LogSeverityToFuchsiaLogSeverity(severity_));
Xiaohan Wang38e4ebb2022-01-19 06:57:43825#endif // BUILDFLAG(IS_FUCHSIA)
Sharon Yang7cb919a2019-05-20 20:27:15826 }
827
Wez6c8acb82019-07-18 00:32:59828 if (ShouldLogToStderr(severity_)) {
Benoit Lizeed678192022-01-20 10:14:54829 // Not using fwrite() here, as there are crashes on Windows when CRT calls
830 // malloc() internally, triggering an OOM crash. This likely means that the
831 // process is close to OOM, but at least get the proper error message out,
832 // and give the caller a chance to free() up some resources. For instance if
833 // the calling code is:
834 //
835 // allocate_something();
836 // if (!TryToDoSomething()) {
837 // LOG(ERROR) << "Something went wrong";
838 // free_something();
839 // }
840 WriteToFd(STDERR_FILENO, str_newline.data(), str_newline.size());
[email protected]f6abeba2008-08-08 13:27:28841 }
[email protected]52a261f2009-03-03 15:01:12842
thestig3e4787d2015-05-19 19:31:52843 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09844 // We can have multiple threads and/or processes, so try to prevent them
845 // from clobbering each other's writes.
846 // If the client app did not call InitLogging, and the lock has not
847 // been created do it now. We do this on demand, but if two threads try
848 // to do this at the same time, there will be a race condition to create
849 // the lock. This is why InitLogging should be called from the main
850 // thread at the beginning of execution.
Xiaohan Wang38e4ebb2022-01-19 06:57:43851#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:01852 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09853#endif
[email protected]5b84fe32010-09-14 22:24:55854 if (InitializeLogFileHandle()) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43855#if BUILDFLAG(IS_WIN)
[email protected]5b84fe32010-09-14 22:24:55856 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52857 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55858 static_cast<const void*>(str_newline.c_str()),
859 static_cast<DWORD>(str_newline.length()),
860 &num_written,
thestig3e4787d2015-05-19 19:31:52861 nullptr);
Xiaohan Wang38e4ebb2022-01-19 06:57:43862#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Avi Drissman933398e2022-01-22 00:55:42863 std::ignore =
864 fwrite(str_newline.data(), str_newline.size(), 1, g_log_file);
thestig3e4787d2015-05-19 19:31:52865 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39866#else
867#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55868#endif
initial.commitd7cae122008-07-26 21:49:38869 }
870 }
871
Lei Zhang93dd42572020-10-23 18:45:53872 if (severity_ == LOGGING_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40873 // Write the log message to the global activity tracker, if running.
874 base::debug::GlobalActivityTracker* tracker =
875 base::debug::GlobalActivityTracker::Get();
876 if (tracker)
877 tracker->RecordLogMessage(str_newline);
878
Wezd78fee62020-09-11 18:29:14879 char str_stack[1024];
Daniel Chengf45f47602022-02-28 22:38:32880 base::strlcpy(str_stack, str_newline.data(), std::size(str_stack));
Weze976b732018-10-20 03:37:31881 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05882
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45883 if (!GetLogAssertHandlerStack().empty()) {
alex-accc1bde62017-04-19 08:33:55884 LogAssertHandlerFunction log_assert_handler =
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45885 GetLogAssertHandlerStack().top();
alex-accc1bde62017-04-19 08:33:55886
887 if (log_assert_handler) {
888 log_assert_handler.Run(
889 file_, line_,
890 base::StringPiece(str_newline.c_str() + message_start_,
891 stack_start - message_start_),
892 base::StringPiece(str_newline.c_str() + stack_start));
893 }
[email protected]1ffe08c12008-08-13 11:15:11894 } else {
[email protected]82d89ab2014-02-28 18:25:34895 // Don't use the string with the newline, get a fresh version to send to
896 // the debug message process. We also don't display assertions to the
897 // user in release mode. The enduser can't do anything with this
898 // information, and displaying message boxes when the application is
899 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50900#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42901 if (!base::debug::BeingDebugged()) {
902 // Displaying a dialog is unnecessary when debugging and can complicate
903 // debugging.
904 DisplayDebugMessageInDialog(stream_.str());
905 }
[email protected]4d5901272008-11-06 00:33:50906#endif
Daniel Cheng4f5034d2022-03-04 18:34:31907
[email protected]82d89ab2014-02-28 18:25:34908 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52909 IMMEDIATE_CRASH();
initial.commitd7cae122008-07-26 21:49:38910 }
911 }
912}
913
[email protected]eae9c062011-01-11 00:50:59914// writes the common header info to the stream
915void LogMessage::Init(const char* file, int line) {
916 base::StringPiece filename(file);
917 size_t last_slash_pos = filename.find_last_of("\\/");
918 if (last_slash_pos != base::StringPiece::npos)
919 filename.remove_prefix(last_slash_pos + 1);
920
Georg Neisffe34f652021-12-27 21:42:36921#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54922 if (g_log_format == LogFormat::LOG_FORMAT_SYSLOG) {
923 InitWithSyslogPrefix(
924 filename, line, TickCount(), log_severity_name(severity_), g_log_prefix,
925 g_log_process_id, g_log_thread_id, g_log_timestamp, g_log_tickcount);
926 } else
Georg Neisffe34f652021-12-27 21:42:36927#endif // BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54928 {
929 // TODO(darin): It might be nice if the columns were fixed width.
930 stream_ << '[';
931 if (g_log_prefix)
932 stream_ << g_log_prefix << ':';
933 if (g_log_process_id)
934 stream_ << base::GetUniqueIdForProcess() << ':';
935 if (g_log_thread_id)
936 stream_ << base::PlatformThread::CurrentId() << ':';
937 if (g_log_timestamp) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43938#if BUILDFLAG(IS_WIN)
Yuta Hijikata9b7279a2020-08-26 16:10:54939 SYSTEMTIME local_time;
940 GetLocalTime(&local_time);
941 stream_ << std::setfill('0')
942 << std::setw(2) << local_time.wMonth
943 << std::setw(2) << local_time.wDay
944 << '/'
945 << std::setw(2) << local_time.wHour
946 << std::setw(2) << local_time.wMinute
947 << std::setw(2) << local_time.wSecond
948 << '.'
949 << std::setw(3) << local_time.wMilliseconds
950 << ':';
Xiaohan Wang38e4ebb2022-01-19 06:57:43951#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Yuta Hijikata9b7279a2020-08-26 16:10:54952 timeval tv;
953 gettimeofday(&tv, nullptr);
954 time_t t = tv.tv_sec;
955 struct tm local_time;
956 localtime_r(&t, &local_time);
957 struct tm* tm_time = &local_time;
958 stream_ << std::setfill('0')
959 << std::setw(2) << 1 + tm_time->tm_mon
960 << std::setw(2) << tm_time->tm_mday
961 << '/'
962 << std::setw(2) << tm_time->tm_hour
963 << std::setw(2) << tm_time->tm_min
964 << std::setw(2) << tm_time->tm_sec
965 << '.'
966 << std::setw(6) << tv.tv_usec
967 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39968#else
969#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:34970#endif
Yuta Hijikata9b7279a2020-08-26 16:10:54971 }
972 if (g_log_tickcount)
973 stream_ << TickCount() << ':';
974 if (severity_ >= 0) {
975 stream_ << log_severity_name(severity_);
976 } else {
977 stream_ << "VERBOSE" << -severity_;
978 }
979 stream_ << ":" << filename << "(" << line << ")] ";
[email protected]eae9c062011-01-11 00:50:59980 }
pkasting9cf9b94a2014-10-01 22:18:43981 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59982}
983
Xiaohan Wang38e4ebb2022-01-19 06:57:43984#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:20985// This has already been defined in the header, but defining it again as DWORD
986// ensures that the type used in the header is equivalent to DWORD. If not,
987// the redefinition is a compile error.
988typedef DWORD SystemErrorCode;
989#endif
990
991SystemErrorCode GetLastSystemErrorCode() {
Xiaohan Wang38e4ebb2022-01-19 06:57:43992#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:20993 return ::GetLastError();
Xiaohan Wang38e4ebb2022-01-19 06:57:43994#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:20995 return errno;
[email protected]d8617a62009-10-09 23:52:20996#endif
997}
998
[email protected]c914d8a2014-04-23 01:11:01999BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Xiaohan Wang38e4ebb2022-01-19 06:57:431000#if BUILDFLAG(IS_WIN)
thestig75f87352014-12-03 21:42:271001 const int kErrorMessageBufferSize = 256;
1002 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:011003 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:521004 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Daniel Chengf45f47602022-02-28 22:38:321005 std::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:011006 if (len) {
1007 // Messages returned by system end with line breaks.
1008 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:451009 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:011010 }
Bruce Dawson19175842017-08-02 17:00:451011 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:011012 GetLastError(), error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431013#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:141014 return base::safe_strerror(error_code) +
1015 base::StringPrintf(" (%d)", error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431016#endif // BUILDFLAG(IS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391017}
[email protected]d8617a62009-10-09 23:52:201018
Xiaohan Wang38e4ebb2022-01-19 06:57:431019#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201020Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1021 int line,
1022 LogSeverity severity,
1023 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001024 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201025
1026Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011027 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:061028 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1029 // field) and use Alias in hopes that it makes it into crash dumps.
1030 DWORD last_error = err_;
1031 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201032}
Xiaohan Wang38e4ebb2022-01-19 06:57:431033#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201034ErrnoLogMessage::ErrnoLogMessage(const char* file,
1035 int line,
1036 LogSeverity severity,
1037 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001038 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201039
1040ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011041 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141042 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1043 // field) and use Alias in hopes that it makes it into crash dumps.
1044 int last_error = err_;
1045 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201046}
Xiaohan Wang38e4ebb2022-01-19 06:57:431047#endif // BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201048
initial.commitd7cae122008-07-26 21:49:381049void CloseLogFile() {
Xiaohan Wang38e4ebb2022-01-19 06:57:431050#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:011051 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:091052#endif
[email protected]17dcf752013-07-15 21:47:091053 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381054}
1055
Yuta Hijikata000df18f2020-11-18 06:55:581056#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:531057FILE* DuplicateLogFILE() {
1058 if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle())
1059 return nullptr;
1060
1061 int log_fd = fileno(g_log_file);
1062 if (log_fd == -1)
1063 return nullptr;
1064 base::ScopedFD dup_fd(dup(log_fd));
1065 if (dup_fd == -1)
1066 return nullptr;
1067 FILE* duplicate = fdopen(dup_fd.get(), "a");
1068 if (!duplicate)
1069 return nullptr;
Avi Drissman933398e2022-01-22 00:55:421070 std::ignore = dup_fd.release();
Robbie McElrath8bf49842019-08-20 22:22:531071 return duplicate;
1072}
1073#endif
1074
Yuta Hijikata9b7279a2020-08-26 16:10:541075// Used for testing. Declared in test/scoped_logging_settings.h.
1076ScopedLoggingSettings::ScopedLoggingSettings()
Wez244270362021-05-04 22:50:581077 : min_log_level_(g_min_log_level),
1078 logging_destination_(g_logging_destination),
Georg Neisffe34f652021-12-27 21:42:361079#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581080 log_format_(g_log_format),
1081#endif // BUILDFLAG(IS_CHROMEOS_ASH)
1082 enable_process_id_(g_log_process_id),
Yuta Hijikata9b7279a2020-08-26 16:10:541083 enable_thread_id_(g_log_thread_id),
1084 enable_timestamp_(g_log_timestamp),
1085 enable_tickcount_(g_log_tickcount),
Wez244270362021-05-04 22:50:581086 log_prefix_(g_log_prefix),
1087 message_handler_(g_log_message_handler) {
1088 if (g_log_file_name)
1089 log_file_name_ = std::make_unique<PathString>(*g_log_file_name);
1090 // Duplicating |g_log_file| is complex & unnecessary for this test helpers'
1091 // use-cases, and so long as |g_log_file_name| is set, it will be re-opened
1092 // automatically anyway, when required, so just close the existing one.
1093 if (g_log_file) {
1094 CHECK(g_log_file_name) << "Un-named |log_file| is not supported.";
1095 CloseLogFileUnlocked();
1096 }
Yuta Hijikata9b7279a2020-08-26 16:10:541097}
1098
1099ScopedLoggingSettings::~ScopedLoggingSettings() {
Wez244270362021-05-04 22:50:581100 // Re-initialize logging via the normal path. This will clean up old file
1101 // name and handle state, including re-initializing the VLOG internal state.
1102 CHECK(InitLogging({
1103 .logging_dest = logging_destination_,
1104 .log_file_path = log_file_name_ ? log_file_name_->data() : nullptr,
Georg Neisffe34f652021-12-27 21:42:361105#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581106 .log_format = log_format_
1107#endif
1108 })) << "~ScopedLoggingSettings() failed to restore settings.";
1109
1110 // Restore plain data settings.
1111 SetMinLogLevel(min_log_level_);
1112 SetLogItems(enable_process_id_, enable_thread_id_, enable_timestamp_,
1113 enable_tickcount_);
1114 SetLogPrefix(log_prefix_);
1115 SetLogMessageHandler(message_handler_);
Yuta Hijikata9b7279a2020-08-26 16:10:541116}
1117
Georg Neisffe34f652021-12-27 21:42:361118#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:541119void ScopedLoggingSettings::SetLogFormat(LogFormat log_format) const {
1120 g_log_format = log_format;
1121}
Yuta Hijikata000df18f2020-11-18 06:55:581122#endif // BUILDFLAG(IS_CHROMEOS_ASH)
Yuta Hijikata9b7279a2020-08-26 16:10:541123
[email protected]e36ddc82009-12-08 04:22:501124void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491125 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501126 const size_t message_len = strlen(message);
Benoit Lizeed678192022-01-20 10:14:541127 WriteToFd(STDERR_FILENO, message, message_len);
[email protected]e36ddc82009-12-08 04:22:501128
1129 if (message_len > 0 && message[message_len - 1] != '\n') {
Benoit Lizeed678192022-01-20 10:14:541130 int rv;
[email protected]e36ddc82009-12-08 04:22:501131 do {
1132 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1133 if (rv < 0) {
1134 // Give up, nothing we can do now.
1135 break;
1136 }
1137 } while (rv != 1);
1138 }
1139 }
1140
Lei Zhang93dd42572020-10-23 18:45:531141 if (level == LOGGING_FATAL)
Daniel Cheng4f5034d2022-03-04 18:34:311142 IMMEDIATE_CRASH();
[email protected]e36ddc82009-12-08 04:22:501143}
1144
[email protected]34a907732012-01-20 06:33:271145// This was defined at the beginning of this file.
1146#undef write
1147
Xiaohan Wang38e4ebb2022-01-19 06:57:431148#if BUILDFLAG(IS_WIN)
ananta61762fb2015-09-18 01:00:091149bool IsLoggingToFileEnabled() {
1150 return g_logging_destination & LOG_TO_FILE;
1151}
1152
Jan Wilken Dörrieb630aca2019-12-04 10:59:111153std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521154 if (g_log_file_name)
1155 return *g_log_file_name;
Jan Wilken Dörrieb630aca2019-12-04 10:59:111156 return std::wstring();
[email protected]f01b88a2013-02-27 22:04:001157}
1158#endif
1159
Xiyuan Xiaa0559da2022-05-05 19:42:451160#if !BUILDFLAG(USE_RUNTIME_VLOG)
1161int GetDisableAllVLogLevel() {
1162 return -1;
1163}
1164#endif // !BUILDFLAG(USE_RUNTIME_VLOG)
1165
Fergal Daly432aa7c2022-06-14 07:30:541166// Used for testing. Declared in test/scoped_logging_settings.h.
1167ScopedVmoduleSwitches::ScopedVmoduleSwitches() = default;
1168#if BUILDFLAG(USE_RUNTIME_VLOG)
1169VlogInfo* ScopedVmoduleSwitches::CreateVlogInfoWithSwitches(
1170 const std::string& vmodule_switch) {
1171 // Try get a VlogInfo on which to base this.
1172 // First ensure that VLOG has been initialized.
1173 MaybeInitializeVlogInfo();
1174
1175 // Getting this now and setting it later is racy, however if a
1176 // ScopedVmoduleSwitches is being used on multiple threads that requires
1177 // further coordination and avoids this race.
1178 VlogInfo* base_vlog_info = GetVlogInfo();
1179 if (!base_vlog_info) {
1180 // Base is |nullptr|, so just create it from scratch.
1181 return new VlogInfo(/*v_switch_=*/"", vmodule_switch, &g_min_log_level);
1182 }
1183 return base_vlog_info->WithSwitches(vmodule_switch);
1184}
1185
1186void ScopedVmoduleSwitches::InitWithSwitches(
1187 const std::string& vmodule_switch) {
1188 // Make sure we are only initialized once.
1189 CHECK(!scoped_vlog_info_);
1190 {
1191#if defined(LEAK_SANITIZER) && !BUILDFLAG(IS_NACL)
1192 // See comments on |g_vlog_info|.
1193 ScopedLeakSanitizerDisabler lsan_disabler;
1194#endif // defined(LEAK_SANITIZER)
1195 scoped_vlog_info_ = CreateVlogInfoWithSwitches(vmodule_switch);
1196 }
1197 previous_vlog_info_ = ExchangeVlogInfo(scoped_vlog_info_);
1198}
1199
1200ScopedVmoduleSwitches::~ScopedVmoduleSwitches() {
1201 VlogInfo* replaced_vlog_info = ExchangeVlogInfo(previous_vlog_info_);
1202 // Make sure something didn't replace our scoped VlogInfo while we weren't
1203 // looking.
1204 CHECK_EQ(replaced_vlog_info, scoped_vlog_info_);
1205}
1206#else
1207void ScopedVmoduleSwitches::InitWithSwitches(
1208 const std::string& vmodule_switch) {}
1209
1210ScopedVmoduleSwitches::~ScopedVmoduleSwitches() = default;
1211#endif // BUILDFLAG(USE_RUNTIME_VLOG)
1212
[email protected]96fd0032009-04-24 00:13:081213} // namespace logging
initial.commitd7cae122008-07-26 21:49:381214
[email protected]81411c62014-07-08 23:03:061215std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391216 return out << (wstr ? base::WStringPiece(wstr) : base::WStringPiece());
1217}
1218
1219std::ostream& std::operator<<(std::ostream& out, const std::wstring& wstr) {
1220 return out << base::WStringPiece(wstr);
1221}
1222
1223std::ostream& std::operator<<(std::ostream& out, const char16_t* str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461224 return out << (str16 ? base::StringPiece16(str16) : base::StringPiece16());
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391225}
1226
1227std::ostream& std::operator<<(std::ostream& out, const std::u16string& str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461228 return out << base::StringPiece16(str16);
initial.commitd7cae122008-07-26 21:49:381229}