Coverage Report

Created: 2026-11-21 07:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/proc/self/cwd/base/logging.cc
Line
Count
Source
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one
3
 * or more contributor license agreements.  See the NOTICE file
4
 * distributed with this work for additional information
5
 * regarding copyright ownership.  The ASF licenses this file
6
 * to you under the Apache License, Version 2.0 (the
7
 * "License"); you may not use this file except in compliance
8
 * with the License.  You may obtain a copy of the License at
9
 *
10
 *   http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing,
13
 * software distributed under the License is distributed on an
14
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
 * KIND, either express or implied.  See the License for the
16
 * specific language governing permissions and limitations
17
 * under the License.
18
 */
19
20
#include "base/logging.h"
21
22
#include <atomic>
23
#include <cstdio>
24
#include <cstdlib>
25
#include <iostream>
26
#include <iterator>
27
#include <memory>
28
#include <mutex>
29
#include <vector>
30
31
#include "fmt/format.h"
32
#include "spdlog/spdlog.h"
33
34
namespace pagespeed_logging {
35
36
// Atomic flag set by ShutDownLogging(). Once true, LogMessage::~LogMessage()
37
// writes to stderr instead of spdlog, avoiding crashes from the static
38
// destruction order fiasco (spdlog's global logger may be destroyed before
39
// our static ApacheProcessContext destructor runs).
40
static std::atomic<bool> g_logging_shutdown{false};
41
42
// Returns a process-immortal spdlog logger. The strong reference is
43
// captured once on first use and intentionally LEAKED, so the logger object
44
// outlives ALL static destruction — including spdlog's own registry singleton —
45
// and therefore stays valid for any worker thread that is still draining work
46
// and may LOG() during process shutdown. Access is lock-free after the first
47
// call (a function-local-static acquire load), unlike the spdlog::default_logger()
48
// free function, which locks spdlog's registry mutex on every call, and unlike
49
// spdlog::info()/warn()/... which re-fetch the registry's raw default logger
50
// (the object torn down first in the static-destruction-order fiasco).
51
6.15M
static spdlog::logger* HeldLogger() {
52
  // The strong reference is captured once and never freed, so the logger object
53
  // (and its sinks) stay immortal for the process lifetime. The heap shared_ptr
54
  // is kept REACHABLE through this static pointer, so LeakSanitizer treats it as
55
  // a live root — intentional immortality, not a reported leak. (Returning
56
  // ->get() into the static instead would orphan the shared_ptr and LSan flags
57
  // it: a 16-byte "direct leak".)
58
6.15M
  static std::shared_ptr<spdlog::logger>* const held =
59
6.15M
      new std::shared_ptr<spdlog::logger>(spdlog::default_logger());
60
6.15M
  return held->get();
61
6.15M
}
62
63
namespace {
64
65
std::mutex g_sinks_mutex;
66
std::vector<LogSink*>* g_sinks = nullptr;
67
68
// Allocates on first use. Only AddLogSink may call this: the read and remove
69
// paths must not resurrect the container, or a LOG() arriving after the last
70
// RemoveLogSink would re-leak it past DLL unload.
71
0
std::vector<LogSink*>* GetOrCreateSinks() {
72
0
  if (g_sinks == nullptr) {
73
0
    g_sinks = new std::vector<LogSink*>();
74
0
  }
75
0
  return g_sinks;
76
0
}
77
78
}  // namespace
79
80
0
void AddLogSink(LogSink* sink) {
81
0
  std::lock_guard<std::mutex> lock(g_sinks_mutex);
82
0
  GetOrCreateSinks()->push_back(sink);
83
0
}
84
85
0
void RemoveLogSink(LogSink* sink) {
86
0
  std::lock_guard<std::mutex> lock(g_sinks_mutex);
87
0
  if (g_sinks == nullptr) {
88
0
    return;
89
0
  }
90
0
  for (auto it = g_sinks->begin(); it != g_sinks->end(); ++it) {
91
0
    if (*it == sink) {
92
0
      g_sinks->erase(it);
93
0
      break;
94
0
    }
95
0
  }
96
  // Free the container once the last sink unregisters. erase() alone keeps the
97
  // vector's heap buffer alive, and that buffer is owned by the module that
98
  // registered the sink -- for a dynamically unloaded module (the IIS DLL) it
99
  // outlives FreeLibrary and trips AppVerifier's Leak provider (stop 0x900).
100
0
  if (g_sinks->empty()) {
101
0
    delete g_sinks;
102
0
    g_sinks = nullptr;
103
0
  }
104
0
}
105
106
void SendToSinks(int severity, const char* full_filename,
107
                 const char* base_filename, int line, const char* message,
108
22.3M
                 size_t message_len) {
109
22.3M
  std::lock_guard<std::mutex> lock(g_sinks_mutex);
110
22.3M
  if (g_sinks == nullptr) {
111
22.3M
    return;
112
22.3M
  }
113
0
  for (auto* sink : *g_sinks) {
114
0
    sink->send(severity, full_filename, base_filename, line, message,
115
0
               message_len);
116
0
  }
117
0
}
118
119
0
void ShutDownLogging() {
120
  // Route subsequent LOG()s to stderr. This guards the registered-sink path
121
  // (SendToSinks -> ApacheGLogSink -> ap_log_perror on the Apache pool), which
122
  // is NOT covered by the immortal spdlog logger above. The spdlog path is safe
123
  // regardless of this flag because HeldLogger() never dies.
124
0
  g_logging_shutdown.store(true, std::memory_order_release);
125
0
}
126
127
22.3M
LogMessage::~LogMessage() {
128
22.3M
  std::string msg = stream_.str();
129
22.3M
  const char* base_filename = GetBasename(file_);
130
131
  // Verbose VLOG(n) messages carry a negative severity. They must not be
132
  // written to a process logger: that output is not level-filtered by the
133
  // hosting server, so mirroring it flooded server error logs at the
134
  // default LogLevel. Registered sinks still receive verbose messages and
135
  // apply their own cutoffs. A verbose severity is never LOG_FATAL, so no
136
  // abort check is needed on this path. Once shutdown has begun the sinks
137
  // may be gone (a straggling worker's host log pool is freed by then), and
138
  // a verbose message is not worth a stderr line: drop it.
139
22.3M
  if (severity_ < 0) {
140
16.2M
    if (g_logging_shutdown.load(std::memory_order_acquire)) {
141
0
      return;
142
0
    }
143
16.2M
    SendToSinks(severity_, file_, base_filename, line_, msg.c_str(),
144
16.2M
                msg.size());
145
16.2M
    return;
146
16.2M
  }
147
148
6.15M
  if (g_logging_shutdown.load(std::memory_order_acquire)) {
149
    // Process is shutting down — spdlog may already be destroyed.
150
    // Write to stderr instead, which is always safe.
151
0
    static const char* const kSeverityNames[] = {"INFO", "WARN", "ERROR",
152
0
                                                  "FATAL"};
153
0
    int idx = (severity_ >= 0 && severity_ <= 3) ? severity_ : 0;
154
0
    fprintf(stderr, "[%s] [pagespeed] [%s:%d] %s\n", kSeverityNames[idx],
155
0
            base_filename, line_, msg.c_str());
156
0
    if (severity_ == logging::LOG_FATAL) {
157
0
      std::abort();
158
0
    }
159
0
    return;
160
0
  }
161
162
  // Emit through the immortal held logger via a raw pointer: lock-free, and
163
  // valid even if spdlog's registry singleton has already been destroyed during
164
  // shutdown.
165
6.15M
  spdlog::logger* logger = HeldLogger();
166
167
  // Send to spdlog (via the held logger, never the registry free functions).
168
  // The line is formatted here and handed to spdlog as a plain message:
169
  // spdlog 1.17.0's format-string overloads convert through a member that fmt
170
  // 12.2 marks deprecated, and no spdlog release yet avoids that conversion.
171
6.15M
  fmt::memory_buffer line;
172
6.15M
  fmt::format_to(std::back_inserter(line), "[pagespeed] [{}:{}] {}",
173
6.15M
                 base_filename, line_, msg);
174
6.15M
  const spdlog::string_view_t line_view(line.data(), line.size());
175
6.15M
  switch (severity_) {
176
0
    case logging::LOG_INFO:
177
0
      logger->info(line_view);
178
0
      break;
179
6.15M
    case logging::LOG_WARNING:
180
6.15M
      logger->warn(line_view);
181
6.15M
      break;
182
66
    case logging::LOG_ERROR:
183
66
      logger->error(line_view);
184
66
      break;
185
0
    case logging::LOG_FATAL:
186
0
      logger->critical(line_view);
187
      // Also write to stderr for death tests (EXPECT_DEBUG_DEATH captures stderr)
188
0
      std::cerr << "[FATAL] [" << base_filename << ":" << line_ << "] " << msg
189
0
                << '\n';
190
0
      logger->dump_backtrace();
191
0
      break;
192
0
    default:
193
0
      logger->info(line_view);
194
0
      break;
195
6.15M
  }
196
197
  // Send to registered sinks
198
6.15M
  SendToSinks(severity_, file_, base_filename, line_, msg.c_str(), msg.size());
199
200
  // Abort on fatal errors
201
6.15M
  if (severity_ == logging::LOG_FATAL) {
202
0
    std::abort();
203
0
  }
204
6.15M
}
205
206
}  // namespace pagespeed_logging
207
208
namespace net_instaweb {
209
210
0
PageSpeedLogSink::PageSpeedLogSink() { ::pagespeed_logging::AddLogSink(this); }
211
212
0
PageSpeedLogSink::~PageSpeedLogSink() {
213
0
  ::pagespeed_logging::RemoveLogSink(this);
214
0
}
215
216
void PageSpeedLogSink::send(int severity, const char* /*full_filename*/,
217
                            const char* base_filename, int line,
218
0
                            const char* message, size_t message_len) {
219
0
  if (severity < min_log_level_) {
220
0
    return;
221
0
  }
222
  // Default implementation just logs to spdlog (already done by LogMessage)
223
  // Subclasses can override to redirect to Apache error log, etc.
224
0
}
225
226
}  // namespace net_instaweb