blob: aa45657ddd4af337446da3d41b235e21d7caf67c [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
Lei Zhangb7f26222021-06-15 18:45:4724#include "base/cxx17_backports.h"
Lukasz Anforowicz872567d2021-09-08 19:49:2225#include "base/debug/crash_logging.h"
Chris Hamilton306740d2019-04-25 18:48:3626#include "base/pending_task.h"
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:3927#include "base/strings/string_piece.h"
Chris Hamilton306740d2019-04-25 18:48:3628#include "base/task/common/task_annotator.h"
Eric Secklerf6c544f2020-06-02 10:49:2129#include "base/trace_event/base_tracing.h"
avi9b6f42932015-12-26 22:15:1430#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5031
Xiaohan Wang38e4ebb2022-01-19 06:57:4332#if BUILDFLAG(IS_WIN)
[email protected]e36ddc82009-12-08 04:22:5033#include <io.h>
alex-accc1bde62017-04-19 08:33:5534#include <windows.h>
[email protected]f6abeba2008-08-08 13:27:2835typedef HANDLE FileHandle;
[email protected]e36ddc82009-12-08 04:22:5036// Windows warns on using write(). It prefers _write().
37#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
38// Windows doesn't define STDERR_FILENO. Define it here.
39#define STDERR_FILENO 2
Eric Noyaufce100702017-10-16 09:46:3440
Xiaohan Wang38e4ebb2022-01-19 06:57:4341#elif BUILDFLAG(IS_APPLE)
Eric Noyaufce100702017-10-16 09:46:3442// In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
43// in favor of OS_LOG (Unified Logging).
44#include <AvailabilityMacros.h>
Xiaohan Wang38e4ebb2022-01-19 06:57:4345#if BUILDFLAG(IS_IOS)
Eric Noyaufce100702017-10-16 09:46:3446#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
47#define USE_ASL
48#endif
Xiaohan Wang38e4ebb2022-01-19 06:57:4349#else // BUILDFLAG(IS_IOS)
Eric Noyaufce100702017-10-16 09:46:3450#if !defined(MAC_OS_X_VERSION_10_12) || \
51 MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
52#define USE_ASL
53#endif
Xiaohan Wang38e4ebb2022-01-19 06:57:4354#endif // BUILDFLAG(IS_IOS)
Eric Noyaufce100702017-10-16 09:46:3455
56#if defined(USE_ASL)
mark4c7449c2015-11-10 19:53:4257#include <asl.h>
Eric Noyaufce100702017-10-16 09:46:3458#else
59#include <os/log.h>
60#endif
61
mark4c7449c2015-11-10 19:53:4262#include <CoreFoundation/CoreFoundation.h>
[email protected]f6abeba2008-08-08 13:27:2863#include <mach/mach.h>
64#include <mach/mach_time.h>
65#include <mach-o/dyld.h>
Eric Noyaufce100702017-10-16 09:46:3466
Xiaohan Wang38e4ebb2022-01-19 06:57:4367#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
68#if BUILDFLAG(IS_NACL)
thestig75f87352014-12-03 21:42:2769#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0870#endif
[email protected]052f1b52008-11-06 21:43:0771#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5972#endif
73
Xiaohan Wang38e4ebb2022-01-19 06:57:4374#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:0275#include "base/fuchsia/scoped_fx_logger.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3976#endif
77
Xiaohan Wang38e4ebb2022-01-19 06:57:4378#if BUILDFLAG(IS_ANDROID)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3979#include <android/log.h>
80#endif
81
Xiaohan Wang38e4ebb2022-01-19 06:57:4382#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:2083#include <errno.h>
mark4c7449c2015-11-10 19:53:4284#include <paths.h>
[email protected]f6abeba2008-08-08 13:27:2885#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0086#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2887#include <string.h>
mark4c7449c2015-11-10 19:53:4288#include <sys/stat.h>
Chris Findeisen2a373a2d2019-08-15 19:44:3089#include "base/process/process_handle.h"
[email protected]f6abeba2008-08-08 13:27:2890#define MAX_PATH PATH_MAX
91typedef FILE* FileHandle;
[email protected]f6abeba2008-08-08 13:27:2892#endif
93
[email protected]1f88b5162011-04-01 00:02:2994#include <algorithm>
95#include <cstring>
initial.commitd7cae122008-07-26 21:49:3896#include <ctime>
97#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2998#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0199#include <string>
alex-accc1bde62017-04-19 08:33:55100#include <utility>
[email protected]b16ef312008-08-19 18:36:23101
initial.commitd7cae122008-07-26 21:49:38102#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:55103#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:38104#include "base/command_line.h"
Brett Wilson1f07f20e2017-10-02 18:55:28105#include "base/containers/stack.h"
alex-accc1bde62017-04-19 08:33:55106#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:05107#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:50108#include "base/debug/debugger.h"
109#include "base/debug/stack_trace.h"
Alan Cutter9b0e1ab2019-03-21 04:22:16110#include "base/debug/task_trace.h"
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45111#include "base/no_destructor.h"
Sharon Yanga4b908de2019-05-07 22:19:03112#include "base/path_service.h"
[email protected]2025d002012-11-14 20:54:35113#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:00114#include "base/strings/string_piece.h"
Xianzhu Wangae8d96a32018-10-16 20:41:13115#include "base/strings/string_split.h"
[email protected]c914d8a2014-04-23 01:11:01116#include "base/strings/string_util.h"
117#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:42118#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:07119#include "base/strings/utf_string_conversions.h"
Benoit Lize5c98a832020-07-07 16:32:01120#include "base/synchronization/lock.h"
Yuta Hijikata9b7279a2020-08-26 16:10:54121#include "base/test/scoped_logging_settings.h"
[email protected]63e66802012-01-18 21:21:09122#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:36123#include "base/vlog.h"
Yuta Hijikata000df18f2020-11-18 06:55:58124#include "build/chromeos_buildflags.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39125
Xiaohan Wang38e4ebb2022-01-19 06:57:43126#if BUILDFLAG(IS_WIN)
Cliff Smolinskyc5c52102019-05-03 20:51:54127#include "base/win/win_util.h"
128#endif
129
Xiaohan Wang38e4ebb2022-01-19 06:57:43130#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
brettw6ee6fd62015-06-09 18:05:24131#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:04132#endif
[email protected]52a261f2009-03-03 15:01:12133
Yuta Hijikata000df18f2020-11-18 06:55:58134#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:53135#include "base/files/scoped_file.h"
136#endif
137
initial.commitd7cae122008-07-26 21:49:38138namespace logging {
139
[email protected]064aa162011-12-03 00:30:08140namespace {
141
thestig3e4787d2015-05-19 19:31:52142VlogInfo* g_vlog_info = nullptr;
143VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:38144
weza245bd072017-06-18 23:26:34145const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
Daniel Chengf45f47602022-02-28 22:38:32146static_assert(LOGGING_NUM_SEVERITIES == std::size(log_severity_names),
weza245bd072017-06-18 23:26:34147 "Incorrect number of log_severity_names");
initial.commitd7cae122008-07-26 21:49:38148
thestig75f87352014-12-03 21:42:27149const char* log_severity_name(int severity) {
Lei Zhang93dd42572020-10-23 18:45:53150 if (severity >= 0 && severity < LOGGING_NUM_SEVERITIES)
[email protected]80f360a2014-01-23 01:36:19151 return log_severity_names[severity];
152 return "UNKNOWN";
153}
154
thestig3e4787d2015-05-19 19:31:52155int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32156
Sharon Yang7cb919a2019-05-20 20:27:15157// Specifies the process' logging sink(s), represented as a combination of
158// LoggingDestination values joined by bitwise OR.
Peter Kasting40cfeae2021-06-14 12:21:48159uint32_t g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38160
Georg Neisffe34f652021-12-27 21:42:36161#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata1fc8f6342020-09-01 03:25:56162// Specifies the format of log header for chrome os.
163LogFormat g_log_format = LogFormat::LOG_FORMAT_SYSLOG;
Yuta Hijikata9b7279a2020-08-26 16:10:54164#endif
165
Xiaohan Wang38e4ebb2022-01-19 06:57:43166#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02167// Retains system logging structures.
168base::ScopedFxLogger& GetScopedFxLogger() {
169 static base::NoDestructor<base::ScopedFxLogger> logger;
170 return *logger;
171}
172#endif
173
Lei Zhang93dd42572020-10-23 18:45:53174// For LOGGING_ERROR and above, always print to stderr.
175const int kAlwaysPrintErrorLevel = LOGGING_ERROR;
[email protected]a33c9892008-08-25 20:10:31176
[email protected]614e9fa2008-08-11 22:52:59177// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38178// will be lazily initialized to the default value when it is
179// first needed.
jdoerrie5c4dc4e2019-02-01 18:02:33180using PathString = base::FilePath::StringType;
thestig3e4787d2015-05-19 19:31:52181PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38182
thestig3e4787d2015-05-19 19:31:52183// This file is lazily opened and the handle may be nullptr
184FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38185
thestig3e4787d2015-05-19 19:31:52186// What should be prepended to each message?
187bool g_log_process_id = false;
188bool g_log_thread_id = false;
189bool g_log_timestamp = true;
190bool g_log_tickcount = false;
James Cooka0536c32018-08-01 20:13:31191const char* g_log_prefix = nullptr;
initial.commitd7cae122008-07-26 21:49:38192
[email protected]81e0a852010-08-17 00:38:12193// Should we pop up fatal debug messages in a dialog?
194bool show_error_dialogs = false;
195
initial.commitd7cae122008-07-26 21:49:38196// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55197// the debug message dialog and process termination. Assert handlers are stored
198// in stack to allow overriding and restoring.
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45199base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() {
200 static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance;
201 return *instance;
202}
alex-accc1bde62017-04-19 08:33:55203
[email protected]2b07b8412009-11-25 15:26:34204// A log message handler that gets notified of every log message we process.
Wez244270362021-05-04 22:50:58205LogMessageHandlerFunction g_log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38206
avi9b6f42932015-12-26 22:15:14207uint64_t TickCount() {
Xiaohan Wang38e4ebb2022-01-19 06:57:43208#if BUILDFLAG(IS_WIN)
[email protected]f8588472008-11-05 23:17:24209 return GetTickCount();
Xiaohan Wang38e4ebb2022-01-19 06:57:43210#elif BUILDFLAG(IS_FUCHSIA)
Sharon Yang52c60992019-05-16 22:41:35211 return zx_clock_get_monotonic() /
Wezb0501302018-03-09 05:18:45212 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
Xiaohan Wang38e4ebb2022-01-19 06:57:43213#elif BUILDFLAG(IS_APPLE)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39214 return mach_absolute_time();
Xiaohan Wang38e4ebb2022-01-19 06:57:43215#elif BUILDFLAG(IS_NACL)
[email protected]19ea84ca2010-11-12 08:37:08216 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
217 // So we have to use clock() for now.
218 return clock();
Xiaohan Wang38e4ebb2022-01-19 06:57:43219#elif BUILDFLAG(IS_POSIX)
[email protected]052f1b52008-11-06 21:43:07220 struct timespec ts;
221 clock_gettime(CLOCK_MONOTONIC, &ts);
222
avi9b6f42932015-12-26 22:15:14223 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
224 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07225
226 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24227#endif
228}
229
[email protected]614e9fa2008-08-11 22:52:59230void DeleteFilePath(const PathString& log_name) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43231#if BUILDFLAG(IS_WIN)
Jan Wilken Dörrieb630aca2019-12-04 10:59:11232 DeleteFile(log_name.c_str());
Xiaohan Wang38e4ebb2022-01-19 06:57:43233#elif BUILDFLAG(IS_NACL)
[email protected]ac07ec52013-04-22 17:32:45234 // Do nothing; unlink() isn't supported on NaCl.
Xiaohan Wang38e4ebb2022-01-19 06:57:43235#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]614e9fa2008-08-11 22:52:59236 unlink(log_name.c_str());
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39237#else
238#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28239#endif
240}
initial.commitd7cae122008-07-26 21:49:38241
[email protected]5f95d532010-10-01 17:16:58242PathString GetDefaultLogFile() {
Xiaohan Wang38e4ebb2022-01-19 06:57:43243#if BUILDFLAG(IS_WIN)
[email protected]5b84fe32010-09-14 22:24:55244 // On Windows we use the same path as the exe.
Jan Wilken Dörrieb630aca2019-12-04 10:59:11245 wchar_t module_name[MAX_PATH];
246 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58247
scottmgfc5b7072015-01-27 21:46:28248 PathString log_name = module_name;
249 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58250 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28251 log_name.erase(last_backslash + 1);
Jan Wilken Dörrieb630aca2019-12-04 10:59:11252 log_name += FILE_PATH_LITERAL("debug.log");
scottmgfc5b7072015-01-27 21:46:28253 return log_name;
Xiaohan Wang38e4ebb2022-01-19 06:57:43254#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55255 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58256 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55257#endif
258}
259
ananta61762fb2015-09-18 01:00:09260// We don't need locks on Windows for atomically appending to files. The OS
261// provides this functionality.
Xiaohan Wang38e4ebb2022-01-19 06:57:43262#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]5b84fe32010-09-14 22:24:55263
Benoit Lize5c98a832020-07-07 16:32:01264base::Lock& GetLoggingLock() {
265 static base::NoDestructor<base::Lock> lock;
266 return *lock;
267}
[email protected]5b84fe32010-09-14 22:24:55268
Xiaohan Wang38e4ebb2022-01-19 06:57:43269#endif // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
ananta61762fb2015-09-18 01:00:09270
thestig3e4787d2015-05-19 19:31:52271// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38272// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52273// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38274bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52275 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38276 return true;
277
thestig3e4787d2015-05-19 19:31:52278 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59279 // Nobody has called InitLogging to specify a debug log file, so here we
280 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52281 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38282 }
283
Robbie McElrath8bf49842019-08-20 22:22:53284 if ((g_logging_destination & LOG_TO_FILE) == 0)
285 return true;
286
Xiaohan Wang38e4ebb2022-01-19 06:57:43287#if BUILDFLAG(IS_WIN)
Robbie McElrath8bf49842019-08-20 22:22:53288 // The FILE_APPEND_DATA access mask ensures that the file is atomically
289 // appended to across accesses from multiple threads.
290 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
291 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
Jan Wilken Dörrieb630aca2019-12-04 10:59:11292 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
Robbie McElrath8bf49842019-08-20 22:22:53293 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
294 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
295 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
296 // We are intentionally not using FilePath or FileUtil here to reduce the
297 // dependencies of the logging implementation. For e.g. FilePath and
298 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
299 // some consumers of base logging like chrome_elf, etc.
300 // Please don't change the code below to use FilePath.
301 // try the current directory
Jan Wilken Dörrieb630aca2019-12-04 10:59:11302 wchar_t system_buffer[MAX_PATH];
Robbie McElrath8bf49842019-08-20 22:22:53303 system_buffer[0] = 0;
Daniel Chengf45f47602022-02-28 22:38:32304 DWORD len = ::GetCurrentDirectory(std::size(system_buffer), system_buffer);
305 if (len == 0 || len > std::size(system_buffer))
Robbie McElrath8bf49842019-08-20 22:22:53306 return false;
307
308 *g_log_file_name = system_buffer;
309 // Append a trailing backslash if needed.
310 if (g_log_file_name->back() != L'\\')
Jan Wilken Dörrieb630aca2019-12-04 10:59:11311 *g_log_file_name += FILE_PATH_LITERAL("\\");
312 *g_log_file_name += FILE_PATH_LITERAL("debug.log");
Robbie McElrath8bf49842019-08-20 22:22:53313
Jan Wilken Dörrieb630aca2019-12-04 10:59:11314 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52315 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
316 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
317 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
Robbie McElrath8bf49842019-08-20 22:22:53318 g_log_file = nullptr;
[email protected]78c6dd62009-06-08 23:29:11319 return false;
Robbie McElrath8bf49842019-08-20 22:22:53320 }
321 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43322#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Robbie McElrath8bf49842019-08-20 22:22:53323 g_log_file = fopen(g_log_file_name->c_str(), "a");
324 if (g_log_file == nullptr)
325 return false;
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39326#else
327#error Unsupported platform
[email protected]f6abeba2008-08-08 13:27:28328#endif
[email protected]1d8c2702008-08-19 23:39:32329
initial.commitd7cae122008-07-26 21:49:38330 return true;
331}
332
[email protected]17dcf752013-07-15 21:47:09333void CloseFile(FileHandle log) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43334#if BUILDFLAG(IS_WIN)
[email protected]17dcf752013-07-15 21:47:09335 CloseHandle(log);
Xiaohan Wang38e4ebb2022-01-19 06:57:43336#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]17dcf752013-07-15 21:47:09337 fclose(log);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39338#else
339#error Unsupported platform
[email protected]17dcf752013-07-15 21:47:09340#endif
341}
342
343void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52344 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09345 return;
346
thestig3e4787d2015-05-19 19:31:52347 CloseFile(g_log_file);
348 g_log_file = nullptr;
Robbie McElrath8bf49842019-08-20 22:22:53349
350 // If we initialized logging via an externally-provided file descriptor, we
351 // won't have a log path set and shouldn't try to reopen the log file.
352 if (!g_log_file_name)
353 g_logging_destination &= ~LOG_TO_FILE;
[email protected]17dcf752013-07-15 21:47:09354}
355
Xiaohan Wang38e4ebb2022-01-19 06:57:43356#if BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02357inline FuchsiaLogSeverity LogSeverityToFuchsiaLogSeverity(
358 LogSeverity severity) {
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38359 switch (severity) {
360 case LOGGING_INFO:
Wez45e3ffe2021-09-24 02:10:02361 return FUCHSIA_LOG_INFO;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38362 case LOGGING_WARNING:
Wez45e3ffe2021-09-24 02:10:02363 return FUCHSIA_LOG_WARNING;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38364 case LOGGING_ERROR:
Wez45e3ffe2021-09-24 02:10:02365 return FUCHSIA_LOG_ERROR;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38366 case LOGGING_FATAL:
367 // Don't use FX_LOG_FATAL, otherwise fx_logger_log() will abort().
Wez45e3ffe2021-09-24 02:10:02368 return FUCHSIA_LOG_ERROR;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38369 }
370 if (severity > -3) {
371 // LOGGING_VERBOSE levels 1 and 2.
Wez45e3ffe2021-09-24 02:10:02372 return FUCHSIA_LOG_DEBUG;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38373 }
374 // LOGGING_VERBOSE levels 3 and higher, or incorrect levels.
Wez45e3ffe2021-09-24 02:10:02375 return FUCHSIA_LOG_TRACE;
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38376}
Fabrice de Gans-Riberifb94dff82021-04-15 21:09:38377#endif // defined (OS_FUCHSIA)
378
Benoit Lizeed678192022-01-20 10:14:54379void WriteToFd(int fd, const char* data, size_t length) {
380 size_t bytes_written = 0;
381 int rv;
382 while (bytes_written < length) {
383 rv = HANDLE_EINTR(write(fd, data + bytes_written, length - bytes_written));
384 if (rv < 0) {
385 // Give up, nothing we can do now.
386 break;
387 }
388 bytes_written += rv;
389 }
390}
391
[email protected]064aa162011-12-03 00:30:08392} // namespace
393
Tomas Popelaafffa972018-11-13 20:42:05394#if defined(DCHECK_IS_CONFIGURABLE)
Lei Zhang93dd42572020-10-23 18:45:53395// In DCHECK-enabled Chrome builds, allow the meaning of LOGGING_DCHECK to be
Wez289477f2017-08-24 20:51:30396// determined at run-time. We default it to INFO, to avoid it triggering
397// crashes before the run-time has explicitly chosen the behaviour.
Lei Zhang93dd42572020-10-23 18:45:53398BASE_EXPORT logging::LogSeverity LOGGING_DCHECK = LOGGING_INFO;
Tomas Popelaafffa972018-11-13 20:42:05399#endif // defined(DCHECK_IS_CONFIGURABLE)
Wez289477f2017-08-24 20:51:30400
scottmg3c957a52016-12-10 20:57:59401// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
402// an object of the correct type on the LHS of the unused part of the ternary
403// operator.
404std::ostream* g_swallow_stream;
405
[email protected]5e3f7c22013-06-21 21:15:33406bool BaseInitLoggingImpl(const LoggingSettings& settings) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43407#if BUILDFLAG(IS_NACL)
Sharon Yang7cb919a2019-05-20 20:27:15408 // Can log only to the system debug log and stderr.
409 CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR),
410 0u);
[email protected]ac07ec52013-04-22 17:32:45411#endif
Robbie McElrath8bf49842019-08-20 22:22:53412
Georg Neisffe34f652021-12-27 21:42:36413#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata8a93e522020-09-25 08:59:57414 g_log_format = settings.log_format;
415#endif
416
Joshua Peraza236556ce2020-10-22 23:23:31417 if (base::CommandLine::InitializedForCurrentProcess()) {
418 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
419 // Don't bother initializing |g_vlog_info| unless we use one of the
420 // vlog switches.
421 if (command_line->HasSwitch(switches::kV) ||
422 command_line->HasSwitch(switches::kVModule)) {
423 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
424 // by another thread. Don't delete the old VLogInfo, just create a second
425 // one. We keep track of both to avoid memory leak warnings.
426 CHECK(!g_vlog_info_prev);
427 g_vlog_info_prev = g_vlog_info;
[email protected]064aa162011-12-03 00:30:08428
Joshua Peraza236556ce2020-10-22 23:23:31429 g_vlog_info =
430 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
431 command_line->GetSwitchValueASCII(switches::kVModule),
432 &g_min_log_level);
433 }
[email protected]99b7c57f2010-09-29 19:26:36434 }
435
thestig3e4787d2015-05-19 19:31:52436 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38437
Xiaohan Wang38e4ebb2022-01-19 06:57:43438#if BUILDFLAG(IS_FUCHSIA)
Wez224c0bf62019-05-24 19:26:13439 if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) {
Wez5d4a666c2021-10-04 16:41:36440 GetScopedFxLogger() = base::ScopedFxLogger::CreateForProcess();
Wez224c0bf62019-05-24 19:26:13441 }
442#endif
443
[email protected]5e3f7c22013-06-21 21:15:33444 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52445 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21446 return true;
initial.commitd7cae122008-07-26 21:49:38447
Xiaohan Wang38e4ebb2022-01-19 06:57:43448#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:01449 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09450#endif
[email protected]17dcf752013-07-15 21:47:09451
452 // Calling InitLogging twice or after some log call has already opened the
453 // default log file will re-initialize to the new options.
454 CloseLogFileUnlocked();
455
Yuta Hijikata000df18f2020-11-18 06:55:58456#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:53457 if (settings.log_file) {
458 DCHECK(!settings.log_file_path);
459 g_log_file = settings.log_file;
460 return true;
461 }
462#endif
Lei Zhang93dd42572020-10-23 18:45:53463
Xiaohan Wang5411974b2020-10-10 19:36:12464 DCHECK(settings.log_file_path) << "LOG_TO_FILE set but no log_file_path!";
Robbie McElrath8bf49842019-08-20 22:22:53465
thestig3e4787d2015-05-19 19:31:52466 if (!g_log_file_name)
467 g_log_file_name = new PathString();
Robbie McElrath8bf49842019-08-20 22:22:53468 *g_log_file_name = settings.log_file_path;
[email protected]5e3f7c22013-06-21 21:15:33469 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52470 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38471
[email protected]c7d5da992010-10-28 00:20:21472 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38473}
474
475void SetMinLogLevel(int level) {
Lei Zhang93dd42572020-10-23 18:45:53476 g_min_log_level = std::min(LOGGING_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38477}
478
479int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52480 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38481}
482
skobesc78c0ad72015-12-07 20:21:23483bool ShouldCreateLogMessage(int severity) {
484 if (severity < g_min_log_level)
485 return false;
486
Wez6c8acb82019-07-18 00:32:59487 // Return true here unless we know ~LogMessage won't do anything.
Wez244270362021-05-04 22:50:58488 return g_logging_destination != LOG_NONE || g_log_message_handler ||
skobesc78c0ad72015-12-07 20:21:23489 severity >= kAlwaysPrintErrorLevel;
490}
491
Wez6c8acb82019-07-18 00:32:59492// Returns true when LOG_TO_STDERR flag is set, or |severity| is high.
493// If |severity| is high then true will be returned when no log destinations are
494// set, or only LOG_TO_FILE is set, since that is useful for local development
495// and debugging.
496bool ShouldLogToStderr(int severity) {
497 if (g_logging_destination & LOG_TO_STDERR)
498 return true;
Benjamin Lermand823d682021-10-25 11:31:01499#if !BUILDFLAG(IS_FUCHSIA)
500 // High-severity logs go to stderr by default, except on Fuchsia.
Wez6c8acb82019-07-18 00:32:59501 if (severity >= kAlwaysPrintErrorLevel)
502 return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
Benjamin Lermand823d682021-10-25 11:31:01503#endif
Wez6c8acb82019-07-18 00:32:59504 return false;
505}
506
[email protected]162ac0f2010-11-04 15:50:49507int GetVlogVerbosity() {
508 return std::max(-1, LOG_INFO - GetMinLogLevel());
509}
510
[email protected]99b7c57f2010-09-29 19:26:36511int GetVlogLevelHelper(const char* file, size_t N) {
512 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52513 // Note: |g_vlog_info| may change on a different thread during startup
514 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08515 VlogInfo* vlog_info = g_vlog_info;
516 return vlog_info ?
517 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49518 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36519}
520
initial.commitd7cae122008-07-26 21:49:38521void SetLogItems(bool enable_process_id, bool enable_thread_id,
522 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52523 g_log_process_id = enable_process_id;
524 g_log_thread_id = enable_thread_id;
525 g_log_timestamp = enable_timestamp;
526 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38527}
528
James Cooka0536c32018-08-01 20:13:31529void SetLogPrefix(const char* prefix) {
530 DCHECK(!prefix ||
531 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
532 g_log_prefix = prefix;
533}
534
[email protected]81e0a852010-08-17 00:38:12535void SetShowErrorDialogs(bool enable_dialogs) {
536 show_error_dialogs = enable_dialogs;
537}
538
alex-accc1bde62017-04-19 08:33:55539ScopedLogAssertHandler::ScopedLogAssertHandler(
540 LogAssertHandlerFunction handler) {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45541 GetLogAssertHandlerStack().push(std::move(handler));
alex-accc1bde62017-04-19 08:33:55542}
543
544ScopedLogAssertHandler::~ScopedLogAssertHandler() {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45545 GetLogAssertHandlerStack().pop();
initial.commitd7cae122008-07-26 21:49:38546}
547
[email protected]2b07b8412009-11-25 15:26:34548void SetLogMessageHandler(LogMessageHandlerFunction handler) {
Wez244270362021-05-04 22:50:58549 g_log_message_handler = handler;
[email protected]2b07b8412009-11-25 15:26:34550}
551
[email protected]64e5cc02010-11-03 19:20:27552LogMessageHandlerFunction GetLogMessageHandler() {
Wez244270362021-05-04 22:50:58553 return g_log_message_handler;
[email protected]64e5cc02010-11-03 19:20:27554}
555
[email protected]f2c05492014-06-17 12:04:23556#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22557// Displays a message box to the user with the error message in it.
558// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25559// This is for developers only; we don't use this in circumstances
560// (like release builds) where users could see it, since users don't
561// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22562void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38563 if (str.empty())
564 return;
565
[email protected]81e0a852010-08-17 00:38:12566 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44567 return;
568
Xiaohan Wang38e4ebb2022-01-19 06:57:43569#if BUILDFLAG(IS_WIN)
[email protected]561513f2010-12-16 23:29:25570 // We intentionally don't implement a dialog on other platforms.
571 // You can just look at stderr.
Cliff Smolinskyc5c52102019-05-03 20:51:54572 if (base::win::IsUser32AndGdi32Available()) {
573 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
574 MB_OK | MB_ICONHAND | MB_TOPMOST);
575 } else {
576 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
577 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43578#endif // BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38579}
[email protected]f2c05492014-06-17 12:04:23580#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38581
[email protected]eae9c062011-01-11 00:50:59582LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
583 : severity_(severity), file_(file), line_(line) {
584 Init(file, line);
585}
586
tnagel4a045d3f2015-07-12 14:19:28587LogMessage::LogMessage(const char* file, int line, const char* condition)
Lei Zhang93dd42572020-10-23 18:45:53588 : severity_(LOGGING_FATAL), file_(file), line_(line) {
tnagel4a045d3f2015-07-12 14:19:28589 Init(file, line);
590 stream_ << "Check failed: " << condition << ". ";
591}
592
initial.commitd7cae122008-07-26 21:49:38593LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55594 size_t stack_start = stream_.tellp();
Xiaohan Wang38e4ebb2022-01-19 06:57:43595#if !defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_NACL) && !defined(__UCLIBC__) && \
596 !BUILDFLAG(IS_AIX)
Lei Zhang93dd42572020-10-23 18:45:53597 if (severity_ == LOGGING_FATAL && !base::debug::BeingDebugged()) {
brucedawson7c559eb2015-09-05 00:34:42598 // Include a stack trace on a fatal, unless a debugger is attached.
Alan Cutter9b0e1ab2019-03-21 04:22:16599 base::debug::StackTrace stack_trace;
[email protected]d1ccc35a2010-03-24 05:03:24600 stream_ << std::endl; // Newline to separate from log message.
Alan Cutter9b0e1ab2019-03-21 04:22:16601 stack_trace.OutputToStream(&stream_);
602 base::debug::TaskTrace task_trace;
603 if (!task_trace.empty())
604 task_trace.OutputToStream(&stream_);
Chris Hamilton306740d2019-04-25 18:48:36605
Chris Hamilton888085312019-05-30 00:53:30606 // Include the IPC context, if any.
607 // TODO(chrisha): Integrate with symbolization once those tools exist!
Chris Hamilton306740d2019-04-25 18:48:36608 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
Chris Hamilton888085312019-05-30 00:53:30609 if (task && task->ipc_hash) {
610 stream_ << "IPC message handler context: "
611 << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
Chris Hamilton306740d2019-04-25 18:48:36612 }
Lukasz Anforowicz872567d2021-09-08 19:49:22613
614 // Include the crash keys, if any.
615 base::debug::OutputCrashKeysToStream(stream_);
[email protected]d1ccc35a2010-03-24 05:03:24616 }
[email protected]1d8c2702008-08-19 23:39:32617#endif
[email protected]d1ccc35a2010-03-24 05:03:24618 stream_ << std::endl;
619 std::string str_newline(stream_.str());
Nicolò Mazzucato6c278d9b2019-08-02 16:25:44620 TRACE_LOG_MESSAGE(
621 file_, base::StringPiece(str_newline).substr(message_start_), line_);
[email protected]d1ccc35a2010-03-24 05:03:24622
[email protected]2b07b8412009-11-25 15:26:34623 // Give any log message handler first dibs on the message.
Wez244270362021-05-04 22:50:58624 if (g_log_message_handler &&
625 g_log_message_handler(severity_, file_, line_, message_start_,
626 str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49627 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34628 return;
[email protected]162ac0f2010-11-04 15:50:49629 }
initial.commitd7cae122008-07-26 21:49:38630
thestig3e4787d2015-05-19 19:31:52631 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43632#if BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38633 OutputDebugStringA(str_newline.c_str());
Xiaohan Wang38e4ebb2022-01-19 06:57:43634#elif BUILDFLAG(IS_APPLE)
mark4c7449c2015-11-10 19:53:42635 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Eric Noyaufce100702017-10-16 09:46:34636 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
637 // its successor OS_LOG. If there's something weird about stderr, assume
638 // that log messages are going nowhere and log via ASL/OS_LOG too.
639 // Messages logged via ASL/OS_LOG show up in Console.app.
mark4c7449c2015-11-10 19:53:42640 //
641 // Programs started by launchd, as UI applications normally are, have had
642 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
643 // a pipe to launchd, which logged what it received (see log_redirect_fd in
644 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
645 //
646 // Another alternative would be to determine whether stderr is a pipe to
647 // launchd and avoid logging via ASL only in that case. See 10.7.5
648 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Eric Noyaufce100702017-10-16 09:46:34649 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
650 // to the system log at all.
mark4c7449c2015-11-10 19:53:42651 //
652 // Note that the ASL client by default discards messages whose levels are
653 // below ASL_LEVEL_NOTICE. It's possible to change that with
654 // asl_set_filter(), but this is pointless because syslogd normally applies
655 // the same filter.
Eric Noyaufce100702017-10-16 09:46:34656 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42657 struct stat stderr_stat;
658 if (fstat(fileno(stderr), &stderr_stat) == -1) {
659 return true;
660 }
661 if (!S_ISCHR(stderr_stat.st_mode)) {
662 return false;
663 }
664
665 struct stat dev_null_stat;
666 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
667 return true;
668 }
669
670 return !S_ISCHR(dev_null_stat.st_mode) ||
671 stderr_stat.st_rdev == dev_null_stat.st_rdev;
672 }();
673
Eric Noyaufce100702017-10-16 09:46:34674 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42675 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
676 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42677 CFBundleRef main_bundle = CFBundleGetMainBundle();
678 CFStringRef main_bundle_id_cf =
679 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34680 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42681 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34682 : std::string("");
683#if defined(USE_ASL)
684 // The facility is set to the main bundle ID if available. Otherwise,
685 // "com.apple.console" is used.
686 const class ASLClient {
mark4c7449c2015-11-10 19:53:42687 public:
Bruce Dawson4c6f8e12017-11-16 04:35:59688 explicit ASLClient(const std::string& facility)
689 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
David Bienvenub4b441e2020-09-23 05:49:57690 ASLClient(const ASLClient&) = delete;
691 ASLClient& operator=(const ASLClient&) = delete;
mark4c7449c2015-11-10 19:53:42692 ~ASLClient() { asl_close(client_); }
693
694 aslclient get() const { return client_; }
695
696 private:
697 aslclient client_;
Eric Noyaufce100702017-10-16 09:46:34698 } asl_client(main_bundle_id.empty() ? main_bundle_id
699 : "com.apple.console");
mark4c7449c2015-11-10 19:53:42700
Eric Noyaufce100702017-10-16 09:46:34701 const class ASLMessage {
mark4c7449c2015-11-10 19:53:42702 public:
703 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
David Bienvenub4b441e2020-09-23 05:49:57704 ASLMessage(const ASLMessage&) = delete;
705 ASLMessage& operator=(const ASLMessage&) = delete;
mark4c7449c2015-11-10 19:53:42706 ~ASLMessage() { asl_free(message_); }
707
708 aslmsg get() const { return message_; }
709
710 private:
711 aslmsg message_;
mark4c7449c2015-11-10 19:53:42712 } asl_message;
713
714 // By default, messages are only readable by the admin group. Explicitly
715 // make them readable by the user generating the messages.
716 char euid_string[12];
Daniel Chengf45f47602022-02-28 22:38:32717 snprintf(euid_string, std::size(euid_string), "%d", geteuid());
mark4c7449c2015-11-10 19:53:42718 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
719
720 // Map Chrome log severities to ASL log levels.
721 const char* const asl_level_string = [](LogSeverity severity) {
722 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
723 // non-obvious two-step macro trick achieves what's needed.
724 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
725#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
726#define ASL_LEVEL_STR_X(level) #level
727 switch (severity) {
Lei Zhang93dd42572020-10-23 18:45:53728 case LOGGING_INFO:
mark4c7449c2015-11-10 19:53:42729 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
Lei Zhang93dd42572020-10-23 18:45:53730 case LOGGING_WARNING:
mark4c7449c2015-11-10 19:53:42731 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
Lei Zhang93dd42572020-10-23 18:45:53732 case LOGGING_ERROR:
mark4c7449c2015-11-10 19:53:42733 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
Lei Zhang93dd42572020-10-23 18:45:53734 case LOGGING_FATAL:
mark4c7449c2015-11-10 19:53:42735 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
736 default:
737 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
738 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
739 }
740#undef ASL_LEVEL_STR
741#undef ASL_LEVEL_STR_X
742 }(severity_);
743 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
744
745 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
746
747 asl_send(asl_client.get(), asl_message.get());
Eric Noyaufce100702017-10-16 09:46:34748#else // !defined(USE_ASL)
749 const class OSLog {
750 public:
751 explicit OSLog(const char* subsystem)
752 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
753 : OS_LOG_DEFAULT) {}
David Bienvenub4b441e2020-09-23 05:49:57754 OSLog(const OSLog&) = delete;
755 OSLog& operator=(const OSLog&) = delete;
Eric Noyaufce100702017-10-16 09:46:34756 ~OSLog() {
757 if (os_log_ != OS_LOG_DEFAULT) {
758 os_release(os_log_);
759 }
760 }
761 os_log_t get() const { return os_log_; }
762
763 private:
764 os_log_t os_log_;
Eric Noyaufce100702017-10-16 09:46:34765 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
766 const os_log_type_t os_log_type = [](LogSeverity severity) {
767 switch (severity) {
Lei Zhang93dd42572020-10-23 18:45:53768 case LOGGING_INFO:
Eric Noyaufce100702017-10-16 09:46:34769 return OS_LOG_TYPE_INFO;
Lei Zhang93dd42572020-10-23 18:45:53770 case LOGGING_WARNING:
Eric Noyaufce100702017-10-16 09:46:34771 return OS_LOG_TYPE_DEFAULT;
Lei Zhang93dd42572020-10-23 18:45:53772 case LOGGING_ERROR:
Eric Noyaufce100702017-10-16 09:46:34773 return OS_LOG_TYPE_ERROR;
Lei Zhang93dd42572020-10-23 18:45:53774 case LOGGING_FATAL:
Eric Noyaufce100702017-10-16 09:46:34775 return OS_LOG_TYPE_FAULT;
776 default:
777 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
778 }
779 }(severity_);
780 os_log_with_type(log.get(), os_log_type, "%{public}s",
781 str_newline.c_str());
782#endif // defined(USE_ASL)
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
[email protected]82d89ab2014-02-28 18:25:34907 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52908#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
909 IMMEDIATE_CRASH();
910#else
[email protected]82d89ab2014-02-28 18:25:34911 base::debug::BreakDebugger();
Torne (Richard Coles)54b86796a62018-07-24 14:59:52912#endif
initial.commitd7cae122008-07-26 21:49:38913 }
914 }
915}
916
[email protected]eae9c062011-01-11 00:50:59917// writes the common header info to the stream
918void LogMessage::Init(const char* file, int line) {
919 base::StringPiece filename(file);
920 size_t last_slash_pos = filename.find_last_of("\\/");
921 if (last_slash_pos != base::StringPiece::npos)
922 filename.remove_prefix(last_slash_pos + 1);
923
Georg Neisffe34f652021-12-27 21:42:36924#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54925 if (g_log_format == LogFormat::LOG_FORMAT_SYSLOG) {
926 InitWithSyslogPrefix(
927 filename, line, TickCount(), log_severity_name(severity_), g_log_prefix,
928 g_log_process_id, g_log_thread_id, g_log_timestamp, g_log_tickcount);
929 } else
Georg Neisffe34f652021-12-27 21:42:36930#endif // BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54931 {
932 // TODO(darin): It might be nice if the columns were fixed width.
933 stream_ << '[';
934 if (g_log_prefix)
935 stream_ << g_log_prefix << ':';
936 if (g_log_process_id)
937 stream_ << base::GetUniqueIdForProcess() << ':';
938 if (g_log_thread_id)
939 stream_ << base::PlatformThread::CurrentId() << ':';
940 if (g_log_timestamp) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43941#if BUILDFLAG(IS_WIN)
Yuta Hijikata9b7279a2020-08-26 16:10:54942 SYSTEMTIME local_time;
943 GetLocalTime(&local_time);
944 stream_ << std::setfill('0')
945 << std::setw(2) << local_time.wMonth
946 << std::setw(2) << local_time.wDay
947 << '/'
948 << std::setw(2) << local_time.wHour
949 << std::setw(2) << local_time.wMinute
950 << std::setw(2) << local_time.wSecond
951 << '.'
952 << std::setw(3) << local_time.wMilliseconds
953 << ':';
Xiaohan Wang38e4ebb2022-01-19 06:57:43954#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Yuta Hijikata9b7279a2020-08-26 16:10:54955 timeval tv;
956 gettimeofday(&tv, nullptr);
957 time_t t = tv.tv_sec;
958 struct tm local_time;
959 localtime_r(&t, &local_time);
960 struct tm* tm_time = &local_time;
961 stream_ << std::setfill('0')
962 << std::setw(2) << 1 + tm_time->tm_mon
963 << std::setw(2) << tm_time->tm_mday
964 << '/'
965 << std::setw(2) << tm_time->tm_hour
966 << std::setw(2) << tm_time->tm_min
967 << std::setw(2) << tm_time->tm_sec
968 << '.'
969 << std::setw(6) << tv.tv_usec
970 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39971#else
972#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:34973#endif
Yuta Hijikata9b7279a2020-08-26 16:10:54974 }
975 if (g_log_tickcount)
976 stream_ << TickCount() << ':';
977 if (severity_ >= 0) {
978 stream_ << log_severity_name(severity_);
979 } else {
980 stream_ << "VERBOSE" << -severity_;
981 }
982 stream_ << ":" << filename << "(" << line << ")] ";
[email protected]eae9c062011-01-11 00:50:59983 }
pkasting9cf9b94a2014-10-01 22:18:43984 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59985}
986
Xiaohan Wang38e4ebb2022-01-19 06:57:43987#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:20988// This has already been defined in the header, but defining it again as DWORD
989// ensures that the type used in the header is equivalent to DWORD. If not,
990// the redefinition is a compile error.
991typedef DWORD SystemErrorCode;
992#endif
993
994SystemErrorCode GetLastSystemErrorCode() {
Xiaohan Wang38e4ebb2022-01-19 06:57:43995#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:20996 return ::GetLastError();
Xiaohan Wang38e4ebb2022-01-19 06:57:43997#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:20998 return errno;
[email protected]d8617a62009-10-09 23:52:20999#endif
1000}
1001
[email protected]c914d8a2014-04-23 01:11:011002BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Xiaohan Wang38e4ebb2022-01-19 06:57:431003#if BUILDFLAG(IS_WIN)
thestig75f87352014-12-03 21:42:271004 const int kErrorMessageBufferSize = 256;
1005 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:011006 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:521007 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Daniel Chengf45f47602022-02-28 22:38:321008 std::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:011009 if (len) {
1010 // Messages returned by system end with line breaks.
1011 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:451012 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:011013 }
Bruce Dawson19175842017-08-02 17:00:451014 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:011015 GetLastError(), error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431016#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:141017 return base::safe_strerror(error_code) +
1018 base::StringPrintf(" (%d)", error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431019#endif // BUILDFLAG(IS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391020}
[email protected]d8617a62009-10-09 23:52:201021
Xiaohan Wang38e4ebb2022-01-19 06:57:431022#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201023Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1024 int line,
1025 LogSeverity severity,
1026 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001027 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201028
1029Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011030 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:061031 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1032 // field) and use Alias in hopes that it makes it into crash dumps.
1033 DWORD last_error = err_;
1034 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201035}
Xiaohan Wang38e4ebb2022-01-19 06:57:431036#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201037ErrnoLogMessage::ErrnoLogMessage(const char* file,
1038 int line,
1039 LogSeverity severity,
1040 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001041 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201042
1043ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011044 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141045 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1046 // field) and use Alias in hopes that it makes it into crash dumps.
1047 int last_error = err_;
1048 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201049}
Xiaohan Wang38e4ebb2022-01-19 06:57:431050#endif // BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201051
initial.commitd7cae122008-07-26 21:49:381052void CloseLogFile() {
Xiaohan Wang38e4ebb2022-01-19 06:57:431053#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:011054 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:091055#endif
[email protected]17dcf752013-07-15 21:47:091056 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381057}
1058
Yuta Hijikata000df18f2020-11-18 06:55:581059#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:531060FILE* DuplicateLogFILE() {
1061 if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle())
1062 return nullptr;
1063
1064 int log_fd = fileno(g_log_file);
1065 if (log_fd == -1)
1066 return nullptr;
1067 base::ScopedFD dup_fd(dup(log_fd));
1068 if (dup_fd == -1)
1069 return nullptr;
1070 FILE* duplicate = fdopen(dup_fd.get(), "a");
1071 if (!duplicate)
1072 return nullptr;
Avi Drissman933398e2022-01-22 00:55:421073 std::ignore = dup_fd.release();
Robbie McElrath8bf49842019-08-20 22:22:531074 return duplicate;
1075}
1076#endif
1077
Yuta Hijikata9b7279a2020-08-26 16:10:541078// Used for testing. Declared in test/scoped_logging_settings.h.
1079ScopedLoggingSettings::ScopedLoggingSettings()
Wez244270362021-05-04 22:50:581080 : min_log_level_(g_min_log_level),
1081 logging_destination_(g_logging_destination),
Georg Neisffe34f652021-12-27 21:42:361082#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581083 log_format_(g_log_format),
1084#endif // BUILDFLAG(IS_CHROMEOS_ASH)
1085 enable_process_id_(g_log_process_id),
Yuta Hijikata9b7279a2020-08-26 16:10:541086 enable_thread_id_(g_log_thread_id),
1087 enable_timestamp_(g_log_timestamp),
1088 enable_tickcount_(g_log_tickcount),
Wez244270362021-05-04 22:50:581089 log_prefix_(g_log_prefix),
1090 message_handler_(g_log_message_handler) {
1091 if (g_log_file_name)
1092 log_file_name_ = std::make_unique<PathString>(*g_log_file_name);
1093 // Duplicating |g_log_file| is complex & unnecessary for this test helpers'
1094 // use-cases, and so long as |g_log_file_name| is set, it will be re-opened
1095 // automatically anyway, when required, so just close the existing one.
1096 if (g_log_file) {
1097 CHECK(g_log_file_name) << "Un-named |log_file| is not supported.";
1098 CloseLogFileUnlocked();
1099 }
Yuta Hijikata9b7279a2020-08-26 16:10:541100}
1101
1102ScopedLoggingSettings::~ScopedLoggingSettings() {
Wez244270362021-05-04 22:50:581103 // Re-initialize logging via the normal path. This will clean up old file
1104 // name and handle state, including re-initializing the VLOG internal state.
1105 CHECK(InitLogging({
1106 .logging_dest = logging_destination_,
1107 .log_file_path = log_file_name_ ? log_file_name_->data() : nullptr,
Georg Neisffe34f652021-12-27 21:42:361108#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581109 .log_format = log_format_
1110#endif
1111 })) << "~ScopedLoggingSettings() failed to restore settings.";
1112
1113 // Restore plain data settings.
1114 SetMinLogLevel(min_log_level_);
1115 SetLogItems(enable_process_id_, enable_thread_id_, enable_timestamp_,
1116 enable_tickcount_);
1117 SetLogPrefix(log_prefix_);
1118 SetLogMessageHandler(message_handler_);
Yuta Hijikata9b7279a2020-08-26 16:10:541119}
1120
Georg Neisffe34f652021-12-27 21:42:361121#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:541122void ScopedLoggingSettings::SetLogFormat(LogFormat log_format) const {
1123 g_log_format = log_format;
1124}
Yuta Hijikata000df18f2020-11-18 06:55:581125#endif // BUILDFLAG(IS_CHROMEOS_ASH)
Yuta Hijikata9b7279a2020-08-26 16:10:541126
[email protected]e36ddc82009-12-08 04:22:501127void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491128 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501129 const size_t message_len = strlen(message);
Benoit Lizeed678192022-01-20 10:14:541130 WriteToFd(STDERR_FILENO, message, message_len);
[email protected]e36ddc82009-12-08 04:22:501131
1132 if (message_len > 0 && message[message_len - 1] != '\n') {
Benoit Lizeed678192022-01-20 10:14:541133 int rv;
[email protected]e36ddc82009-12-08 04:22:501134 do {
1135 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1136 if (rv < 0) {
1137 // Give up, nothing we can do now.
1138 break;
1139 }
1140 } while (rv != 1);
1141 }
1142 }
1143
Lei Zhang93dd42572020-10-23 18:45:531144 if (level == LOGGING_FATAL)
Benoit Lize33a16522021-09-13 20:15:141145 base::debug::BreakDebuggerAsyncSafe();
[email protected]e36ddc82009-12-08 04:22:501146}
1147
[email protected]34a907732012-01-20 06:33:271148// This was defined at the beginning of this file.
1149#undef write
1150
Xiaohan Wang38e4ebb2022-01-19 06:57:431151#if BUILDFLAG(IS_WIN)
ananta61762fb2015-09-18 01:00:091152bool IsLoggingToFileEnabled() {
1153 return g_logging_destination & LOG_TO_FILE;
1154}
1155
Jan Wilken Dörrieb630aca2019-12-04 10:59:111156std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521157 if (g_log_file_name)
1158 return *g_log_file_name;
Jan Wilken Dörrieb630aca2019-12-04 10:59:111159 return std::wstring();
[email protected]f01b88a2013-02-27 22:04:001160}
1161#endif
1162
[email protected]96fd0032009-04-24 00:13:081163} // namespace logging
initial.commitd7cae122008-07-26 21:49:381164
[email protected]81411c62014-07-08 23:03:061165std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391166 return out << (wstr ? base::WStringPiece(wstr) : base::WStringPiece());
1167}
1168
1169std::ostream& std::operator<<(std::ostream& out, const std::wstring& wstr) {
1170 return out << base::WStringPiece(wstr);
1171}
1172
1173std::ostream& std::operator<<(std::ostream& out, const char16_t* str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461174 return out << (str16 ? base::StringPiece16(str16) : base::StringPiece16());
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391175}
1176
1177std::ostream& std::operator<<(std::ostream& out, const std::u16string& str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461178 return out << base::StringPiece16(str16);
initial.commitd7cae122008-07-26 21:49:381179}