Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #include <logging.h>
7 : : #include <memusage.h>
8 : : #include <util/check.h>
9 : : #include <util/fs.h>
10 : : #include <util/string.h>
11 : : #include <util/threadnames.h>
12 : : #include <util/time.h>
13 : :
14 : : #include <array>
15 : : #include <cstring>
16 : : #include <map>
17 : : #include <optional>
18 : : #include <utility>
19 : :
20 : : using util::Join;
21 : : using util::RemovePrefixView;
22 : :
23 : : const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
24 : : constexpr auto MAX_USER_SETABLE_SEVERITY_LEVEL{BCLog::Level::Info};
25 : :
26 : 16099215 : BCLog::Logger& LogInstance()
27 : : {
28 : : /**
29 : : * NOTE: the logger instances is leaked on exit. This is ugly, but will be
30 : : * cleaned up by the OS/libc. Defining a logger as a global object doesn't work
31 : : * since the order of destruction of static/global objects is undefined.
32 : : * Consider if the logger gets destroyed, and then some later destructor calls
33 : : * LogPrintf, maybe indirectly, and you get a core dump at shutdown trying to
34 : : * access the logger. When the shutdown sequence is fully audited and tested,
35 : : * explicit destruction of these objects can be implemented by changing this
36 : : * from a raw pointer to a std::unique_ptr.
37 : : * Since the ~Logger() destructor is never called, the Logger class and all
38 : : * its subclasses must have implicitly-defined destructors.
39 : : *
40 : : * This method of initialization was originally introduced in
41 : : * ee3374234c60aba2cc4c5cd5cac1c0aefc2d817c.
42 : : */
43 [ + + + - : 16099215 : static BCLog::Logger* g_logger{new BCLog::Logger()};
+ - ]
44 : 16099215 : return *g_logger;
45 : : }
46 : :
47 : : bool fLogIPs = DEFAULT_LOGIPS;
48 : :
49 : 5445757 : static int FileWriteStr(std::string_view str, FILE *fp)
50 : : {
51 : 5445757 : return fwrite(str.data(), 1, str.size(), fp);
52 : : }
53 : :
54 : 1654 : bool BCLog::Logger::StartLogging()
55 : : {
56 : 1654 : StdLockGuard scoped_lock(m_cs);
57 : :
58 [ - + ]: 1654 : assert(m_buffering);
59 [ - + ]: 1654 : assert(m_fileout == nullptr);
60 : :
61 [ + + ]: 1654 : if (m_print_to_file) {
62 [ - + ]: 1653 : assert(!m_file_path.empty());
63 [ + - ]: 1653 : m_fileout = fsbridge::fopen(m_file_path, "a");
64 [ + + ]: 1653 : if (!m_fileout) {
65 : : return false;
66 : : }
67 : :
68 : 1651 : setbuf(m_fileout, nullptr); // unbuffered
69 : :
70 : : // Add newlines to the logfile to distinguish this execution from the
71 : : // last one.
72 [ + - ]: 1651 : FileWriteStr("\n\n\n\n\n", m_fileout);
73 : : }
74 : :
75 : : // dump buffered messages from before we opened the log
76 : 1652 : m_buffering = false;
77 [ - + ]: 1652 : if (m_buffer_lines_discarded > 0) {
78 [ # # # # ]: 0 : LogPrintStr_(strprintf("Early logging buffer overflowed, %d log lines discarded.\n", m_buffer_lines_discarded), std::source_location::current(), BCLog::ALL, Level::Info, /*should_ratelimit=*/false);
79 : : }
80 [ + + ]: 8166 : while (!m_msgs_before_open.empty()) {
81 [ + - ]: 6514 : const auto& buflog = m_msgs_before_open.front();
82 [ + - ]: 6514 : std::string s{buflog.str};
83 [ + - ]: 6514 : FormatLogStrInPlace(s, buflog.category, buflog.level, buflog.source_loc, buflog.threadname, buflog.now, buflog.mocktime);
84 : 6514 : m_msgs_before_open.pop_front();
85 : :
86 [ + + + - ]: 6514 : if (m_print_to_file) FileWriteStr(s, m_fileout);
87 [ - + - - ]: 6514 : if (m_print_to_console) fwrite(s.data(), 1, s.size(), stdout);
88 [ + + ]: 7726 : for (const auto& cb : m_print_callbacks) {
89 [ + - ]: 1212 : cb(s);
90 : : }
91 : 6514 : }
92 : 1652 : m_cur_buffer_memusage = 0;
93 [ - + - - ]: 1652 : if (m_print_to_console) fflush(stdout);
94 : :
95 : : return true;
96 : 1654 : }
97 : :
98 : 605 : void BCLog::Logger::DisconnectTestLogger()
99 : : {
100 : 605 : StdLockGuard scoped_lock(m_cs);
101 : 605 : m_buffering = true;
102 [ + - + - ]: 605 : if (m_fileout != nullptr) fclose(m_fileout);
103 : 605 : m_fileout = nullptr;
104 : 605 : m_print_callbacks.clear();
105 : 605 : m_max_buffer_memusage = DEFAULT_MAX_LOG_BUFFER;
106 : 605 : m_cur_buffer_memusage = 0;
107 : 605 : m_buffer_lines_discarded = 0;
108 : 605 : m_msgs_before_open.clear();
109 : 605 : }
110 : :
111 : 0 : void BCLog::Logger::DisableLogging()
112 : : {
113 : 0 : {
114 : 0 : StdLockGuard scoped_lock(m_cs);
115 [ # # ]: 0 : assert(m_buffering);
116 [ # # ]: 0 : assert(m_print_callbacks.empty());
117 : 0 : }
118 : 0 : m_print_to_file = false;
119 : 0 : m_print_to_console = false;
120 : 0 : StartLogging();
121 : 0 : }
122 : :
123 : 1677 : void BCLog::Logger::EnableCategory(BCLog::LogFlags flag)
124 : : {
125 : 1677 : m_categories |= flag;
126 : 1677 : }
127 : :
128 : 1676 : bool BCLog::Logger::EnableCategory(std::string_view str)
129 : : {
130 : 1676 : BCLog::LogFlags flag;
131 [ + + ]: 1676 : if (!GetLogCategory(flag, str)) return false;
132 : 1675 : EnableCategory(flag);
133 : 1675 : return true;
134 : : }
135 : :
136 : 4405 : void BCLog::Logger::DisableCategory(BCLog::LogFlags flag)
137 : : {
138 : 4405 : m_categories &= ~flag;
139 : 4405 : }
140 : :
141 : 4406 : bool BCLog::Logger::DisableCategory(std::string_view str)
142 : : {
143 : 4406 : BCLog::LogFlags flag;
144 [ + + ]: 4406 : if (!GetLogCategory(flag, str)) return false;
145 : 4405 : DisableCategory(flag);
146 : 4405 : return true;
147 : : }
148 : :
149 : 5263604 : bool BCLog::Logger::WillLogCategory(BCLog::LogFlags category) const
150 : : {
151 : 5263604 : return (m_categories.load(std::memory_order_relaxed) & category) != 0;
152 : : }
153 : :
154 : 5107583 : bool BCLog::Logger::WillLogCategoryLevel(BCLog::LogFlags category, BCLog::Level level) const
155 : : {
156 : : // Log messages at Info, Warning and Error level unconditionally, so that
157 : : // important troubleshooting information doesn't get lost.
158 [ + + ]: 5107583 : if (level >= BCLog::Level::Info) return true;
159 : :
160 [ + + ]: 5104482 : if (!WillLogCategory(category)) return false;
161 : :
162 : 5049803 : StdLockGuard scoped_lock(m_cs);
163 : 5049803 : const auto it{m_category_log_levels.find(category)};
164 [ + + ]: 5049803 : return level >= (it == m_category_log_levels.end() ? LogLevel() : it->second);
165 : 5049803 : }
166 : :
167 : 1047 : bool BCLog::Logger::DefaultShrinkDebugFile() const
168 : : {
169 : 1047 : return m_categories == BCLog::NONE;
170 : : }
171 : :
172 : : static const std::map<std::string, BCLog::LogFlags, std::less<>> LOG_CATEGORIES_BY_STR{
173 : : {"net", BCLog::NET},
174 : : {"tor", BCLog::TOR},
175 : : {"mempool", BCLog::MEMPOOL},
176 : : {"http", BCLog::HTTP},
177 : : {"bench", BCLog::BENCH},
178 : : {"zmq", BCLog::ZMQ},
179 : : {"walletdb", BCLog::WALLETDB},
180 : : {"rpc", BCLog::RPC},
181 : : {"estimatefee", BCLog::ESTIMATEFEE},
182 : : {"addrman", BCLog::ADDRMAN},
183 : : {"selectcoins", BCLog::SELECTCOINS},
184 : : {"reindex", BCLog::REINDEX},
185 : : {"cmpctblock", BCLog::CMPCTBLOCK},
186 : : {"rand", BCLog::RAND},
187 : : {"prune", BCLog::PRUNE},
188 : : {"proxy", BCLog::PROXY},
189 : : {"mempoolrej", BCLog::MEMPOOLREJ},
190 : : {"libevent", BCLog::LIBEVENT},
191 : : {"coindb", BCLog::COINDB},
192 : : {"qt", BCLog::QT},
193 : : {"leveldb", BCLog::LEVELDB},
194 : : {"validation", BCLog::VALIDATION},
195 : : {"i2p", BCLog::I2P},
196 : : {"ipc", BCLog::IPC},
197 : : #ifdef DEBUG_LOCKCONTENTION
198 : : {"lock", BCLog::LOCK},
199 : : #endif
200 : : {"blockstorage", BCLog::BLOCKSTORAGE},
201 : : {"txreconciliation", BCLog::TXRECONCILIATION},
202 : : {"scan", BCLog::SCAN},
203 : : {"txpackages", BCLog::TXPACKAGES},
204 : : };
205 : :
206 : : static const std::unordered_map<BCLog::LogFlags, std::string> LOG_CATEGORIES_BY_FLAG{
207 : : // Swap keys and values from LOG_CATEGORIES_BY_STR.
208 : 2451 : [](const auto& in) {
209 : 2451 : std::unordered_map<BCLog::LogFlags, std::string> out;
210 [ + - + + ]: 71079 : for (const auto& [k, v] : in) {
211 : 68628 : const bool inserted{out.emplace(v, k).second};
212 [ - + ]: 68628 : assert(inserted);
213 : : }
214 : 2451 : return out;
215 : 0 : }(LOG_CATEGORIES_BY_STR)
216 : : };
217 : :
218 : 6115 : bool GetLogCategory(BCLog::LogFlags& flag, std::string_view str)
219 : : {
220 [ + + + - : 6115 : if (str.empty() || str == "1" || str == "all") {
- + ]
221 : 1668 : flag = BCLog::ALL;
222 : 1668 : return true;
223 : : }
224 : 4447 : auto it = LOG_CATEGORIES_BY_STR.find(str);
225 [ + + ]: 4447 : if (it != LOG_CATEGORIES_BY_STR.end()) {
226 : 4445 : flag = it->second;
227 : 4445 : return true;
228 : : }
229 : : return false;
230 : : }
231 : :
232 : 408189 : std::string BCLog::Logger::LogLevelToStr(BCLog::Level level)
233 : : {
234 [ + + + + : 408189 : switch (level) {
+ - ]
235 : 398361 : case BCLog::Level::Trace:
236 : 398361 : return "trace";
237 : 3439 : case BCLog::Level::Debug:
238 : 3439 : return "debug";
239 : 1733 : case BCLog::Level::Info:
240 : 1733 : return "info";
241 : 1076 : case BCLog::Level::Warning:
242 : 1076 : return "warning";
243 : 3580 : case BCLog::Level::Error:
244 : 3580 : return "error";
245 : : }
246 : 0 : assert(false);
247 : : }
248 : :
249 : 5046084 : static std::string LogCategoryToStr(BCLog::LogFlags category)
250 : : {
251 [ - + ]: 5046084 : if (category == BCLog::ALL) {
252 : 0 : return "all";
253 : : }
254 : 5046084 : auto it = LOG_CATEGORIES_BY_FLAG.find(category);
255 [ - + ]: 5046084 : assert(it != LOG_CATEGORIES_BY_FLAG.end());
256 : 5046084 : return it->second;
257 : : }
258 : :
259 : 1677 : static std::optional<BCLog::Level> GetLogLevel(std::string_view level_str)
260 : : {
261 [ + + ]: 1677 : if (level_str == "trace") {
262 : 1671 : return BCLog::Level::Trace;
263 [ + + ]: 6 : } else if (level_str == "debug") {
264 : 2 : return BCLog::Level::Debug;
265 [ + + ]: 4 : } else if (level_str == "info") {
266 : 2 : return BCLog::Level::Info;
267 [ - + ]: 2 : } else if (level_str == "warning") {
268 : 0 : return BCLog::Level::Warning;
269 [ - + ]: 2 : } else if (level_str == "error") {
270 : 0 : return BCLog::Level::Error;
271 : : } else {
272 : 2 : return std::nullopt;
273 : : }
274 : : }
275 : :
276 : 5646 : std::vector<LogCategory> BCLog::Logger::LogCategoriesList() const
277 : : {
278 : 5646 : std::vector<LogCategory> ret;
279 [ + - ]: 5646 : ret.reserve(LOG_CATEGORIES_BY_STR.size());
280 [ + - + + ]: 163734 : for (const auto& [category, flag] : LOG_CATEGORIES_BY_STR) {
281 [ + - + - : 158088 : ret.push_back(LogCategory{.category = category, .active = WillLogCategory(flag)});
+ - ]
282 : : }
283 : 5646 : return ret;
284 : 0 : }
285 : :
286 : : /** Log severity levels that can be selected by the user. */
287 : : static constexpr std::array<BCLog::Level, 3> LogLevelsList()
288 : : {
289 : : return {BCLog::Level::Info, BCLog::Level::Debug, BCLog::Level::Trace};
290 : : }
291 : :
292 : 1720 : std::string BCLog::Logger::LogLevelsString() const
293 : : {
294 : 1720 : const auto& levels = LogLevelsList();
295 [ + - + - ]: 8600 : return Join(std::vector<BCLog::Level>{levels.begin(), levels.end()}, ", ", [](BCLog::Level level) { return LogLevelToStr(level); });
296 : : }
297 : :
298 : 5454775 : std::string BCLog::Logger::LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
299 : : {
300 [ + + ]: 5454775 : std::string strStamped;
301 : :
302 [ + + ]: 5454775 : if (!m_log_timestamps)
303 : : return strStamped;
304 : :
305 : 5450619 : const auto now_seconds{std::chrono::time_point_cast<std::chrono::seconds>(now)};
306 [ + - ]: 5450619 : strStamped = FormatISO8601DateTime(TicksSinceEpoch<std::chrono::seconds>(now_seconds));
307 [ + - + - ]: 5450619 : if (m_log_time_micros && !strStamped.empty()) {
308 : 5450619 : strStamped.pop_back();
309 [ + - ]: 10901238 : strStamped += strprintf(".%06dZ", Ticks<std::chrono::microseconds>(now - now_seconds));
310 : : }
311 [ + + ]: 5450619 : if (mocktime > 0s) {
312 [ + - + - : 2731644 : strStamped += " (mocktime: " + FormatISO8601DateTime(count_seconds(mocktime)) + ")";
+ - ]
313 : : }
314 [ + - ]: 10905394 : strStamped += ' ';
315 : :
316 : : return strStamped;
317 : 0 : }
318 : :
319 : : namespace BCLog {
320 : : /** Belts and suspenders: make sure outgoing log messages don't contain
321 : : * potentially suspicious characters, such as terminal control codes.
322 : : *
323 : : * This escapes control characters except newline ('\n') in C syntax.
324 : : * It escapes instead of removes them to still allow for troubleshooting
325 : : * issues where they accidentally end up in strings.
326 : : */
327 : 5474325 : std::string LogEscapeMessage(std::string_view str) {
328 : 5474325 : std::string ret;
329 [ + + ]: 488790657 : for (char ch_in : str) {
330 : 483316332 : uint8_t ch = (uint8_t)ch_in;
331 [ + + + + ]: 483316332 : if ((ch >= 32 || ch == '\n') && ch != '\x7f') {
332 [ + - ]: 966625003 : ret += ch_in;
333 : : } else {
334 [ + - ]: 15322 : ret += strprintf("\\x%02x", ch);
335 : : }
336 : : }
337 : 5474325 : return ret;
338 : 0 : }
339 : : } // namespace BCLog
340 : :
341 : 5454775 : std::string BCLog::Logger::GetLogPrefix(BCLog::LogFlags category, BCLog::Level level) const
342 : : {
343 [ + + ]: 5454775 : if (category == LogFlags::NONE) category = LogFlags::ALL;
344 : :
345 [ + - + + ]: 5454775 : const bool has_category{m_always_print_category_level || category != LogFlags::ALL};
346 : :
347 : : // If there is no category, Info is implied
348 [ + + ]: 5454775 : if (!has_category && level == Level::Info) return {};
349 : :
350 : 5049702 : std::string s{"["};
351 [ + + ]: 5049702 : if (has_category) {
352 [ + - ]: 10092168 : s += LogCategoryToStr(category);
353 : : }
354 : :
355 [ + - + + ]: 5049702 : if (m_always_print_category_level || !has_category || level != Level::Debug) {
356 : : // If there is a category, Debug is implied, so don't add the level
357 : :
358 : : // Only add separator if we have a category
359 [ + + + - ]: 401312 : if (has_category) s += ":";
360 [ + - ]: 802624 : s += Logger::LogLevelToStr(level);
361 : : }
362 : :
363 [ + - ]: 5049702 : s += "] ";
364 : 5049702 : return s;
365 : 5049702 : }
366 : :
367 : 26060 : static size_t MemUsage(const BCLog::Logger::BufferedLog& buflog)
368 : : {
369 : 26060 : return memusage::DynamicUsage(buflog.str) +
370 : 26060 : memusage::DynamicUsage(buflog.threadname) +
371 : 26060 : memusage::MallocUsage(sizeof(memusage::list_node<BCLog::Logger::BufferedLog>));
372 : : }
373 : :
374 : 1048 : BCLog::LogRateLimiter::LogRateLimiter(
375 : : SchedulerFunction scheduler_func,
376 : : uint64_t max_bytes,
377 : 1048 : std::chrono::seconds reset_window) : m_max_bytes{max_bytes}, m_reset_window{reset_window}
378 : : {
379 [ + - ]: 1054 : scheduler_func([this] { Reset(); }, reset_window);
380 : 1048 : }
381 : :
382 : 209877 : BCLog::LogRateLimiter::Status BCLog::LogRateLimiter::Consume(
383 : : const std::source_location& source_loc,
384 : : const std::string& str)
385 : : {
386 : 209877 : StdLockGuard scoped_lock(m_mutex);
387 [ + - ]: 209877 : auto& counter{m_source_locations.try_emplace(source_loc, m_max_bytes).first->second};
388 [ + + ]: 209877 : Status status{counter.GetDroppedBytes() > 0 ? Status::STILL_SUPPRESSED : Status::UNSUPPRESSED};
389 : :
390 [ + - + + : 209877 : if (!counter.Consume(str.size()) && status == Status::UNSUPPRESSED) {
+ + ]
391 : 10 : status = Status::NEWLY_SUPPRESSED;
392 : 10 : m_suppression_active = true;
393 : : }
394 : :
395 : 209877 : return status;
396 : 209877 : }
397 : :
398 : 5454775 : void BCLog::Logger::FormatLogStrInPlace(std::string& str, BCLog::LogFlags category, BCLog::Level level, const std::source_location& source_loc, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const
399 : : {
400 [ + - ]: 5493217 : if (!str.ends_with('\n')) str.push_back('\n');
401 : :
402 [ + - ]: 5454775 : str.insert(0, GetLogPrefix(category, level));
403 : :
404 [ + + ]: 5454775 : if (m_log_sourcelocations) {
405 [ + - + - : 27253130 : str.insert(0, strprintf("[%s:%d] [%s] ", RemovePrefixView(source_loc.file_name(), "./"), source_loc.line(), source_loc.function_name()));
+ - + - ]
406 : : }
407 : :
408 [ + + ]: 5454775 : if (m_log_threadnames) {
409 [ + + + - ]: 10901238 : str.insert(0, strprintf("[%s] ", (threadname.empty() ? "unknown" : threadname)));
410 : : }
411 : :
412 [ + - ]: 5454775 : str.insert(0, LogTimestampStr(now, mocktime));
413 : 5454775 : }
414 : :
415 : 5474313 : void BCLog::Logger::LogPrintStr(std::string_view str, std::source_location&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
416 : : {
417 : 5474313 : StdLockGuard scoped_lock(m_cs);
418 [ + - ]: 5474313 : return LogPrintStr_(str, std::move(source_loc), category, level, should_ratelimit);
419 : 5474313 : }
420 : :
421 : : // NOLINTNEXTLINE(misc-no-recursion)
422 : 5474321 : void BCLog::Logger::LogPrintStr_(std::string_view str, std::source_location&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
423 : : {
424 : 5474321 : std::string str_prefixed = LogEscapeMessage(str);
425 : :
426 [ + + ]: 5474321 : if (m_buffering) {
427 : 26060 : {
428 : 26060 : BufferedLog buf{
429 : 26060 : .now = SystemClock::now(),
430 [ + - ]: 26060 : .mocktime = GetMockTime(),
431 : : .str = str_prefixed,
432 : : .threadname = util::ThreadGetInternalName(),
433 : : .source_loc = std::move(source_loc),
434 : : .category = category,
435 : : .level = level,
436 [ + - + - ]: 26060 : };
437 : 26060 : m_cur_buffer_memusage += MemUsage(buf);
438 [ + - ]: 26060 : m_msgs_before_open.push_back(std::move(buf));
439 : 0 : }
440 : :
441 [ - + ]: 26060 : while (m_cur_buffer_memusage > m_max_buffer_memusage) {
442 [ # # ]: 0 : if (m_msgs_before_open.empty()) {
443 : 0 : m_cur_buffer_memusage = 0;
444 : 0 : break;
445 : : }
446 : 0 : m_cur_buffer_memusage -= MemUsage(m_msgs_before_open.front());
447 : 0 : m_msgs_before_open.pop_front();
448 : 0 : ++m_buffer_lines_discarded;
449 : : }
450 : :
451 : 26060 : return;
452 : : }
453 : :
454 [ + - + - : 5448261 : FormatLogStrInPlace(str_prefixed, category, level, source_loc, util::ThreadGetInternalName(), SystemClock::now(), GetMockTime());
+ - ]
455 : 5448261 : bool ratelimit{false};
456 [ + + + + ]: 5448261 : if (should_ratelimit && m_limiter) {
457 [ + - ]: 209869 : auto status{m_limiter->Consume(source_loc, str_prefixed)};
458 [ + + ]: 209869 : if (status == BCLog::LogRateLimiter::Status::NEWLY_SUPPRESSED) {
459 : : // NOLINTNEXTLINE(misc-no-recursion)
460 [ + - ]: 16 : LogPrintStr_(strprintf(
461 : : "Excessive logging detected from %s:%d (%s): >%d bytes logged during "
462 : : "the last time window of %is. Suppressing logging to disk from this "
463 : : "source location until time window resets. Console logging "
464 : : "unaffected. Last log entry.\n",
465 [ + - + - : 24 : source_loc.file_name(), source_loc.line(), source_loc.function_name(),
+ - ]
466 [ + - ]: 8 : m_limiter->m_max_bytes,
467 : 8 : Ticks<std::chrono::seconds>(m_limiter->m_reset_window)),
468 [ + - ]: 8 : std::source_location::current(), LogFlags::ALL, Level::Warning, /*should_ratelimit=*/false); // with should_ratelimit=false, this cannot lead to infinite recursion
469 : : }
470 : 209869 : ratelimit = status == BCLog::LogRateLimiter::Status::STILL_SUPPRESSED;
471 : : // To avoid confusion caused by dropped log messages when debugging an issue,
472 : : // we prefix log lines with "[*]" when there are any suppressed source locations.
473 [ + + ]: 209869 : if (m_limiter->SuppressionsActive()) {
474 [ + - ]: 12952 : str_prefixed.insert(0, "[*] ");
475 : : }
476 : : }
477 : :
478 [ - + ]: 5448261 : if (m_print_to_console) {
479 : : // print to console
480 [ # # ]: 0 : fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
481 [ # # ]: 0 : fflush(stdout);
482 : : }
483 [ + + ]: 5747537 : for (const auto& cb : m_print_callbacks) {
484 [ + - ]: 299276 : cb(str_prefixed);
485 : : }
486 [ + - + + ]: 5448261 : if (m_print_to_file && !ratelimit) {
487 [ - + ]: 5437597 : assert(m_fileout != nullptr);
488 : :
489 : : // reopen the log file, if requested
490 [ + + ]: 5437597 : if (m_reopen_file) {
491 [ + - ]: 7 : m_reopen_file = false;
492 [ + - ]: 7 : FILE* new_fileout = fsbridge::fopen(m_file_path, "a");
493 [ + - ]: 7 : if (new_fileout) {
494 : 7 : setbuf(new_fileout, nullptr); // unbuffered
495 [ + - ]: 7 : fclose(m_fileout);
496 : 7 : m_fileout = new_fileout;
497 : : }
498 : : }
499 [ + - ]: 5437597 : FileWriteStr(str_prefixed, m_fileout);
500 : : }
501 : 5474321 : }
502 : :
503 : 0 : void BCLog::Logger::ShrinkDebugFile()
504 : : {
505 : : // Amount of debug.log to save at end when shrinking (must fit in memory)
506 : 0 : constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
507 : :
508 [ # # ]: 0 : assert(!m_file_path.empty());
509 : :
510 : : // Scroll debug.log if it's getting too big
511 : 0 : FILE* file = fsbridge::fopen(m_file_path, "r");
512 : :
513 : : // Special files (e.g. device nodes) may not have a size.
514 : 0 : size_t log_size = 0;
515 : 0 : try {
516 [ # # ]: 0 : log_size = fs::file_size(m_file_path);
517 [ - - ]: 0 : } catch (const fs::filesystem_error&) {}
518 : :
519 : : // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
520 : : // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
521 [ # # ]: 0 : if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
522 : : {
523 : : // Restart the file with some of the end
524 : 0 : std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
525 [ # # ]: 0 : if (fseek(file, -((long)vch.size()), SEEK_END)) {
526 [ # # ]: 0 : LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
527 [ # # ]: 0 : fclose(file);
528 : 0 : return;
529 : : }
530 [ # # ]: 0 : int nBytes = fread(vch.data(), 1, vch.size(), file);
531 [ # # ]: 0 : fclose(file);
532 : :
533 [ # # ]: 0 : file = fsbridge::fopen(m_file_path, "w");
534 [ # # ]: 0 : if (file)
535 : : {
536 [ # # ]: 0 : fwrite(vch.data(), 1, nBytes, file);
537 [ # # ]: 0 : fclose(file);
538 : : }
539 : 0 : }
540 [ # # ]: 0 : else if (file != nullptr)
541 : 0 : fclose(file);
542 : : }
543 : :
544 : 7 : void BCLog::LogRateLimiter::Reset()
545 : : {
546 [ + - ]: 7 : decltype(m_source_locations) source_locations;
547 : 7 : {
548 [ + - ]: 7 : StdLockGuard scoped_lock(m_mutex);
549 : 7 : source_locations.swap(m_source_locations);
550 : 7 : m_suppression_active = false;
551 : 7 : }
552 [ + + + + ]: 158 : for (const auto& [source_loc, counter] : source_locations) {
553 [ + + ]: 151 : uint64_t dropped_bytes{counter.GetDroppedBytes()};
554 [ + + ]: 151 : if (dropped_bytes == 0) continue;
555 [ + - + - : 12 : LogPrintLevel_(
+ - + - ]
556 : : LogFlags::ALL, Level::Info, /*should_ratelimit=*/false,
557 : : "Restarting logging from %s:%d (%s): %d bytes were dropped during the last %ss.\n",
558 : : source_loc.file_name(), source_loc.line(), source_loc.function_name(),
559 : : dropped_bytes, Ticks<std::chrono::seconds>(m_reset_window));
560 : : }
561 : 7 : }
562 : :
563 : 209880 : bool BCLog::LogLimitStats::Consume(uint64_t bytes)
564 : : {
565 [ + + ]: 209880 : if (bytes > m_available_bytes) {
566 : 10676 : m_dropped_bytes += bytes;
567 : 10676 : m_available_bytes = 0;
568 : 10676 : return false;
569 : : }
570 : :
571 : 199204 : m_available_bytes -= bytes;
572 : 199204 : return true;
573 : : }
574 : :
575 : 1672 : bool BCLog::Logger::SetLogLevel(std::string_view level_str)
576 : : {
577 : 1672 : const auto level = GetLogLevel(level_str);
578 [ + + + - ]: 1672 : if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
579 : 1671 : m_log_level = level.value();
580 : 1671 : return true;
581 : : }
582 : :
583 : 5 : bool BCLog::Logger::SetCategoryLogLevel(std::string_view category_str, std::string_view level_str)
584 : : {
585 : 5 : BCLog::LogFlags flag;
586 [ + - ]: 5 : if (!GetLogCategory(flag, category_str)) return false;
587 : :
588 : 5 : const auto level = GetLogLevel(level_str);
589 [ + + + - ]: 5 : if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
590 : :
591 : 4 : StdLockGuard scoped_lock(m_cs);
592 [ + - ]: 4 : m_category_log_levels[flag] = level.value();
593 : 4 : return true;
594 : 4 : }
|