blob: 26f8e043268a6a7c74cb023e898c6be6244d0149 [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;
Benjamin Lermand823d682021-10-25 11:31:01504#if !BUILDFLAG(IS_FUCHSIA)
505 // High-severity logs go to stderr by default, except on Fuchsia.
Wez6c8acb82019-07-18 00:32:59506 if (severity >= kAlwaysPrintErrorLevel)
507 return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
Benjamin Lermand823d682021-10-25 11:31:01508#endif
Wez6c8acb82019-07-18 00:32:59509 return false;
510}
511
[email protected]162ac0f2010-11-04 15:50:49512int GetVlogVerbosity() {
513 return std::max(-1, LOG_INFO - GetMinLogLevel());
514}
515
[email protected]99b7c57f2010-09-29 19:26:36516int GetVlogLevelHelper(const char* file, size_t N) {
517 DCHECK_GT(N, 0U);
Xiyuan Xiaa0559da2022-05-05 19:42:45518
519#if BUILDFLAG(USE_RUNTIME_VLOG)
thestig3e4787d2015-05-19 19:31:52520 // Note: |g_vlog_info| may change on a different thread during startup
521 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08522 VlogInfo* vlog_info = g_vlog_info;
523 return vlog_info ?
524 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49525 GetVlogVerbosity();
Xiyuan Xiaa0559da2022-05-05 19:42:45526#else
527 return GetVlogVerbosity();
528#endif // BUILDFLAG(USE_RUNTIME_VLOG)
[email protected]99b7c57f2010-09-29 19:26:36529}
530
initial.commitd7cae122008-07-26 21:49:38531void SetLogItems(bool enable_process_id, bool enable_thread_id,
532 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52533 g_log_process_id = enable_process_id;
534 g_log_thread_id = enable_thread_id;
535 g_log_timestamp = enable_timestamp;
536 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38537}
538
James Cooka0536c32018-08-01 20:13:31539void SetLogPrefix(const char* prefix) {
540 DCHECK(!prefix ||
541 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
542 g_log_prefix = prefix;
543}
544
[email protected]81e0a852010-08-17 00:38:12545void SetShowErrorDialogs(bool enable_dialogs) {
546 show_error_dialogs = enable_dialogs;
547}
548
alex-accc1bde62017-04-19 08:33:55549ScopedLogAssertHandler::ScopedLogAssertHandler(
550 LogAssertHandlerFunction handler) {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45551 GetLogAssertHandlerStack().push(std::move(handler));
alex-accc1bde62017-04-19 08:33:55552}
553
554ScopedLogAssertHandler::~ScopedLogAssertHandler() {
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45555 GetLogAssertHandlerStack().pop();
initial.commitd7cae122008-07-26 21:49:38556}
557
[email protected]2b07b8412009-11-25 15:26:34558void SetLogMessageHandler(LogMessageHandlerFunction handler) {
Wez244270362021-05-04 22:50:58559 g_log_message_handler = handler;
[email protected]2b07b8412009-11-25 15:26:34560}
561
[email protected]64e5cc02010-11-03 19:20:27562LogMessageHandlerFunction GetLogMessageHandler() {
Wez244270362021-05-04 22:50:58563 return g_log_message_handler;
[email protected]64e5cc02010-11-03 19:20:27564}
565
[email protected]f2c05492014-06-17 12:04:23566#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22567// Displays a message box to the user with the error message in it.
568// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25569// This is for developers only; we don't use this in circumstances
570// (like release builds) where users could see it, since users don't
571// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22572void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38573 if (str.empty())
574 return;
575
[email protected]81e0a852010-08-17 00:38:12576 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44577 return;
578
Xiaohan Wang38e4ebb2022-01-19 06:57:43579#if BUILDFLAG(IS_WIN)
[email protected]561513f2010-12-16 23:29:25580 // We intentionally don't implement a dialog on other platforms.
581 // You can just look at stderr.
Cliff Smolinskyc5c52102019-05-03 20:51:54582 if (base::win::IsUser32AndGdi32Available()) {
583 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
584 MB_OK | MB_ICONHAND | MB_TOPMOST);
585 } else {
586 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
587 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43588#endif // BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38589}
[email protected]f2c05492014-06-17 12:04:23590#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38591
[email protected]eae9c062011-01-11 00:50:59592LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
593 : severity_(severity), file_(file), line_(line) {
594 Init(file, line);
595}
596
tnagel4a045d3f2015-07-12 14:19:28597LogMessage::LogMessage(const char* file, int line, const char* condition)
Lei Zhang93dd42572020-10-23 18:45:53598 : severity_(LOGGING_FATAL), file_(file), line_(line) {
tnagel4a045d3f2015-07-12 14:19:28599 Init(file, line);
600 stream_ << "Check failed: " << condition << ". ";
601}
602
initial.commitd7cae122008-07-26 21:49:38603LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55604 size_t stack_start = stream_.tellp();
Xiaohan Wang38e4ebb2022-01-19 06:57:43605#if !defined(OFFICIAL_BUILD) && !BUILDFLAG(IS_NACL) && !defined(__UCLIBC__) && \
606 !BUILDFLAG(IS_AIX)
Lei Zhang93dd42572020-10-23 18:45:53607 if (severity_ == LOGGING_FATAL && !base::debug::BeingDebugged()) {
brucedawson7c559eb2015-09-05 00:34:42608 // Include a stack trace on a fatal, unless a debugger is attached.
Alan Cutter9b0e1ab2019-03-21 04:22:16609 base::debug::StackTrace stack_trace;
[email protected]d1ccc35a2010-03-24 05:03:24610 stream_ << std::endl; // Newline to separate from log message.
Alan Cutter9b0e1ab2019-03-21 04:22:16611 stack_trace.OutputToStream(&stream_);
612 base::debug::TaskTrace task_trace;
613 if (!task_trace.empty())
614 task_trace.OutputToStream(&stream_);
Chris Hamilton306740d2019-04-25 18:48:36615
Chris Hamilton888085312019-05-30 00:53:30616 // Include the IPC context, if any.
617 // TODO(chrisha): Integrate with symbolization once those tools exist!
Chris Hamilton306740d2019-04-25 18:48:36618 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
Chris Hamilton888085312019-05-30 00:53:30619 if (task && task->ipc_hash) {
620 stream_ << "IPC message handler context: "
621 << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
Chris Hamilton306740d2019-04-25 18:48:36622 }
Lukasz Anforowicz872567d2021-09-08 19:49:22623
624 // Include the crash keys, if any.
625 base::debug::OutputCrashKeysToStream(stream_);
[email protected]d1ccc35a2010-03-24 05:03:24626 }
[email protected]1d8c2702008-08-19 23:39:32627#endif
[email protected]d1ccc35a2010-03-24 05:03:24628 stream_ << std::endl;
629 std::string str_newline(stream_.str());
Nicolò Mazzucato6c278d9b2019-08-02 16:25:44630 TRACE_LOG_MESSAGE(
631 file_, base::StringPiece(str_newline).substr(message_start_), line_);
[email protected]d1ccc35a2010-03-24 05:03:24632
[email protected]2b07b8412009-11-25 15:26:34633 // Give any log message handler first dibs on the message.
Wez244270362021-05-04 22:50:58634 if (g_log_message_handler &&
635 g_log_message_handler(severity_, file_, line_, message_start_,
636 str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49637 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34638 return;
[email protected]162ac0f2010-11-04 15:50:49639 }
initial.commitd7cae122008-07-26 21:49:38640
thestig3e4787d2015-05-19 19:31:52641 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43642#if BUILDFLAG(IS_WIN)
initial.commitd7cae122008-07-26 21:49:38643 OutputDebugStringA(str_newline.c_str());
Xiaohan Wang38e4ebb2022-01-19 06:57:43644#elif BUILDFLAG(IS_APPLE)
mark4c7449c2015-11-10 19:53:42645 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
Eric Noyaufce100702017-10-16 09:46:34646 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
647 // its successor OS_LOG. If there's something weird about stderr, assume
648 // that log messages are going nowhere and log via ASL/OS_LOG too.
649 // Messages logged via ASL/OS_LOG show up in Console.app.
mark4c7449c2015-11-10 19:53:42650 //
651 // Programs started by launchd, as UI applications normally are, have had
652 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
653 // a pipe to launchd, which logged what it received (see log_redirect_fd in
654 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
655 //
656 // Another alternative would be to determine whether stderr is a pipe to
657 // launchd and avoid logging via ASL only in that case. See 10.7.5
658 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
Eric Noyaufce100702017-10-16 09:46:34659 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
660 // to the system log at all.
mark4c7449c2015-11-10 19:53:42661 //
662 // Note that the ASL client by default discards messages whose levels are
663 // below ASL_LEVEL_NOTICE. It's possible to change that with
664 // asl_set_filter(), but this is pointless because syslogd normally applies
665 // the same filter.
Eric Noyaufce100702017-10-16 09:46:34666 const bool log_to_system = []() {
mark4c7449c2015-11-10 19:53:42667 struct stat stderr_stat;
668 if (fstat(fileno(stderr), &stderr_stat) == -1) {
669 return true;
670 }
671 if (!S_ISCHR(stderr_stat.st_mode)) {
672 return false;
673 }
674
675 struct stat dev_null_stat;
676 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
677 return true;
678 }
679
680 return !S_ISCHR(dev_null_stat.st_mode) ||
681 stderr_stat.st_rdev == dev_null_stat.st_rdev;
682 }();
683
Eric Noyaufce100702017-10-16 09:46:34684 if (log_to_system) {
mark4c7449c2015-11-10 19:53:42685 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
686 // CF-1153.18/CFUtilities.c __CFLogCString().
mark4c7449c2015-11-10 19:53:42687 CFBundleRef main_bundle = CFBundleGetMainBundle();
688 CFStringRef main_bundle_id_cf =
689 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
Eric Noyaufce100702017-10-16 09:46:34690 std::string main_bundle_id =
mark4c7449c2015-11-10 19:53:42691 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
Eric Noyaufce100702017-10-16 09:46:34692 : std::string("");
693#if defined(USE_ASL)
694 // The facility is set to the main bundle ID if available. Otherwise,
695 // "com.apple.console" is used.
696 const class ASLClient {
mark4c7449c2015-11-10 19:53:42697 public:
Bruce Dawson4c6f8e12017-11-16 04:35:59698 explicit ASLClient(const std::string& facility)
699 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
David Bienvenub4b441e2020-09-23 05:49:57700 ASLClient(const ASLClient&) = delete;
701 ASLClient& operator=(const ASLClient&) = delete;
mark4c7449c2015-11-10 19:53:42702 ~ASLClient() { asl_close(client_); }
703
704 aslclient get() const { return client_; }
705
706 private:
707 aslclient client_;
Eric Noyaufce100702017-10-16 09:46:34708 } asl_client(main_bundle_id.empty() ? main_bundle_id
709 : "com.apple.console");
mark4c7449c2015-11-10 19:53:42710
Eric Noyaufce100702017-10-16 09:46:34711 const class ASLMessage {
mark4c7449c2015-11-10 19:53:42712 public:
713 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
David Bienvenub4b441e2020-09-23 05:49:57714 ASLMessage(const ASLMessage&) = delete;
715 ASLMessage& operator=(const ASLMessage&) = delete;
mark4c7449c2015-11-10 19:53:42716 ~ASLMessage() { asl_free(message_); }
717
718 aslmsg get() const { return message_; }
719
720 private:
721 aslmsg message_;
mark4c7449c2015-11-10 19:53:42722 } asl_message;
723
724 // By default, messages are only readable by the admin group. Explicitly
725 // make them readable by the user generating the messages.
726 char euid_string[12];
Daniel Chengf45f47602022-02-28 22:38:32727 snprintf(euid_string, std::size(euid_string), "%d", geteuid());
mark4c7449c2015-11-10 19:53:42728 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
729
730 // Map Chrome log severities to ASL log levels.
731 const char* const asl_level_string = [](LogSeverity severity) {
732 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
733 // non-obvious two-step macro trick achieves what's needed.
734 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
735#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
736#define ASL_LEVEL_STR_X(level) #level
737 switch (severity) {
Lei Zhang93dd42572020-10-23 18:45:53738 case LOGGING_INFO:
mark4c7449c2015-11-10 19:53:42739 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
Lei Zhang93dd42572020-10-23 18:45:53740 case LOGGING_WARNING:
mark4c7449c2015-11-10 19:53:42741 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
Lei Zhang93dd42572020-10-23 18:45:53742 case LOGGING_ERROR:
mark4c7449c2015-11-10 19:53:42743 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
Lei Zhang93dd42572020-10-23 18:45:53744 case LOGGING_FATAL:
mark4c7449c2015-11-10 19:53:42745 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
746 default:
747 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
748 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
749 }
750#undef ASL_LEVEL_STR
751#undef ASL_LEVEL_STR_X
752 }(severity_);
753 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
754
755 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
756
757 asl_send(asl_client.get(), asl_message.get());
Eric Noyaufce100702017-10-16 09:46:34758#else // !defined(USE_ASL)
759 const class OSLog {
760 public:
761 explicit OSLog(const char* subsystem)
762 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
763 : OS_LOG_DEFAULT) {}
David Bienvenub4b441e2020-09-23 05:49:57764 OSLog(const OSLog&) = delete;
765 OSLog& operator=(const OSLog&) = delete;
Eric Noyaufce100702017-10-16 09:46:34766 ~OSLog() {
767 if (os_log_ != OS_LOG_DEFAULT) {
768 os_release(os_log_);
769 }
770 }
771 os_log_t get() const { return os_log_; }
772
773 private:
774 os_log_t os_log_;
Eric Noyaufce100702017-10-16 09:46:34775 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
776 const os_log_type_t os_log_type = [](LogSeverity severity) {
777 switch (severity) {
Lei Zhang93dd42572020-10-23 18:45:53778 case LOGGING_INFO:
Eric Noyaufce100702017-10-16 09:46:34779 return OS_LOG_TYPE_INFO;
Lei Zhang93dd42572020-10-23 18:45:53780 case LOGGING_WARNING:
Eric Noyaufce100702017-10-16 09:46:34781 return OS_LOG_TYPE_DEFAULT;
Lei Zhang93dd42572020-10-23 18:45:53782 case LOGGING_ERROR:
Eric Noyaufce100702017-10-16 09:46:34783 return OS_LOG_TYPE_ERROR;
Lei Zhang93dd42572020-10-23 18:45:53784 case LOGGING_FATAL:
Eric Noyaufce100702017-10-16 09:46:34785 return OS_LOG_TYPE_FAULT;
786 default:
787 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
788 }
789 }(severity_);
790 os_log_with_type(log.get(), os_log_type, "%{public}s",
791 str_newline.c_str());
792#endif // defined(USE_ASL)
mark4c7449c2015-11-10 19:53:42793 }
Xiaohan Wang38e4ebb2022-01-19 06:57:43794#elif BUILDFLAG(IS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25795 android_LogPriority priority =
796 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50797 switch (severity_) {
Lei Zhang93dd42572020-10-23 18:45:53798 case LOGGING_INFO:
[email protected]3132e35c2011-07-07 20:46:50799 priority = ANDROID_LOG_INFO;
800 break;
Lei Zhang93dd42572020-10-23 18:45:53801 case LOGGING_WARNING:
[email protected]3132e35c2011-07-07 20:46:50802 priority = ANDROID_LOG_WARN;
803 break;
Lei Zhang93dd42572020-10-23 18:45:53804 case LOGGING_ERROR:
[email protected]3132e35c2011-07-07 20:46:50805 priority = ANDROID_LOG_ERROR;
806 break;
Lei Zhang93dd42572020-10-23 18:45:53807 case LOGGING_FATAL:
[email protected]3132e35c2011-07-07 20:46:50808 priority = ANDROID_LOG_FATAL;
809 break;
810 }
Tomasz Śniatowski23dd15af2019-02-15 08:32:03811 const char kAndroidLogTag[] = "chromium";
Xianzhu Wangae8d96a32018-10-16 20:41:13812#if DCHECK_IS_ON()
813 // Split the output by new lines to prevent the Android system from
814 // truncating the log.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03815 std::vector<std::string> lines = base::SplitString(
816 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
817 // str_newline has an extra newline appended to it (at the top of this
818 // function), so skip the last split element to avoid needlessly
819 // logging an empty string.
820 lines.pop_back();
821 for (const auto& line : lines)
822 __android_log_write(priority, kAndroidLogTag, line.c_str());
Xianzhu Wangae8d96a32018-10-16 20:41:13823#else
824 // The Android system may truncate the string if it's too long.
Tomasz Śniatowski23dd15af2019-02-15 08:32:03825 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18826#endif
Xiaohan Wang38e4ebb2022-01-19 06:57:43827#elif BUILDFLAG(IS_FUCHSIA)
Wez45e3ffe2021-09-24 02:10:02828 // LogMessage() will silently drop the message if the logger is not valid.
Weza38cc532021-12-16 22:58:20829 // Skip the final character of |str_newline|, since LogMessage() will add
830 // a newline.
831 const auto message = base::StringPiece(str_newline).substr(message_start_);
832 GetScopedFxLogger().LogMessage(file_, line_,
833 message.substr(0, message.size() - 1),
834 LogSeverityToFuchsiaLogSeverity(severity_));
Xiaohan Wang38e4ebb2022-01-19 06:57:43835#endif // BUILDFLAG(IS_FUCHSIA)
Sharon Yang7cb919a2019-05-20 20:27:15836 }
837
Wez6c8acb82019-07-18 00:32:59838 if (ShouldLogToStderr(severity_)) {
Benoit Lizeed678192022-01-20 10:14:54839 // Not using fwrite() here, as there are crashes on Windows when CRT calls
840 // malloc() internally, triggering an OOM crash. This likely means that the
841 // process is close to OOM, but at least get the proper error message out,
842 // and give the caller a chance to free() up some resources. For instance if
843 // the calling code is:
844 //
845 // allocate_something();
846 // if (!TryToDoSomething()) {
847 // LOG(ERROR) << "Something went wrong";
848 // free_something();
849 // }
850 WriteToFd(STDERR_FILENO, str_newline.data(), str_newline.size());
[email protected]f6abeba2008-08-08 13:27:28851 }
[email protected]52a261f2009-03-03 15:01:12852
thestig3e4787d2015-05-19 19:31:52853 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09854 // We can have multiple threads and/or processes, so try to prevent them
855 // from clobbering each other's writes.
856 // If the client app did not call InitLogging, and the lock has not
857 // been created do it now. We do this on demand, but if two threads try
858 // to do this at the same time, there will be a race condition to create
859 // the lock. This is why InitLogging should be called from the main
860 // thread at the beginning of execution.
Xiaohan Wang38e4ebb2022-01-19 06:57:43861#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:01862 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:09863#endif
[email protected]5b84fe32010-09-14 22:24:55864 if (InitializeLogFileHandle()) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43865#if BUILDFLAG(IS_WIN)
[email protected]5b84fe32010-09-14 22:24:55866 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52867 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55868 static_cast<const void*>(str_newline.c_str()),
869 static_cast<DWORD>(str_newline.length()),
870 &num_written,
thestig3e4787d2015-05-19 19:31:52871 nullptr);
Xiaohan Wang38e4ebb2022-01-19 06:57:43872#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Avi Drissman933398e2022-01-22 00:55:42873 std::ignore =
874 fwrite(str_newline.data(), str_newline.size(), 1, g_log_file);
thestig3e4787d2015-05-19 19:31:52875 fflush(g_log_file);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39876#else
877#error Unsupported platform
[email protected]cba21962010-08-31 22:35:55878#endif
initial.commitd7cae122008-07-26 21:49:38879 }
880 }
881
Lei Zhang93dd42572020-10-23 18:45:53882 if (severity_ == LOGGING_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40883 // Write the log message to the global activity tracker, if running.
884 base::debug::GlobalActivityTracker* tracker =
885 base::debug::GlobalActivityTracker::Get();
886 if (tracker)
887 tracker->RecordLogMessage(str_newline);
888
Wezd78fee62020-09-11 18:29:14889 char str_stack[1024];
Daniel Chengf45f47602022-02-28 22:38:32890 base::strlcpy(str_stack, str_newline.data(), std::size(str_stack));
Weze976b732018-10-20 03:37:31891 base::debug::Alias(&str_stack);
[email protected]eb4c4d032012-04-03 18:45:05892
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45893 if (!GetLogAssertHandlerStack().empty()) {
alex-accc1bde62017-04-19 08:33:55894 LogAssertHandlerFunction log_assert_handler =
Yannic Bonenberger3dcd7fe2019-06-08 11:01:45895 GetLogAssertHandlerStack().top();
alex-accc1bde62017-04-19 08:33:55896
897 if (log_assert_handler) {
898 log_assert_handler.Run(
899 file_, line_,
900 base::StringPiece(str_newline.c_str() + message_start_,
901 stack_start - message_start_),
902 base::StringPiece(str_newline.c_str() + stack_start));
903 }
[email protected]1ffe08c12008-08-13 11:15:11904 } else {
[email protected]82d89ab2014-02-28 18:25:34905 // Don't use the string with the newline, get a fresh version to send to
906 // the debug message process. We also don't display assertions to the
907 // user in release mode. The enduser can't do anything with this
908 // information, and displaying message boxes when the application is
909 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50910#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42911 if (!base::debug::BeingDebugged()) {
912 // Displaying a dialog is unnecessary when debugging and can complicate
913 // debugging.
914 DisplayDebugMessageInDialog(stream_.str());
915 }
[email protected]4d5901272008-11-06 00:33:50916#endif
Daniel Cheng4f5034d2022-03-04 18:34:31917
[email protected]82d89ab2014-02-28 18:25:34918 // Crash the process to generate a dump.
Torne (Richard Coles)54b86796a62018-07-24 14:59:52919 IMMEDIATE_CRASH();
initial.commitd7cae122008-07-26 21:49:38920 }
921 }
922}
923
[email protected]eae9c062011-01-11 00:50:59924// writes the common header info to the stream
925void LogMessage::Init(const char* file, int line) {
926 base::StringPiece filename(file);
927 size_t last_slash_pos = filename.find_last_of("\\/");
928 if (last_slash_pos != base::StringPiece::npos)
929 filename.remove_prefix(last_slash_pos + 1);
930
Georg Neisffe34f652021-12-27 21:42:36931#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54932 if (g_log_format == LogFormat::LOG_FORMAT_SYSLOG) {
933 InitWithSyslogPrefix(
934 filename, line, TickCount(), log_severity_name(severity_), g_log_prefix,
935 g_log_process_id, g_log_thread_id, g_log_timestamp, g_log_tickcount);
936 } else
Georg Neisffe34f652021-12-27 21:42:36937#endif // BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:54938 {
939 // TODO(darin): It might be nice if the columns were fixed width.
940 stream_ << '[';
941 if (g_log_prefix)
942 stream_ << g_log_prefix << ':';
943 if (g_log_process_id)
944 stream_ << base::GetUniqueIdForProcess() << ':';
945 if (g_log_thread_id)
946 stream_ << base::PlatformThread::CurrentId() << ':';
947 if (g_log_timestamp) {
Xiaohan Wang38e4ebb2022-01-19 06:57:43948#if BUILDFLAG(IS_WIN)
Yuta Hijikata9b7279a2020-08-26 16:10:54949 SYSTEMTIME local_time;
950 GetLocalTime(&local_time);
951 stream_ << std::setfill('0')
952 << std::setw(2) << local_time.wMonth
953 << std::setw(2) << local_time.wDay
954 << '/'
955 << std::setw(2) << local_time.wHour
956 << std::setw(2) << local_time.wMinute
957 << std::setw(2) << local_time.wSecond
958 << '.'
959 << std::setw(3) << local_time.wMilliseconds
960 << ':';
Xiaohan Wang38e4ebb2022-01-19 06:57:43961#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Yuta Hijikata9b7279a2020-08-26 16:10:54962 timeval tv;
963 gettimeofday(&tv, nullptr);
964 time_t t = tv.tv_sec;
965 struct tm local_time;
966 localtime_r(&t, &local_time);
967 struct tm* tm_time = &local_time;
968 stream_ << std::setfill('0')
969 << std::setw(2) << 1 + tm_time->tm_mon
970 << std::setw(2) << tm_time->tm_mday
971 << '/'
972 << std::setw(2) << tm_time->tm_hour
973 << std::setw(2) << tm_time->tm_min
974 << std::setw(2) << tm_time->tm_sec
975 << '.'
976 << std::setw(6) << tv.tv_usec
977 << ':';
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39978#else
979#error Unsupported platform
djkurtz543a3be2016-11-30 14:17:34980#endif
Yuta Hijikata9b7279a2020-08-26 16:10:54981 }
982 if (g_log_tickcount)
983 stream_ << TickCount() << ':';
984 if (severity_ >= 0) {
985 stream_ << log_severity_name(severity_);
986 } else {
987 stream_ << "VERBOSE" << -severity_;
988 }
989 stream_ << ":" << filename << "(" << line << ")] ";
[email protected]eae9c062011-01-11 00:50:59990 }
pkasting9cf9b94a2014-10-01 22:18:43991 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59992}
993
Xiaohan Wang38e4ebb2022-01-19 06:57:43994#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:20995// This has already been defined in the header, but defining it again as DWORD
996// ensures that the type used in the header is equivalent to DWORD. If not,
997// the redefinition is a compile error.
998typedef DWORD SystemErrorCode;
999#endif
1000
1001SystemErrorCode GetLastSystemErrorCode() {
Xiaohan Wang38e4ebb2022-01-19 06:57:431002#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201003 return ::GetLastError();
Xiaohan Wang38e4ebb2022-01-19 06:57:431004#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201005 return errno;
[email protected]d8617a62009-10-09 23:52:201006#endif
1007}
1008
[email protected]c914d8a2014-04-23 01:11:011009BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
Xiaohan Wang38e4ebb2022-01-19 06:57:431010#if BUILDFLAG(IS_WIN)
thestig75f87352014-12-03 21:42:271011 const int kErrorMessageBufferSize = 256;
1012 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:011013 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:521014 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
Daniel Chengf45f47602022-02-28 22:38:321015 std::size(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:011016 if (len) {
1017 // Messages returned by system end with line breaks.
1018 return base::CollapseWhitespaceASCII(msgbuf, true) +
Bruce Dawson19175842017-08-02 17:00:451019 base::StringPrintf(" (0x%lX)", error_code);
[email protected]c914d8a2014-04-23 01:11:011020 }
Bruce Dawson19175842017-08-02 17:00:451021 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
[email protected]c914d8a2014-04-23 01:11:011022 GetLastError(), error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431023#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Robert Sesekd2f495f2017-07-25 22:03:141024 return base::safe_strerror(error_code) +
1025 base::StringPrintf(" (%d)", error_code);
Xiaohan Wang38e4ebb2022-01-19 06:57:431026#endif // BUILDFLAG(IS_WIN)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:391027}
[email protected]d8617a62009-10-09 23:52:201028
Xiaohan Wang38e4ebb2022-01-19 06:57:431029#if BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201030Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1031 int line,
1032 LogSeverity severity,
1033 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001034 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201035
1036Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011037 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:061038 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1039 // field) and use Alias in hopes that it makes it into crash dumps.
1040 DWORD last_error = err_;
1041 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201042}
Xiaohan Wang38e4ebb2022-01-19 06:57:431043#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
[email protected]d8617a62009-10-09 23:52:201044ErrnoLogMessage::ErrnoLogMessage(const char* file,
1045 int line,
1046 LogSeverity severity,
1047 SystemErrorCode err)
Hans Wennborg12aea3e2020-04-14 15:29:001048 : LogMessage(file, line, severity), err_(err) {}
[email protected]d8617a62009-10-09 23:52:201049
1050ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:011051 stream() << ": " << SystemErrorCodeToString(err_);
Robert Sesekd2f495f2017-07-25 22:03:141052 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1053 // field) and use Alias in hopes that it makes it into crash dumps.
1054 int last_error = err_;
1055 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:201056}
Xiaohan Wang38e4ebb2022-01-19 06:57:431057#endif // BUILDFLAG(IS_WIN)
[email protected]d8617a62009-10-09 23:52:201058
initial.commitd7cae122008-07-26 21:49:381059void CloseLogFile() {
Xiaohan Wang38e4ebb2022-01-19 06:57:431060#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
Benoit Lize5c98a832020-07-07 16:32:011061 base::AutoLock guard(GetLoggingLock());
ananta61762fb2015-09-18 01:00:091062#endif
[email protected]17dcf752013-07-15 21:47:091063 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:381064}
1065
Yuta Hijikata000df18f2020-11-18 06:55:581066#if BUILDFLAG(IS_CHROMEOS_ASH)
Robbie McElrath8bf49842019-08-20 22:22:531067FILE* DuplicateLogFILE() {
1068 if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle())
1069 return nullptr;
1070
1071 int log_fd = fileno(g_log_file);
1072 if (log_fd == -1)
1073 return nullptr;
1074 base::ScopedFD dup_fd(dup(log_fd));
1075 if (dup_fd == -1)
1076 return nullptr;
1077 FILE* duplicate = fdopen(dup_fd.get(), "a");
1078 if (!duplicate)
1079 return nullptr;
Avi Drissman933398e2022-01-22 00:55:421080 std::ignore = dup_fd.release();
Robbie McElrath8bf49842019-08-20 22:22:531081 return duplicate;
1082}
1083#endif
1084
Yuta Hijikata9b7279a2020-08-26 16:10:541085// Used for testing. Declared in test/scoped_logging_settings.h.
1086ScopedLoggingSettings::ScopedLoggingSettings()
Wez244270362021-05-04 22:50:581087 : min_log_level_(g_min_log_level),
1088 logging_destination_(g_logging_destination),
Georg Neisffe34f652021-12-27 21:42:361089#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581090 log_format_(g_log_format),
1091#endif // BUILDFLAG(IS_CHROMEOS_ASH)
1092 enable_process_id_(g_log_process_id),
Yuta Hijikata9b7279a2020-08-26 16:10:541093 enable_thread_id_(g_log_thread_id),
1094 enable_timestamp_(g_log_timestamp),
1095 enable_tickcount_(g_log_tickcount),
Wez244270362021-05-04 22:50:581096 log_prefix_(g_log_prefix),
1097 message_handler_(g_log_message_handler) {
1098 if (g_log_file_name)
1099 log_file_name_ = std::make_unique<PathString>(*g_log_file_name);
1100 // Duplicating |g_log_file| is complex & unnecessary for this test helpers'
1101 // use-cases, and so long as |g_log_file_name| is set, it will be re-opened
1102 // automatically anyway, when required, so just close the existing one.
1103 if (g_log_file) {
1104 CHECK(g_log_file_name) << "Un-named |log_file| is not supported.";
1105 CloseLogFileUnlocked();
1106 }
Yuta Hijikata9b7279a2020-08-26 16:10:541107}
1108
1109ScopedLoggingSettings::~ScopedLoggingSettings() {
Wez244270362021-05-04 22:50:581110 // Re-initialize logging via the normal path. This will clean up old file
1111 // name and handle state, including re-initializing the VLOG internal state.
1112 CHECK(InitLogging({
1113 .logging_dest = logging_destination_,
1114 .log_file_path = log_file_name_ ? log_file_name_->data() : nullptr,
Georg Neisffe34f652021-12-27 21:42:361115#if BUILDFLAG(IS_CHROMEOS)
Wez244270362021-05-04 22:50:581116 .log_format = log_format_
1117#endif
1118 })) << "~ScopedLoggingSettings() failed to restore settings.";
1119
1120 // Restore plain data settings.
1121 SetMinLogLevel(min_log_level_);
1122 SetLogItems(enable_process_id_, enable_thread_id_, enable_timestamp_,
1123 enable_tickcount_);
1124 SetLogPrefix(log_prefix_);
1125 SetLogMessageHandler(message_handler_);
Yuta Hijikata9b7279a2020-08-26 16:10:541126}
1127
Georg Neisffe34f652021-12-27 21:42:361128#if BUILDFLAG(IS_CHROMEOS)
Yuta Hijikata9b7279a2020-08-26 16:10:541129void ScopedLoggingSettings::SetLogFormat(LogFormat log_format) const {
1130 g_log_format = log_format;
1131}
Yuta Hijikata000df18f2020-11-18 06:55:581132#endif // BUILDFLAG(IS_CHROMEOS_ASH)
Yuta Hijikata9b7279a2020-08-26 16:10:541133
[email protected]e36ddc82009-12-08 04:22:501134void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:491135 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:501136 const size_t message_len = strlen(message);
Benoit Lizeed678192022-01-20 10:14:541137 WriteToFd(STDERR_FILENO, message, message_len);
[email protected]e36ddc82009-12-08 04:22:501138
1139 if (message_len > 0 && message[message_len - 1] != '\n') {
Benoit Lizeed678192022-01-20 10:14:541140 int rv;
[email protected]e36ddc82009-12-08 04:22:501141 do {
1142 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1143 if (rv < 0) {
1144 // Give up, nothing we can do now.
1145 break;
1146 }
1147 } while (rv != 1);
1148 }
1149 }
1150
Lei Zhang93dd42572020-10-23 18:45:531151 if (level == LOGGING_FATAL)
Daniel Cheng4f5034d2022-03-04 18:34:311152 IMMEDIATE_CRASH();
[email protected]e36ddc82009-12-08 04:22:501153}
1154
[email protected]34a907732012-01-20 06:33:271155// This was defined at the beginning of this file.
1156#undef write
1157
Xiaohan Wang38e4ebb2022-01-19 06:57:431158#if BUILDFLAG(IS_WIN)
ananta61762fb2015-09-18 01:00:091159bool IsLoggingToFileEnabled() {
1160 return g_logging_destination & LOG_TO_FILE;
1161}
1162
Jan Wilken Dörrieb630aca2019-12-04 10:59:111163std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:521164 if (g_log_file_name)
1165 return *g_log_file_name;
Jan Wilken Dörrieb630aca2019-12-04 10:59:111166 return std::wstring();
[email protected]f01b88a2013-02-27 22:04:001167}
1168#endif
1169
Xiyuan Xiaa0559da2022-05-05 19:42:451170#if !BUILDFLAG(USE_RUNTIME_VLOG)
1171int GetDisableAllVLogLevel() {
1172 return -1;
1173}
1174#endif // !BUILDFLAG(USE_RUNTIME_VLOG)
1175
[email protected]96fd0032009-04-24 00:13:081176} // namespace logging
initial.commitd7cae122008-07-26 21:49:381177
[email protected]81411c62014-07-08 23:03:061178std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391179 return out << (wstr ? base::WStringPiece(wstr) : base::WStringPiece());
1180}
1181
1182std::ostream& std::operator<<(std::ostream& out, const std::wstring& wstr) {
1183 return out << base::WStringPiece(wstr);
1184}
1185
1186std::ostream& std::operator<<(std::ostream& out, const char16_t* str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461187 return out << (str16 ? base::StringPiece16(str16) : base::StringPiece16());
Jan Wilken Dörrie4a498d8c2021-01-20 10:19:391188}
1189
1190std::ostream& std::operator<<(std::ostream& out, const std::u16string& str16) {
Jan Wilken Dörrie43d5378f2021-03-10 12:04:461191 return out << base::StringPiece16(str16);
initial.commitd7cae122008-07-26 21:49:381192}