blob: b95671f23d68d7e4d6ec19c9f06cb9a82c17840b [file] [log] [blame]
[email protected]63e66802012-01-18 21:21:091// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
[email protected]b16ef312008-08-19 18:36:235#include "base/logging.h"
[email protected]f6abeba2008-08-08 13:27:286
Hans Wennborg12aea3e2020-04-14 15:29:007// logging.h is a widely included header and its size has significant impact on
8// build time. Try not to raise this limit unless absolutely necessary. See
9// https://chromium.googlesource.com/chromium/src/+/HEAD/docs/wmax_tokens.md
10#ifndef NACL_TC_REV
Hans Wennborg944479f2020-06-25 21:39:2511#pragma clang max_tokens_here 350000
Hans Wennborg12aea3e2020-04-14 15:29:0012#endif // NACL_TC_REV
13
Hans Wennborg944479f2020-06-25 21:39:2514#ifdef BASE_CHECK_H_
15#error "logging.h should not include check.h"
16#endif
17
avi51ba3e692015-12-26 17:30:5018#include <limits.h>
avi9b6f42932015-12-26 22:15:1419#include <stdint.h>
20
Avi Drissman933398e2022-01-22 00:55:4221#include <tuple>
David Bienvenub4b441e2020-09-23 05:49:5722#include <vector>
23
David Sanders6e709942022-04-05 06:49:2624#include "base/base_export.h"
Lukasz Anforowicz872567d2021-09-08 19:49:2225#include "base/debug/crash_logging.h"
Kalvin Lee70699ccd2022-04-28 17:27:3626#include "base/immediate_crash.h"
Chris Hamilton306740d2019-04-25 18:48:3627#include "base/pending_task.h"
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:3928#include "base/strings/string_piece.h"
Chris Hamilton306740d2019-04-25 18:48:3629#include "base/task/common/task_annotator.h"
Eric Secklerf6c544f2020-06-02 10:49:2130#include "base/trace_event/base_tracing.h"
avi9b6f42932015-12-26 22:15:1431#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5032
Xiaohan Wang38e4ebb2022-01-19 06:57:4333#if BUILDFLAG(IS_WIN)
[email protected]e36ddc82009-12-08 04:22:5034#include <io.h>
alex-accc1bde62017-04-19 08:33:5535#include <windows.h>
[email protected]f6abeba2008-08-08 13:27:2836typedef HANDLE FileHandle;
[email protected]e36ddc82009-12-08 04:22:5037// Windows warns on using write(). It prefers _write().
38#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
39// Windows doesn't define STDERR_FILENO. Define it here.
40#define STDERR_FILENO 2
Eric Noyaufce100702017-10-16 09:46:3441
Xiaohan Wang38e4ebb2022-01-19 06:57:4342#elif BUILDFLAG(IS_APPLE)
Eric Noyaufce100702017-10-16 09:46:3443// In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
44// in favor of OS_LOG (Unified Logging).
45#include <AvailabilityMacros.h>
Xiaohan Wang38e4ebb2022-01-19 06:57:4346#if BUILDFLAG(IS_IOS)
Eric Noyaufce100702017-10-16 09:46:3447#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
48#define USE_ASL
49#endif
Xiaohan Wang38e4ebb2022-01-19 06:57:4350#else // BUILDFLAG(IS_IOS)
Eric Noyaufce100702017-10-16 09:46:3451#if !defined(MAC_OS_X_VERSION_10_12) || \
52 MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
53#define USE_ASL
54#endif
Xiaohan Wang38e4ebb2022-01-19 06:57:4355#endif // BUILDFLAG(IS_IOS)
Eric Noyaufce100702017-10-16 09:46:3456
57#if defined(USE_ASL)
mark4c7449c2015-11-10 19:53:4258#include <asl.h>
Eric Noyaufce100702017-10-16 09:46:3459#else
60#include <os/log.h>
61#endif
62
mark4c7449c2015-11-10 19:53:4263#include <CoreFoundation/CoreFoundation.h>
[email protected]f6abeba2008-08-08 13:27:2864#include <mach/mach.h>
65#include <mach/mach_time.h>
66#include <mach-o/dyld.h>
Eric Noyaufce100702017-10-16 09:46:3467
Xiaohan Wang38e4ebb2022-01-19 06:57:4368#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
69#if BUILDFLAG(IS_NACL)
thestig75f87352014-12-03 21:42:2770#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0871#endif
[email protected]052f1b52008-11-06 21:43:0772#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5973#endif
74
Xiaohan Wang38e4ebb2022-01-19 06:57:4375#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:0276#include "base/fuchsia/scoped_fx_logger.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3977#endif
78
Xiaohan Wang38e4ebb2022-01-19 06:57:4379#if BUILDFLAG(IS_ANDROID)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3980#include <android/log.h>
81#endif
82
Xiaohan Wang38e4ebb2022-01-19 06:57:4383#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:2084#include <errno.h>
mark4c7449c2015-11-10 19:53:4285#include <paths.h>
[email protected]f6abeba2008-08-08 13:27:2886#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0087#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2888#include <string.h>
mark4c7449c2015-11-10 19:53:4289#include <sys/stat.h>
Chris Findeisen2a373a2d2019-08-15 19:44:3090#include "base/process/process_handle.h"
[email protected]f6abeba2008-08-08 13:27:2891#define MAX_PATH PATH_MAX
92typedef FILE* FileHandle;
[email protected]f6abeba2008-08-08 13:27:2893#endif
94
[email protected]1f88b5162011-04-01 00:02:2995#include <algorithm>
96#include <cstring>
initial.commitd7cae122008-07-26 21:49:3897#include <ctime>
98#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2999#include <ostream>
[email protected]c914d8a2014-04-23 01:11:01100#include <string>
alex-accc1bde62017-04-19 08:33:55101#include <utility>
[email protected]b16ef312008-08-19 18:36:23102
initial.commitd7cae122008-07-26 21:49:38103#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:55104#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:38105#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:28106#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:55107#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:05108#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:50109#include "base/debug/debugger.h"
110#include "base/debug/stack_trace.h"
Alan Cutter9b0e1ab2019-03-21 04:22:16111#include "base/debug/task_trace.h"
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45112#include "base/no_destructor.h"
Sharon Yanga4b908de2019-05-07 22:19:03113#include "base/path_service.h"
[email protected]2025d002012-11-14 20:54:35114#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:00115#include "base/strings/string_piece.h"
Xianzhu Wangae8d96a32018-10-16 20:41:13116#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:01117#include "base/strings/string_util.h"
118#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42119#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07120#include "base/strings/utf_string_conversions.h"
Benoit Lize5c98a832020-07-07 16:32:01121#include "base/synchronization/lock.h"
Yuta Hijikata9b7279a2020-08-26 16:10:54122#include "base/test/scoped_logging_settings.h"
[email protected]63e66802012-01-18 21:21:09123#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36124#include "base/vlog.h"
Yuta Hijikata000df18f2020-11-18 06:55:58125#include "build/chromeos_buildflags.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39126
Xiaohan Wang38e4ebb2022-01-19 06:57:43127#if BUILDFLAG(IS_WIN)
Cliff Smolinskyc5c52102019-05-03 20:51:54128#include "base/win/win_util.h"
129#endif
130
Xiaohan Wang38e4ebb2022-01-19 06:57:43131#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24132#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04133#endif
[email protected]52a261f2009-03-03 15:01:12134
Yuta Hijikata000df18f2020-11-18 06:55:58135#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:53136#include "base/files/scoped_file.h"
137#endif
138
initial.commitd7cae122008-07-26 21:49:38139namespace logging {
140
[email protected]064aa162011-12-03 00:30:08141namespace {
142
Xiyuan Xiaa0559da2022-05-05 19:42:45143#if BUILDFLAG(USE_RUNTIME_VLOG)
thestig3e4787d2015-05-19 19:31:52144VlogInfo* g_vlog_info = nullptr;
145VlogInfo* g_vlog_info_prev = nullptr;
Xiyuan Xiaa0559da2022-05-05 19:42:45146#endif // BUILDFLAG(USE_RUNTIME_VLOG)
initial.commitd7cae122008-07-26 21:49:38147
weza245bd072017-06-18 23:26:34148const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
Daniel Chengf45f47602022-02-28 22:38:32149static_assert(LOGGING_NUM_SEVERITIES == std::size(log_severity_names),
weza245bd072017-06-18 23:26:34150 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38151
thestig75f87352014-12-03 21:42:27152const char* log_severity_name(int severity) {
Lei Zhang93dd42572020-10-23 18:45:53153 if (severity >= 0 && severity < LOGGING_NUM_SEVERITIES)
[email protected]80f360a2014-01-23 01:36:19154 return log_severity_names[severity];
155 return "UNKNOWN";
156}
157
thestig3e4787d2015-05-19 19:31:52158int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32159
Sharon Yang7cb919a2019-05-20 20:27:15160// Specifies the process' logging sink(s), represented as a combination of
161// LoggingDestination values joined by bitwise OR.
Peter Kasting40cfeae2021-06-14 12:21:48162uint32_t g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38163
Georg Neisffe34f652021-12-27 21:42:36164#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata1fc8f6342020-09-01 03:25:56165// Specifies the format of log header for chrome os.
166LogFormat g_log_format = LogFormat::LOG_FORMAT_SYSLOG;
Yuta Hijikata9b7279a2020-08-26 16:10:54167#endif
168
Xiaohan Wang38e4ebb2022-01-19 06:57:43169#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02170// Retains system logging structures.
171base::ScopedFxLogger& GetScopedFxLogger() {
172 static base::NoDestructor<base::ScopedFxLogger> logger;
173 return *logger;
174}
175#endif
176
Lei Zhang93dd42572020-10-23 18:45:53177// For LOGGING_ERROR and above, always print to stderr.
178const int kAlwaysPrintErrorLevel = LOGGING_ERROR;
[email protected]a33c9892008-08-25 20:10:31179
[email protected]614e9fa2008-08-11 22:52:59180// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38181// will be lazily initialized to the default value when it is
182// first needed.
jdoerrie5c4dc4e2019-02-01 18:02:33183using PathString = base::FilePath::StringType;
thestig3e4787d2015-05-19 19:31:52184PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38185
thestig3e4787d2015-05-19 19:31:52186// This file is lazily opened and the handle may be nullptr
187FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38188
thestig3e4787d2015-05-19 19:31:52189// What should be prepended to each message?
190bool g_log_process_id = false;
191bool g_log_thread_id = false;
192bool g_log_timestamp = true;
193bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31194const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38195
[email protected]81e0a852010-08-17 00:38:12196// Should we pop up fatal debug messages in a dialog?
197bool show_error_dialogs = false;
198
initial.commitd7cae122008-07-26 21:49:38199// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55200// the debug message dialog and process termination. Assert handlers are stored
201// in stack to allow overriding and restoring.
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45202base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() {
203 static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance;
204 return *instance;
205}
alex-accc1bde62017-04-19 08:33:55206
[email protected]2b07b8412009-11-25 15:26:34207// A log message handler that gets notified of every log message we process.
Wez244270362021-05-04 22:50:58208LogMessageHandlerFunction g_log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38209
avi9b6f42932015-12-26 22:15:14210uint64_t TickCount() {
Xiaohan Wang38e4ebb2022-01-19 06:57:43211#if BUILDFLAG(IS_WIN)
[email protected]f8588472008-11-05 23:17:24212 return GetTickCount();
Xiaohan Wang38e4ebb2022-01-19 06:57:43213#elif BUILDFLAG(IS_FUCHSIA)
Sharon Yang52c60992019-05-16 22:41:35214 return zx_clock_get_monotonic() /
Wezb0501302018-03-09 05:18:45215 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
Xiaohan Wang38e4ebb2022-01-19 06:57:43216#elif BUILDFLAG(IS_APPLE)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39217 return mach_absolute_time();
Xiaohan Wang38e4ebb2022-01-19 06:57:43218#elif BUILDFLAG(IS_NACL)
[email protected]19ea84ca2010-11-12 08:37:08219 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
220 // So we have to use clock() for now.
221 return clock();
Xiaohan Wang38e4ebb2022-01-19 06:57:43222#elif BUILDFLAG(IS_POSIX)
[email protected]052f1b52008-11-06 21:43:07223 struct timespec ts;
224 clock_gettime(CLOCK_MONOTONIC, &ts);
225
avi9b6f42932015-12-26 22:15:14226 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
227 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07228
229 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24230#endif
231}
232
[email protected]614e9fa2008-08-11 22:52:59233void DeleteFilePath(const PathString& log_name) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43234#if BUILDFLAG(IS_WIN)
Jan Wilken Dörrieb630aca2019-12-04 10:59:11235 DeleteFile(log_name.c_str());
Xiaohan Wang38e4ebb2022-01-19 06:57:43236#elif BUILDFLAG(IS_NACL)
[email protected]ac07ec52013-04-22 17:32:45237 // Do nothing; unlink() isn't supported on NaCl.
Xiaohan Wang38e4ebb2022-01-19 06:57:43238#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59239 unlink(log_name.c_str());
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39240#else
241#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28242#endif
243}
initial.commitd7cae122008-07-26 21:49:38244
[email protected]5f95d532010-10-01 17:16:58245PathString GetDefaultLogFile() {
Xiaohan Wang38e4ebb2022-01-19 06:57:43246#if BUILDFLAG(IS_WIN)
[email protected]5b84fe32010-09-14 22:24:55247 // On Windows we use the same path as the exe.
Jan Wilken Dörrieb630aca2019-12-04 10:59:11248 wchar_t module_name[MAX_PATH];
249 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58250
scottmgfc5b7072015-01-27 21:46:28251 PathString log_name = module_name;
252 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58253 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28254 log_name.erase(last_backslash + 1);
Jan Wilken Dörrieb630aca2019-12-04 10:59:11255 log_name += FILE_PATH_LITERAL("debug.log");
scottmgfc5b7072015-01-27 21:46:28256 return log_name;
Xiaohan Wang38e4ebb2022-01-19 06:57:43257#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55258 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58259 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55260#endif
261}
262
ananta61762fb2015-09-18 01:00:09263// We don't need locks on Windows for atomically appending to files. The OS
264// provides this functionality.
Xiaohan Wang38e4ebb2022-01-19 06:57:43265#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55266
Benoit Lize5c98a832020-07-07 16:32:01267base::Lock& GetLoggingLock() {
268 static base::NoDestructor<base::Lock> lock;
269 return *lock;
270}
[email protected]5b84fe32010-09-14 22:24:55271
Xiaohan Wang38e4ebb2022-01-19 06:57:43272#endif // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
ananta61762fb2015-09-18 01:00:09273
thestig3e4787d2015-05-19 19:31:52274// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38275// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52276// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38277bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52278 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38279 return true;
280
thestig3e4787d2015-05-19 19:31:52281 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59282 // Nobody has called InitLogging to specify a debug log file, so here we
283 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52284 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38285 }
286
Robbie McElrath8bf49842019-08-20 22:22:53287 if ((g_logging_destination & LOG_TO_FILE) == 0)
288 return true;
289
Xiaohan Wang38e4ebb2022-01-19 06:57:43290#if BUILDFLAG(IS_WIN)
Robbie McElrath8bf49842019-08-20 22:22:53291 // The FILE_APPEND_DATA access mask ensures that the file is atomically
292 // appended to across accesses from multiple threads.
293 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
294 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
Jan Wilken Dörrieb630aca2019-12-04 10:59:11295 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
Robbie McElrath8bf49842019-08-20 22:22:53296 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
297 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
298 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
299 // We are intentionally not using FilePath or FileUtil here to reduce the
300 // dependencies of the logging implementation. For e.g. FilePath and
301 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
302 // some consumers of base logging like chrome_elf, etc.
303 // Please don't change the code below to use FilePath.
304 // try the current directory
Jan Wilken Dörrieb630aca2019-12-04 10:59:11305 wchar_t system_buffer[MAX_PATH];
Robbie McElrath8bf49842019-08-20 22:22:53306 system_buffer[0] = 0;
Daniel Chengf45f47602022-02-28 22:38:32307 DWORD len = ::GetCurrentDirectory(std::size(system_buffer), system_buffer);
308 if (len == 0 || len > std::size(system_buffer))
Robbie McElrath8bf49842019-08-20 22:22:53309 return false;
310
311 *g_log_file_name = system_buffer;
312 // Append a trailing backslash if needed.
313 if (g_log_file_name->back() != L'\\')
Jan Wilken Dörrieb630aca2019-12-04 10:59:11314 *g_log_file_name += FILE_PATH_LITERAL("\\");
315 *g_log_file_name += FILE_PATH_LITERAL("debug.log");
Robbie McElrath8bf49842019-08-20 22:22:53316
Jan Wilken Dörrieb630aca2019-12-04 10:59:11317 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52318 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
319 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
320 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
Robbie McElrath8bf49842019-08-20 22:22:53321 g_log_file = nullptr;
[email protected]78c6dd62009-06-08 23:29:11322 return false;
Robbie McElrath8bf49842019-08-20 22:22:53323 }
324 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43325#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Robbie McElrath8bf49842019-08-20 22:22:53326 g_log_file = fopen(g_log_file_name->c_str(), "a");
327 if (g_log_file == nullptr)
328 return false;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39329#else
330#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28331#endif
[email protected]1d8c2702008-08-19 23:39:32332
initial.commitd7cae122008-07-26 21:49:38333 return true;
334}
335
[email protected]17dcf752013-07-15 21:47:09336void CloseFile(FileHandle log) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43337#if BUILDFLAG(IS_WIN)
[email protected]17dcf752013-07-15 21:47:09338 CloseHandle(log);
Xiaohan Wang38e4ebb2022-01-19 06:57:43339#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09340 fclose(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39341#else
342#error Unsupported platform
[email protected]17dcf752013-07-15 21:47:09343#endif
344}
345
346void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52347 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09348 return;
349
thestig3e4787d2015-05-19 19:31:52350 CloseFile(g_log_file);
351 g_log_file = nullptr;
Robbie McElrath8bf49842019-08-20 22:22:53352
353 // If we initialized logging via an externally-provided file descriptor, we
354 // won't have a log path set and shouldn't try to reopen the log file.
355 if (!g_log_file_name)
356 g_logging_destination &= ~LOG_TO_FILE;
[email protected]17dcf752013-07-15 21:47:09357}
358
Xiaohan Wang38e4ebb2022-01-19 06:57:43359#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02360inline FuchsiaLogSeverity LogSeverityToFuchsiaLogSeverity(
361 LogSeverity severity) {
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38362 switch (severity) {
363 case LOGGING_INFO:
Wez45e3ffe2021-09-24 02:10:02364 return FUCHSIA_LOG_INFO;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38365 case LOGGING_WARNING:
Wez45e3ffe2021-09-24 02:10:02366 return FUCHSIA_LOG_WARNING;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38367 case LOGGING_ERROR:
Wez45e3ffe2021-09-24 02:10:02368 return FUCHSIA_LOG_ERROR;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38369 case LOGGING_FATAL:
370 // Don't use FX_LOG_FATAL, otherwise fx_logger_log() will abort().
Wez45e3ffe2021-09-24 02:10:02371 return FUCHSIA_LOG_ERROR;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38372 }
373 if (severity > -3) {
374 // LOGGING_VERBOSE levels 1 and 2.
Wez45e3ffe2021-09-24 02:10:02375 return FUCHSIA_LOG_DEBUG;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38376 }
377 // LOGGING_VERBOSE levels 3 and higher, or incorrect levels.
Wez45e3ffe2021-09-24 02:10:02378 return FUCHSIA_LOG_TRACE;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38379}
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38380#endif // defined (OS_FUCHSIA)
381
Benoit Lizeed678192022-01-20 10:14:54382void WriteToFd(int fd, const char* data, size_t length) {
383 size_t bytes_written = 0;
384 int rv;
385 while (bytes_written < length) {
386 rv = HANDLE_EINTR(write(fd, data + bytes_written, length - bytes_written));
387 if (rv < 0) {
388 // Give up, nothing we can do now.
389 break;
390 }
391 bytes_written += rv;
392 }
393}
394
[email protected]064aa162011-12-03 00:30:08395} // namespace
396
Tomas Popelaafffa972018-11-13 20:42:05397#if defined(DCHECK_IS_CONFIGURABLE)
Lei Zhang93dd42572020-10-23 18:45:53398// In DCHECK-enabled Chrome builds, allow the meaning of LOGGING_DCHECK to be
Wez289477f2017-08-24 20:51:30399// determined at run-time. We default it to INFO, to avoid it triggering
400// crashes before the run-time has explicitly chosen the behaviour.
Lei Zhang93dd42572020-10-23 18:45:53401BASE_EXPORT logging::LogSeverity LOGGING_DCHECK = LOGGING_INFO;
Tomas Popelaafffa972018-11-13 20:42:05402#endif // defined(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30403
scottmg3c957a52016-12-10 20:57:59404// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
405// an object of the correct type on the LHS of the unused part of the ternary
406// operator.
407std::ostream* g_swallow_stream;
408
[email protected]5e3f7c22013-06-21 21:15:33409bool BaseInitLoggingImpl(const LoggingSettings& settings) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43410#if BUILDFLAG(IS_NACL)
Sharon Yang7cb919a2019-05-20 20:27:15411 // Can log only to the system debug log and stderr.
412 CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR),
413 0u);
[email protected]ac07ec52013-04-22 17:32:45414#endif
Robbie McElrath8bf49842019-08-20 22:22:53415
Georg Neisffe34f652021-12-27 21:42:36416#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata8a93e522020-09-25 08:59:57417 g_log_format = settings.log_format;
418#endif
419
Xiyuan Xiaa0559da2022-05-05 19:42:45420#if BUILDFLAG(USE_RUNTIME_VLOG)
Joshua Peraza236556ce2020-10-22 23:23:31421 if (base::CommandLine::InitializedForCurrentProcess()) {
422 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
423 // Don't bother initializing |g_vlog_info| unless we use one of the
424 // vlog switches.
425 if (command_line->HasSwitch(switches::kV) ||
426 command_line->HasSwitch(switches::kVModule)) {
427 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
428 // by another thread. Don't delete the old VLogInfo, just create a second
429 // one. We keep track of both to avoid memory leak warnings.
430 CHECK(!g_vlog_info_prev);
431 g_vlog_info_prev = g_vlog_info;
[email protected]064aa162011-12-03 00:30:08432
Joshua Peraza236556ce2020-10-22 23:23:31433 g_vlog_info =
434 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
435 command_line->GetSwitchValueASCII(switches::kVModule),
436 &g_min_log_level);
437 }
[email protected]99b7c57f2010-09-29 19:26:36438 }
Xiyuan Xiaa0559da2022-05-05 19:42:45439#endif // defined(USE_RUNTIME_VLOG)
[email protected]99b7c57f2010-09-29 19:26:36440
thestig3e4787d2015-05-19 19:31:52441 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38442
Xiaohan Wang38e4ebb2022-01-19 06:57:43443#if BUILDFLAG(IS_FUCHSIA)
Wez224c0bf62019-05-24 19:26:13444 if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) {
Wez5d4a666c2021-10-04 16:41:36445 GetScopedFxLogger() = base::ScopedFxLogger::CreateForProcess();
Wez224c0bf62019-05-24 19:26:13446 }
447#endif
448
[email protected]5e3f7c22013-06-21 21:15:33449 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52450 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21451 return true;
initial.commitd7cae122008-07-26 21:49:38452
Xiaohan Wang38e4ebb2022-01-19 06:57:43453#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:01454 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09455#endif
[email protected]17dcf752013-07-15 21:47:09456
457 // Calling InitLogging twice or after some log call has already opened the
458 // default log file will re-initialize to the new options.
459 CloseLogFileUnlocked();
460
Yuta Hijikata000df18f2020-11-18 06:55:58461#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:53462 if (settings.log_file) {
463 DCHECK(!settings.log_file_path);
464 g_log_file = settings.log_file;
465 return true;
466 }
467#endif
Lei Zhang93dd42572020-10-23 18:45:53468
Xiaohan Wang5411974b2020-10-10 19:36:12469 DCHECK(settings.log_file_path) << "LOG_TO_FILE set but no log_file_path!";
Robbie McElrath8bf49842019-08-20 22:22:53470
thestig3e4787d2015-05-19 19:31:52471 if (!g_log_file_name)
472 g_log_file_name = new PathString();
Robbie McElrath8bf49842019-08-20 22:22:53473 *g_log_file_name = settings.log_file_path;
[email protected]5e3f7c22013-06-21 21:15:33474 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52475 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38476
[email protected]c7d5da992010-10-28 00:20:21477 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38478}
479
480void SetMinLogLevel(int level) {
Lei Zhang93dd42572020-10-23 18:45:53481 g_min_log_level = std::min(LOGGING_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38482}
483
484int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52485 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38486}
487
skobesc78c0ad72015-12-07 20:21:23488bool ShouldCreateLogMessage(int severity) {
489 if (severity < g_min_log_level)
490 return false;
491
Wez6c8acb82019-07-18 00:32:59492 // Return true here unless we know ~LogMessage won't do anything.
Wez244270362021-05-04 22:50:58493 return g_logging_destination != LOG_NONE || g_log_message_handler ||
skobesc78c0ad72015-12-07 20:21:23494 severity >= kAlwaysPrintErrorLevel;
495}
496
Wez6c8acb82019-07-18 00:32:59497// Returns true when LOG_TO_STDERR flag is set, or |severity| is high.
498// If |severity| is high then true will be returned when no log destinations are
499// set, or only LOG_TO_FILE is set, since that is useful for local development
500// and debugging.
501bool ShouldLogToStderr(int severity) {
502 if (g_logging_destination & LOG_TO_STDERR)
503 return true;
Wez82ba0502022-05-11 08:50:08504
505#if BUILDFLAG(IS_FUCHSIA)
506 // Fuchsia will persist data logged to stdio by a component, so do not emit
507 // logs to stderr unless explicitly configured to do so.
508 return false;
509#else
Wez6c8acb82019-07-18 00:32:59510 if (severity >= kAlwaysPrintErrorLevel)
511 return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
512 return false;
Wez82ba0502022-05-11 08:50:08513#endif
Wez6c8acb82019-07-18 00:32:59514}
515
[email protected]162ac0f2010-11-04 15:50:49516int GetVlogVerbosity() {
517 return std::max(-1, LOG_INFO - GetMinLogLevel());
518}
519
[email protected]99b7c57f2010-09-29 19:26:36520int GetVlogLevelHelper(const char* file, size_t N) {
521 DCHECK_GT(N, 0U);
Xiyuan Xiaa0559da2022-05-05 19:42:45522
523#if BUILDFLAG(USE_RUNTIME_VLOG)
thestig3e4787d2015-05-19 19:31:52524 // Note: |g_vlog_info| may change on a different thread during startup
525 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08526 VlogInfo* vlog_info = g_vlog_info;
527 return vlog_info ?
528 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49529 GetVlogVerbosity();
Xiyuan Xiaa0559da2022-05-05 19:42:45530#else
531 return GetVlogVerbosity();
532#endif // BUILDFLAG(USE_RUNTIME_VLOG)
[email protected]99b7c57f2010-09-29 19:26:36533}
534
initial.commitd7cae122008-07-26 21:49:38535void SetLogItems(bool enable_process_id, bool enable_thread_id,
536 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52537 g_log_process_id = enable_process_id;
538 g_log_thread_id = enable_thread_id;
539 g_log_timestamp = enable_timestamp;
540 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38541}
542
James Cooka0536c32018-08-01 20:13:31543void SetLogPrefix(const char* prefix) {
544 DCHECK(!prefix ||
545 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
546 g_log_prefix = prefix;
547}
548
[email protected]81e0a852010-08-17 00:38:12549void SetShowErrorDialogs(bool enable_dialogs) {
550 show_error_dialogs = enable_dialogs;
551}
552
alex-accc1bde62017-04-19 08:33:55553ScopedLogAssertHandler::ScopedLogAssertHandler(
554 LogAssertHandlerFunction handler) {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45555 GetLogAssertHandlerStack().push(std::move(handler));
alex-accc1bde62017-04-19 08:33:55556}
557
558ScopedLogAssertHandler::~ScopedLogAssertHandler() {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45559 GetLogAssertHandlerStack().pop();
initial.commitd7cae122008-07-26 21:49:38560}
561
[email protected]2b07b8412009-11-25 15:26:34562void SetLogMessageHandler(LogMessageHandlerFunction handler) {
Wez244270362021-05-04 22:50:58563 g_log_message_handler = handler;
[email protected]2b07b8412009-11-25 15:26:34564}
565
[email protected]64e5cc02010-11-03 19:20:27566LogMessageHandlerFunction GetLogMessageHandler() {
Wez244270362021-05-04 22:50:58567 return g_log_message_handler;
[email protected]64e5cc02010-11-03 19:20:27568}
569
[email protected]f2c05492014-06-17 12:04:23570#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22571// Displays a message box to the user with the error message in it.
572// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25573// This is for developers only; we don't use this in circumstances
574// (like release builds) where users could see it, since users don't
575// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22576void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38577 if (str.empty())
578 return;
579
[email protected]81e0a852010-08-17 00:38:12580 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44581 return;
582
Xiaohan Wang38e4ebb2022-01-19 06:57:43583#if BUILDFLAG(IS_WIN)
[email protected]561513f2010-12-16 23:29:25584 // We intentionally don't implement a dialog on other platforms.
585 // You can just look at stderr.
Cliff Smolinskyc5c52102019-05-03 20:51:54586 if (base::win::IsUser32AndGdi32Available()) {
587 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
588 MB_OK | MB_ICONHAND | MB_TOPMOST);
589 } else {
590 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
591 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43592#endif // BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38593}
[email protected]f2c05492014-06-17 12:04:23594#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38595
[email protected]eae9c062011-01-11 00:50:59596LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
597 : severity_(severity), file_(file), line_(line) {
598 Init(file, line);
599}
600
tnagel4a045d3f2015-07-12 14:19:28601LogMessage::LogMessage(const char* file, int line, const char* condition)
Lei Zhang93dd42572020-10-23 18:45:53602 : severity_(LOGGING_FATAL), file_(file), line_(line) {
tnagel4a045d3f2015-07-12 14:19:28603 Init(file, line);
604 stream_ << "Check failed: " << condition << ". ";
605}
606
initial.commitd7cae122008-07-26 21:49:38607LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55608 size_t stack_start = stream_.tellp();
Xiaohan Wang38e4ebb2022-01-19 06:57:43609#if !defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_NACL) && !defined(__UCLIBC__) && \
610 !BUILDFLAG(IS_AIX)
Lei Zhang93dd42572020-10-23 18:45:53611 if (severity_ == LOGGING_FATAL && !base::debug::BeingDebugged()) {
brucedawson7c559eb2015-09-05 00:34:42612 // Include a stack trace on a fatal, unless a debugger is attached.
Alan Cutter9b0e1ab2019-03-21 04:22:16613 base::debug::StackTrace stack_trace;
[email protected]d1ccc35a2010-03-24 05:03:24614 stream_ << std::endl; // Newline to separate from log message.
Alan Cutter9b0e1ab2019-03-21 04:22:16615 stack_trace.OutputToStream(&stream_);
616 base::debug::TaskTrace task_trace;
617 if (!task_trace.empty())
618 task_trace.OutputToStream(&stream_);
Chris Hamilton306740d2019-04-25 18:48:36619
Chris Hamilton888085312019-05-30 00:53:30620 // Include the IPC context, if any.
621 // TODO(chrisha): Integrate with symbolization once those tools exist!
Chris Hamilton306740d2019-04-25 18:48:36622 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
Chris Hamilton888085312019-05-30 00:53:30623 if (task && task->ipc_hash) {
624 stream_ << "IPC message handler context: "
625 << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
Chris Hamilton306740d2019-04-25 18:48:36626 }
Lukasz Anforowicz872567d2021-09-08 19:49:22627
628 // Include the crash keys, if any.
629 base::debug::OutputCrashKeysToStream(stream_);
[email protected]d1ccc35a2010-03-24 05:03:24630 }
[email protected]1d8c2702008-08-19 23:39:32631#endif
[email protected]d1ccc35a2010-03-24 05:03:24632 stream_ << std::endl;
633 std::string str_newline(stream_.str());
Nicolò Mazzucato6c278d9b2019-08-02 16:25:44634 TRACE_LOG_MESSAGE(
635 file_, base::StringPiece(str_newline).substr(message_start_), line_);
[email protected]d1ccc35a2010-03-24 05:03:24636
[email protected]2b07b8412009-11-25 15:26:34637 // Give any log message handler first dibs on the message.
Wez244270362021-05-04 22:50:58638 if (g_log_message_handler &&
639 g_log_message_handler(severity_, file_, line_, message_start_,
640 str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49641 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34642 return;
[email protected]162ac0f2010-11-04 15:50:49643 }
initial.commitd7cae122008-07-26 21:49:38644
thestig3e4787d2015-05-19 19:31:52645 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43646#if BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38647 OutputDebugStringA(str_newline.c_str());
Xiaohan Wang38e4ebb2022-01-19 06:57:43648#elif BUILDFLAG(IS_APPLE)
mark4c7449c2015-11-10 19:53:42649 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Eric Noyaufce100702017-10-16 09:46:34650 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
651 // its successor OS_LOG. If there's something weird about stderr, assume
652 // that log messages are going nowhere and log via ASL/OS_LOG too.
653 // Messages logged via ASL/OS_LOG show up in Console.app.
mark4c7449c2015-11-10 19:53:42654 //
655 // Programs started by launchd, as UI applications normally are, have had
656 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
657 // a pipe to launchd, which logged what it received (see log_redirect_fd in
658 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
659 //
660 // Another alternative would be to determine whether stderr is a pipe to
661 // launchd and avoid logging via ASL only in that case. See 10.7.5
662 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Eric Noyaufce100702017-10-16 09:46:34663 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
664 // to the system log at all.
mark4c7449c2015-11-10 19:53:42665 //
666 // Note that the ASL client by default discards messages whose levels are
667 // below ASL_LEVEL_NOTICE. It's possible to change that with
668 // asl_set_filter(), but this is pointless because syslogd normally applies
669 // the same filter.
Eric Noyaufce100702017-10-16 09:46:34670 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42671 struct stat stderr_stat;
672 if (fstat(fileno(stderr), &stderr_stat) == -1) {
673 return true;
674 }
675 if (!S_ISCHR(stderr_stat.st_mode)) {
676 return false;
677 }
678
679 struct stat dev_null_stat;
680 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
681 return true;
682 }
683
684 return !S_ISCHR(dev_null_stat.st_mode) ||
685 stderr_stat.st_rdev == dev_null_stat.st_rdev;
686 }();
687
Eric Noyaufce100702017-10-16 09:46:34688 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42689 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
690 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42691 CFBundleRef main_bundle = CFBundleGetMainBundle();
692 CFStringRef main_bundle_id_cf =
693 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34694 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42695 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34696 : std::string("");
697#if defined(USE_ASL)
698 // The facility is set to the main bundle ID if available. Otherwise,
699 // "com.apple.console" is used.
700 const class ASLClient {
mark4c7449c2015-11-10 19:53:42701 public:
Bruce Dawson4c6f8e12017-11-16 04:35:59702 explicit ASLClient(const std::string& facility)
703 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
David Bienvenub4b441e2020-09-23 05:49:57704 ASLClient(const ASLClient&) = delete;
705 ASLClient& operator=(const ASLClient&) = delete;
mark4c7449c2015-11-10 19:53:42706 ~ASLClient() { asl_close(client_); }
707
708 aslclient get() const { return client_; }
709
710 private:
711 aslclient client_;
Eric Noyaufce100702017-10-16 09:46:34712 } asl_client(main_bundle_id.empty() ? main_bundle_id
713 : "com.apple.console");
mark4c7449c2015-11-10 19:53:42714
Eric Noyaufce100702017-10-16 09:46:34715 const class ASLMessage {
mark4c7449c2015-11-10 19:53:42716 public:
717 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
David Bienvenub4b441e2020-09-23 05:49:57718 ASLMessage(const ASLMessage&) = delete;
719 ASLMessage& operator=(const ASLMessage&) = delete;
mark4c7449c2015-11-10 19:53:42720 ~ASLMessage() { asl_free(message_); }
721
722 aslmsg get() const { return message_; }
723
724 private:
725 aslmsg message_;
mark4c7449c2015-11-10 19:53:42726 } asl_message;
727
728 // By default, messages are only readable by the admin group. Explicitly
729 // make them readable by the user generating the messages.
730 char euid_string[12];
Daniel Chengf45f47602022-02-28 22:38:32731 snprintf(euid_string, std::size(euid_string), "%d", geteuid());
mark4c7449c2015-11-10 19:53:42732 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
733
734 // Map Chrome log severities to ASL log levels.
735 const char* const asl_level_string = [](LogSeverity severity) {
736 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
737 // non-obvious two-step macro trick achieves what's needed.
738 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
739#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
740#define ASL_LEVEL_STR_X(level) #level
741 switch (severity) {
Lei Zhang93dd42572020-10-23 18:45:53742 case LOGGING_INFO:
mark4c7449c2015-11-10 19:53:42743 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
Lei Zhang93dd42572020-10-23 18:45:53744 case LOGGING_WARNING:
mark4c7449c2015-11-10 19:53:42745 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
Lei Zhang93dd42572020-10-23 18:45:53746 case LOGGING_ERROR:
mark4c7449c2015-11-10 19:53:42747 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
Lei Zhang93dd42572020-10-23 18:45:53748 case LOGGING_FATAL:
mark4c7449c2015-11-10 19:53:42749 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
750 default:
751 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
752 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
753 }
754#undef ASL_LEVEL_STR
755#undef ASL_LEVEL_STR_X
756 }(severity_);
757 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
758
759 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
760
761 asl_send(asl_client.get(), asl_message.get());
Eric Noyaufce100702017-10-16 09:46:34762#else // !defined(USE_ASL)
763 const class OSLog {
764 public:
765 explicit OSLog(const char* subsystem)
766 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
767 : OS_LOG_DEFAULT) {}
David Bienvenub4b441e2020-09-23 05:49:57768 OSLog(const OSLog&) = delete;
769 OSLog& operator=(const OSLog&) = delete;
Eric Noyaufce100702017-10-16 09:46:34770 ~OSLog() {
771 if (os_log_ != OS_LOG_DEFAULT) {
772 os_release(os_log_);
773 }
774 }
775 os_log_t get() const { return os_log_; }
776
777 private:
778 os_log_t os_log_;
Eric Noyaufce100702017-10-16 09:46:34779 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
780 const os_log_type_t os_log_type = [](LogSeverity severity) {
781 switch (severity) {
Lei Zhang93dd42572020-10-23 18:45:53782 case LOGGING_INFO:
Eric Noyaufce100702017-10-16 09:46:34783 return OS_LOG_TYPE_INFO;
Lei Zhang93dd42572020-10-23 18:45:53784 case LOGGING_WARNING:
Eric Noyaufce100702017-10-16 09:46:34785 return OS_LOG_TYPE_DEFAULT;
Lei Zhang93dd42572020-10-23 18:45:53786 case LOGGING_ERROR:
Eric Noyaufce100702017-10-16 09:46:34787 return OS_LOG_TYPE_ERROR;
Lei Zhang93dd42572020-10-23 18:45:53788 case LOGGING_FATAL:
Eric Noyaufce100702017-10-16 09:46:34789 return OS_LOG_TYPE_FAULT;
Avi Drissmana1d016c2022-05-12 21:58:20790 case LOGGING_VERBOSE:
791 return OS_LOG_TYPE_DEBUG;
Eric Noyaufce100702017-10-16 09:46:34792 default:
Avi Drissmana1d016c2022-05-12 21:58:20793 return OS_LOG_TYPE_DEFAULT;
Eric Noyaufce100702017-10-16 09:46:34794 }
795 }(severity_);
796 os_log_with_type(log.get(), os_log_type, "%{public}s",
797 str_newline.c_str());
798#endif // defined(USE_ASL)
mark4c7449c2015-11-10 19:53:42799 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43800#elif BUILDFLAG(IS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25801 android_LogPriority priority =
802 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50803 switch (severity_) {
Lei Zhang93dd42572020-10-23 18:45:53804 case LOGGING_INFO:
[email protected]3132e35c2011-07-07 20:46:50805 priority = ANDROID_LOG_INFO;
806 break;
Lei Zhang93dd42572020-10-23 18:45:53807 case LOGGING_WARNING:
[email protected]3132e35c2011-07-07 20:46:50808 priority = ANDROID_LOG_WARN;
809 break;
Lei Zhang93dd42572020-10-23 18:45:53810 case LOGGING_ERROR:
[email protected]3132e35c2011-07-07 20:46:50811 priority = ANDROID_LOG_ERROR;
812 break;
Lei Zhang93dd42572020-10-23 18:45:53813 case LOGGING_FATAL:
[email protected]3132e35c2011-07-07 20:46:50814 priority = ANDROID_LOG_FATAL;
815 break;
816 }
Tomasz Śniatowski23dd15af2019-02-15 08:32:03817 const char kAndroidLogTag[] = "chromium";
Xianzhu Wangae8d96a32018-10-16 20:41:13818#if DCHECK_IS_ON()
819 // Split the output by new lines to prevent the Android system from
820 // truncating the log.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03821 std::vector<std::string> lines = base::SplitString(
822 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
823 // str_newline has an extra newline appended to it (at the top of this
824 // function), so skip the last split element to avoid needlessly
825 // logging an empty string.
826 lines.pop_back();
827 for (const auto& line : lines)
828 __android_log_write(priority, kAndroidLogTag, line.c_str());
Xianzhu Wangae8d96a32018-10-16 20:41:13829#else
830 // The Android system may truncate the string if it's too long.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03831 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18832#endif
Xiaohan Wang38e4ebb2022-01-19 06:57:43833#elif BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02834 // LogMessage() will silently drop the message if the logger is not valid.
Weza38cc532021-12-16 22:58:20835 // Skip the final character of |str_newline|, since LogMessage() will add
836 // a newline.
837 const auto message = base::StringPiece(str_newline).substr(message_start_);
838 GetScopedFxLogger().LogMessage(file_, line_,
839 message.substr(0, message.size() - 1),
840 LogSeverityToFuchsiaLogSeverity(severity_));
Xiaohan Wang38e4ebb2022-01-19 06:57:43841#endif // BUILDFLAG(IS_FUCHSIA)
Sharon Yang7cb919a2019-05-20 20:27:15842 }
843
Wez6c8acb82019-07-18 00:32:59844 if (ShouldLogToStderr(severity_)) {
Benoit Lizeed678192022-01-20 10:14:54845 // Not using fwrite() here, as there are crashes on Windows when CRT calls
846 // malloc() internally, triggering an OOM crash. This likely means that the
847 // process is close to OOM, but at least get the proper error message out,
848 // and give the caller a chance to free() up some resources. For instance if
849 // the calling code is:
850 //
851 // allocate_something();
852 // if (!TryToDoSomething()) {
853 // LOG(ERROR) << "Something went wrong";
854 // free_something();
855 // }
856 WriteToFd(STDERR_FILENO, str_newline.data(), str_newline.size());
[email protected]f6abeba2008-08-08 13:27:28857 }
[email protected]52a261f2009-03-03 15:01:12858
thestig3e4787d2015-05-19 19:31:52859 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09860 // We can have multiple threads and/or processes, so try to prevent them
861 // from clobbering each other's writes.
862 // If the client app did not call InitLogging, and the lock has not
863 // been created do it now. We do this on demand, but if two threads try
864 // to do this at the same time, there will be a race condition to create
865 // the lock. This is why InitLogging should be called from the main
866 // thread at the beginning of execution.
Xiaohan Wang38e4ebb2022-01-19 06:57:43867#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:01868 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09869#endif
[email protected]5b84fe32010-09-14 22:24:55870 if (InitializeLogFileHandle()) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43871#if BUILDFLAG(IS_WIN)
[email protected]5b84fe32010-09-14 22:24:55872 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52873 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55874 static_cast<const void*>(str_newline.c_str()),
875 static_cast<DWORD>(str_newline.length()),
876 &num_written,
thestig3e4787d2015-05-19 19:31:52877 nullptr);
Xiaohan Wang38e4ebb2022-01-19 06:57:43878#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Avi Drissman933398e2022-01-22 00:55:42879 std::ignore =
880 fwrite(str_newline.data(), str_newline.size(), 1, g_log_file);
thestig3e4787d2015-05-19 19:31:52881 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39882#else
883#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55884#endif
initial.commitd7cae122008-07-26 21:49:38885 }
886 }
887
Lei Zhang93dd42572020-10-23 18:45:53888 if (severity_ == LOGGING_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40889 // Write the log message to the global activity tracker, if running.
890 base::debug::GlobalActivityTracker* tracker =
891 base::debug::GlobalActivityTracker::Get();
892 if (tracker)
893 tracker->RecordLogMessage(str_newline);
894
Wezd78fee62020-09-11 18:29:14895 char str_stack[1024];
Daniel Chengf45f47602022-02-28 22:38:32896 base::strlcpy(str_stack, str_newline.data(), std::size(str_stack));
Weze976b732018-10-20 03:37:31897 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05898
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45899 if (!GetLogAssertHandlerStack().empty()) {
alex-accc1bde62017-04-19 08:33:55900 LogAssertHandlerFunction log_assert_handler =
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45901 GetLogAssertHandlerStack().top();
alex-accc1bde62017-04-19 08:33:55902
903 if (log_assert_handler) {
904 log_assert_handler.Run(
905 file_, line_,
906 base::StringPiece(str_newline.c_str() + message_start_,
907 stack_start - message_start_),
908 base::StringPiece(str_newline.c_str() + stack_start));
909 }
[email protected]1ffe08c12008-08-13 11:15:11910 } else {
[email protected]82d89ab2014-02-28 18:25:34911 // Don't use the string with the newline, get a fresh version to send to
912 // the debug message process. We also don't display assertions to the
913 // user in release mode. The enduser can't do anything with this
914 // information, and displaying message boxes when the application is
915 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50916#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42917 if (!base::debug::BeingDebugged()) {
918 // Displaying a dialog is unnecessary when debugging and can complicate
919 // debugging.
920 DisplayDebugMessageInDialog(stream_.str());
921 }
[email protected]4d5901272008-11-06 00:33:50922#endif
Daniel Cheng4f5034d2022-03-04 18:34:31923
[email protected]82d89ab2014-02-28 18:25:34924 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52925 IMMEDIATE_CRASH();
initial.commitd7cae122008-07-26 21:49:38926 }
927 }
928}
929
[email protected]eae9c062011-01-11 00:50:59930// writes the common header info to the stream
931void LogMessage::Init(const char* file, int line) {
932 base::StringPiece filename(file);
933 size_t last_slash_pos = filename.find_last_of("\\/");
934 if (last_slash_pos != base::StringPiece::npos)
935 filename.remove_prefix(last_slash_pos + 1);
936
Georg Neisffe34f652021-12-27 21:42:36937#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54938 if (g_log_format == LogFormat::LOG_FORMAT_SYSLOG) {
939 InitWithSyslogPrefix(
940 filename, line, TickCount(), log_severity_name(severity_), g_log_prefix,
941 g_log_process_id, g_log_thread_id, g_log_timestamp, g_log_tickcount);
942 } else
Georg Neisffe34f652021-12-27 21:42:36943#endif // BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54944 {
945 // TODO(darin): It might be nice if the columns were fixed width.
946 stream_ << '[';
947 if (g_log_prefix)
948 stream_ << g_log_prefix << ':';
949 if (g_log_process_id)
950 stream_ << base::GetUniqueIdForProcess() << ':';
951 if (g_log_thread_id)
952 stream_ << base::PlatformThread::CurrentId() << ':';
953 if (g_log_timestamp) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43954#if BUILDFLAG(IS_WIN)
Yuta Hijikata9b7279a2020-08-26 16:10:54955 SYSTEMTIME local_time;
956 GetLocalTime(&local_time);
957 stream_ << std::setfill('0')
958 << std::setw(2) << local_time.wMonth
959 << std::setw(2) << local_time.wDay
960 << '/'
961 << std::setw(2) << local_time.wHour
962 << std::setw(2) << local_time.wMinute
963 << std::setw(2) << local_time.wSecond
964 << '.'
965 << std::setw(3) << local_time.wMilliseconds
966 << ':';
Xiaohan Wang38e4ebb2022-01-19 06:57:43967#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Yuta Hijikata9b7279a2020-08-26 16:10:54968 timeval tv;
969 gettimeofday(&tv, nullptr);
970 time_t t = tv.tv_sec;
971 struct tm local_time;
972 localtime_r(&t, &local_time);
973 struct tm* tm_time = &local_time;
974 stream_ << std::setfill('0')
975 << std::setw(2) << 1 + tm_time->tm_mon
976 << std::setw(2) << tm_time->tm_mday
977 << '/'
978 << std::setw(2) << tm_time->tm_hour
979 << std::setw(2) << tm_time->tm_min
980 << std::setw(2) << tm_time->tm_sec
981 << '.'
982 << std::setw(6) << tv.tv_usec
983 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39984#else
985#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:34986#endif
Yuta Hijikata9b7279a2020-08-26 16:10:54987 }
988 if (g_log_tickcount)
989 stream_ << TickCount() << ':';
990 if (severity_ >= 0) {
991 stream_ << log_severity_name(severity_);
992 } else {
993 stream_ << "VERBOSE" << -severity_;
994 }
995 stream_ << ":" << filename << "(" << line << ")] ";
[email protected]eae9c062011-01-11 00:50:59996 }
pkasting9cf9b94a2014-10-01 22:18:43997 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59998}
999
Xiaohan Wang38e4ebb2022-01-19 06:57:431000#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201001// This has already been defined in the header, but defining it again as DWORD
1002// ensures that the type used in the header is equivalent to DWORD. If not,
1003// the redefinition is a compile error.
1004typedef DWORD SystemErrorCode;
1005#endif
1006
1007SystemErrorCode GetLastSystemErrorCode() {
Xiaohan Wang38e4ebb2022-01-19 06:57:431008#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201009 return ::GetLastError();
Xiaohan Wang38e4ebb2022-01-19 06:57:431010#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201011 return errno;
[email protected]d8617a62009-10-09 23:52:201012#endif
1013}
1014
[email protected]c914d8a2014-04-23 01:11:011015BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Xiaohan Wang38e4ebb2022-01-19 06:57:431016#if BUILDFLAG(IS_WIN)
thestig75f87352014-12-03 21:42:271017 const int kErrorMessageBufferSize = 256;
1018 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:011019 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:521020 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Daniel Chengf45f47602022-02-28 22:38:321021 std::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:011022 if (len) {
1023 // Messages returned by system end with line breaks.
1024 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:451025 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:011026 }
Bruce Dawson19175842017-08-02 17:00:451027 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:011028 GetLastError(), error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431029#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:141030 return base::safe_strerror(error_code) +
1031 base::StringPrintf(" (%d)", error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431032#endif // BUILDFLAG(IS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391033}
[email protected]d8617a62009-10-09 23:52:201034
Xiaohan Wang38e4ebb2022-01-19 06:57:431035#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201036Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1037 int line,
1038 LogSeverity severity,
1039 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001040 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201041
1042Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011043 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:061044 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1045 // field) and use Alias in hopes that it makes it into crash dumps.
1046 DWORD last_error = err_;
1047 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201048}
Xiaohan Wang38e4ebb2022-01-19 06:57:431049#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201050ErrnoLogMessage::ErrnoLogMessage(const char* file,
1051 int line,
1052 LogSeverity severity,
1053 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001054 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201055
1056ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011057 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141058 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1059 // field) and use Alias in hopes that it makes it into crash dumps.
1060 int last_error = err_;
1061 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201062}
Xiaohan Wang38e4ebb2022-01-19 06:57:431063#endif // BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201064
initial.commitd7cae122008-07-26 21:49:381065void CloseLogFile() {
Xiaohan Wang38e4ebb2022-01-19 06:57:431066#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:011067 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:091068#endif
[email protected]17dcf752013-07-15 21:47:091069 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381070}
1071
Yuta Hijikata000df18f2020-11-18 06:55:581072#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:531073FILE* DuplicateLogFILE() {
1074 if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle())
1075 return nullptr;
1076
1077 int log_fd = fileno(g_log_file);
1078 if (log_fd == -1)
1079 return nullptr;
1080 base::ScopedFD dup_fd(dup(log_fd));
1081 if (dup_fd == -1)
1082 return nullptr;
1083 FILE* duplicate = fdopen(dup_fd.get(), "a");
1084 if (!duplicate)
1085 return nullptr;
Avi Drissman933398e2022-01-22 00:55:421086 std::ignore = dup_fd.release();
Robbie McElrath8bf49842019-08-20 22:22:531087 return duplicate;
1088}
1089#endif
1090
Yuta Hijikata9b7279a2020-08-26 16:10:541091// Used for testing. Declared in test/scoped_logging_settings.h.
1092ScopedLoggingSettings::ScopedLoggingSettings()
Wez244270362021-05-04 22:50:581093 : min_log_level_(g_min_log_level),
1094 logging_destination_(g_logging_destination),
Georg Neisffe34f652021-12-27 21:42:361095#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581096 log_format_(g_log_format),
1097#endif // BUILDFLAG(IS_CHROMEOS_ASH)
1098 enable_process_id_(g_log_process_id),
Yuta Hijikata9b7279a2020-08-26 16:10:541099 enable_thread_id_(g_log_thread_id),
1100 enable_timestamp_(g_log_timestamp),
1101 enable_tickcount_(g_log_tickcount),
Wez244270362021-05-04 22:50:581102 log_prefix_(g_log_prefix),
1103 message_handler_(g_log_message_handler) {
1104 if (g_log_file_name)
1105 log_file_name_ = std::make_unique<PathString>(*g_log_file_name);
1106 // Duplicating |g_log_file| is complex & unnecessary for this test helpers'
1107 // use-cases, and so long as |g_log_file_name| is set, it will be re-opened
1108 // automatically anyway, when required, so just close the existing one.
1109 if (g_log_file) {
1110 CHECK(g_log_file_name) << "Un-named |log_file| is not supported.";
1111 CloseLogFileUnlocked();
1112 }
Yuta Hijikata9b7279a2020-08-26 16:10:541113}
1114
1115ScopedLoggingSettings::~ScopedLoggingSettings() {
Wez244270362021-05-04 22:50:581116 // Re-initialize logging via the normal path. This will clean up old file
1117 // name and handle state, including re-initializing the VLOG internal state.
1118 CHECK(InitLogging({
1119 .logging_dest = logging_destination_,
1120 .log_file_path = log_file_name_ ? log_file_name_->data() : nullptr,
Georg Neisffe34f652021-12-27 21:42:361121#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581122 .log_format = log_format_
1123#endif
1124 })) << "~ScopedLoggingSettings() failed to restore settings.";
1125
1126 // Restore plain data settings.
1127 SetMinLogLevel(min_log_level_);
1128 SetLogItems(enable_process_id_, enable_thread_id_, enable_timestamp_,
1129 enable_tickcount_);
1130 SetLogPrefix(log_prefix_);
1131 SetLogMessageHandler(message_handler_);
Yuta Hijikata9b7279a2020-08-26 16:10:541132}
1133
Georg Neisffe34f652021-12-27 21:42:361134#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:541135void ScopedLoggingSettings::SetLogFormat(LogFormat log_format) const {
1136 g_log_format = log_format;
1137}
Yuta Hijikata000df18f2020-11-18 06:55:581138#endif // BUILDFLAG(IS_CHROMEOS_ASH)
Yuta Hijikata9b7279a2020-08-26 16:10:541139
[email protected]e36ddc82009-12-08 04:22:501140void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491141 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501142 const size_t message_len = strlen(message);
Benoit Lizeed678192022-01-20 10:14:541143 WriteToFd(STDERR_FILENO, message, message_len);
[email protected]e36ddc82009-12-08 04:22:501144
1145 if (message_len > 0 && message[message_len - 1] != '\n') {
Benoit Lizeed678192022-01-20 10:14:541146 int rv;
[email protected]e36ddc82009-12-08 04:22:501147 do {
1148 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1149 if (rv < 0) {
1150 // Give up, nothing we can do now.
1151 break;
1152 }
1153 } while (rv != 1);
1154 }
1155 }
1156
Lei Zhang93dd42572020-10-23 18:45:531157 if (level == LOGGING_FATAL)
Daniel Cheng4f5034d2022-03-04 18:34:311158 IMMEDIATE_CRASH();
[email protected]e36ddc82009-12-08 04:22:501159}
1160
[email protected]34a907732012-01-20 06:33:271161// This was defined at the beginning of this file.
1162#undef write
1163
Xiaohan Wang38e4ebb2022-01-19 06:57:431164#if BUILDFLAG(IS_WIN)
ananta61762fb2015-09-18 01:00:091165bool IsLoggingToFileEnabled() {
1166 return g_logging_destination & LOG_TO_FILE;
1167}
1168
Jan Wilken Dörrieb630aca2019-12-04 10:59:111169std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521170 if (g_log_file_name)
1171 return *g_log_file_name;
Jan Wilken Dörrieb630aca2019-12-04 10:59:111172 return std::wstring();
[email protected]f01b88a2013-02-27 22:04:001173}
1174#endif
1175
Xiyuan Xiaa0559da2022-05-05 19:42:451176#if !BUILDFLAG(USE_RUNTIME_VLOG)
1177int GetDisableAllVLogLevel() {
1178 return -1;
1179}
1180#endif // !BUILDFLAG(USE_RUNTIME_VLOG)
1181
[email protected]96fd0032009-04-24 00:13:081182} // namespace logging
initial.commitd7cae122008-07-26 21:49:381183
[email protected]81411c62014-07-08 23:03:061184std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391185 return out << (wstr ? base::WStringPiece(wstr) : base::WStringPiece());
1186}
1187
1188std::ostream& std::operator<<(std::ostream& out, const std::wstring& wstr) {
1189 return out << base::WStringPiece(wstr);
1190}
1191
1192std::ostream& std::operator<<(std::ostream& out, const char16_t* str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461193 return out << (str16 ? base::StringPiece16(str16) : base::StringPiece16());
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391194}
1195
1196std::ostream& std::operator<<(std::ostream& out, const std::u16string& str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461197 return out << base::StringPiece16(str16);
initial.commitd7cae122008-07-26 21:49:381198}