Coverage Report

Created: 2026-07-14 18:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/bitcoin/src/logging.cpp
Line
Count
Source
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
BCLog::Logger& LogInstance()
27
102M
{
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
 * LogInfo, 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
102M
    static BCLog::Logger* g_logger{new BCLog::Logger()};
44
102M
    return *g_logger;
45
102M
}
46
47
bool fLogIPs = DEFAULT_LOGIPS;
48
49
static int FileWriteStr(std::string_view str, FILE *fp)
50
51.8M
{
51
51.8M
    return fwrite(str.data(), 1, str.size(), fp);
52
51.8M
}
53
54
bool BCLog::Logger::StartLogging()
55
27
{
56
27
    STDLOCK(m_cs);
57
58
27
    assert(m_buffering);
  Branch (58:5): [True: 27, False: 0]
59
27
    assert(m_fileout == nullptr);
  Branch (59:5): [True: 27, False: 0]
60
61
27
    if (m_print_to_file) {
  Branch (61:9): [True: 27, False: 0]
62
27
        assert(!m_file_path.empty());
  Branch (62:9): [True: 27, False: 0]
63
27
        m_fileout = fsbridge::fopen(m_file_path, "a");
64
27
        if (!m_fileout) {
  Branch (64:13): [True: 0, False: 27]
65
0
            return false;
66
0
        }
67
68
27
        setbuf(m_fileout, nullptr); // unbuffered
69
70
        // Add newlines to the logfile to distinguish this execution from the
71
        // last one.
72
27
        FileWriteStr("\n\n\n\n\n", m_fileout);
73
27
    }
74
75
    // dump buffered messages from before we opened the log
76
27
    m_buffering = false;
77
27
    if (m_buffer_lines_discarded > 0) {
  Branch (77:9): [True: 0, False: 27]
78
0
        LogPrint_({
79
0
            .category = BCLog::ALL,
80
0
            .level = Level::Info,
81
0
            .should_ratelimit = false,
82
0
            .source_loc = SourceLocation{__func__},
83
0
            .message = strprintf("Early logging buffer overflowed, %d log lines discarded.", m_buffer_lines_discarded),
84
0
        });
85
0
    }
86
270
    while (!m_msgs_before_open.empty()) {
  Branch (86:12): [True: 243, False: 27]
87
243
        const auto& buflog = m_msgs_before_open.front();
88
243
        std::string s{Format(buflog)};
89
243
        m_msgs_before_open.pop_front();
90
91
243
        if (m_print_to_file) FileWriteStr(s, m_fileout);
  Branch (91:13): [True: 243, False: 0]
92
243
        if (m_print_to_console) fwrite(s.data(), 1, s.size(), stdout);
  Branch (92:13): [True: 243, False: 0]
93
243
        for (const auto& cb : m_print_callbacks) {
  Branch (93:29): [True: 0, False: 243]
94
0
            cb(s);
95
0
        }
96
243
    }
97
27
    m_cur_buffer_memusage = 0;
98
27
    if (m_print_to_console) fflush(stdout);
  Branch (98:9): [True: 27, False: 0]
99
100
27
    return true;
101
27
}
102
103
void BCLog::Logger::DisconnectTestLogger()
104
0
{
105
0
    STDLOCK(m_cs);
106
0
    m_buffering = true;
107
0
    if (m_fileout != nullptr) fclose(m_fileout);
  Branch (107:9): [True: 0, False: 0]
108
0
    m_fileout = nullptr;
109
0
    m_print_callbacks.clear();
110
0
    m_max_buffer_memusage = DEFAULT_MAX_LOG_BUFFER;
111
0
    m_cur_buffer_memusage = 0;
112
0
    m_buffer_lines_discarded = 0;
113
0
    m_msgs_before_open.clear();
114
0
}
115
116
void BCLog::Logger::DisableLogging()
117
0
{
118
0
    {
119
0
        STDLOCK(m_cs);
120
0
        assert(m_buffering);
  Branch (120:9): [True: 0, False: 0]
121
0
        assert(m_print_callbacks.empty());
  Branch (121:9): [True: 0, False: 0]
122
0
    }
123
0
    m_print_to_file = false;
124
0
    m_print_to_console = false;
125
0
    StartLogging();
126
0
}
127
128
void BCLog::Logger::EnableCategory(BCLog::LogFlags flag)
129
27
{
130
27
    m_categories |= flag;
131
27
}
132
133
bool BCLog::Logger::EnableCategory(std::string_view str)
134
27
{
135
27
    if (const auto flag{GetLogCategory(str)}) {
  Branch (135:20): [True: 27, False: 0]
136
27
        EnableCategory(*flag);
137
27
        return true;
138
27
    }
139
0
    return false;
140
27
}
141
142
void BCLog::Logger::DisableCategory(BCLog::LogFlags flag)
143
54
{
144
54
    m_categories &= ~flag;
145
54
}
146
147
bool BCLog::Logger::DisableCategory(std::string_view str)
148
54
{
149
54
    if (const auto flag{GetLogCategory(str)}) {
  Branch (149:20): [True: 54, False: 0]
150
54
        DisableCategory(*flag);
151
54
        return true;
152
54
    }
153
0
    return false;
154
54
}
155
156
bool BCLog::Logger::WillLogCategory(BCLog::LogFlags category) const
157
51.0M
{
158
51.0M
    return (m_categories.load(std::memory_order_relaxed) & category) != 0;
159
51.0M
}
160
161
bool BCLog::Logger::WillLogCategoryLevel(BCLog::LogFlags category, BCLog::Level level) const
162
51.0M
{
163
    // Log messages at Info, Warning and Error level unconditionally, so that
164
    // important troubleshooting information doesn't get lost.
165
51.0M
    if (level >= BCLog::Level::Info) return true;
  Branch (165:9): [True: 0, False: 51.0M]
166
167
51.0M
    if (!WillLogCategory(category)) return false;
  Branch (167:9): [True: 831k, False: 50.1M]
168
169
50.1M
    STDLOCK(m_cs);
170
50.1M
    const auto it{m_category_log_levels.find(category)};
171
18.4E
    return level >= (it == m_category_log_levels.end() ? LogLevel() : it->second);
  Branch (171:22): [True: 50.2M, False: 18.4E]
172
51.0M
}
173
174
bool BCLog::Logger::DefaultShrinkDebugFile() const
175
27
{
176
27
    return m_categories == BCLog::NONE;
177
27
}
178
179
static const std::map<std::string, BCLog::LogFlags, std::less<>> LOG_CATEGORIES_BY_STR{
180
    {"net", BCLog::NET},
181
    {"tor", BCLog::TOR},
182
    {"mempool", BCLog::MEMPOOL},
183
    {"http", BCLog::HTTP},
184
    {"bench", BCLog::BENCH},
185
    {"zmq", BCLog::ZMQ},
186
    {"walletdb", BCLog::WALLETDB},
187
    {"rpc", BCLog::RPC},
188
    {"estimatefee", BCLog::ESTIMATEFEE},
189
    {"addrman", BCLog::ADDRMAN},
190
    {"selectcoins", BCLog::SELECTCOINS},
191
    {"reindex", BCLog::REINDEX},
192
    {"cmpctblock", BCLog::CMPCTBLOCK},
193
    {"rand", BCLog::RAND},
194
    {"prune", BCLog::PRUNE},
195
    {"proxy", BCLog::PROXY},
196
    {"mempoolrej", BCLog::MEMPOOLREJ},
197
    {"coindb", BCLog::COINDB},
198
    {"qt", BCLog::QT},
199
    {"leveldb", BCLog::LEVELDB},
200
    {"validation", BCLog::VALIDATION},
201
    {"i2p", BCLog::I2P},
202
    {"ipc", BCLog::IPC},
203
#ifdef DEBUG_LOCKCONTENTION
204
    {"lock", BCLog::LOCK},
205
#endif
206
    {"blockstorage", BCLog::BLOCKSTORAGE},
207
    {"txreconciliation", BCLog::TXRECONCILIATION},
208
    {"scan", BCLog::SCAN},
209
    {"txpackages", BCLog::TXPACKAGES},
210
    {"kernel", BCLog::KERNEL},
211
    {"privatebroadcast", BCLog::PRIVBROADCAST},
212
};
213
214
static const std::unordered_map<BCLog::LogFlags, std::string> LOG_CATEGORIES_BY_FLAG{
215
    // Swap keys and values from LOG_CATEGORIES_BY_STR.
216
27
    [](const auto& in) {
217
27
        std::unordered_map<BCLog::LogFlags, std::string> out;
218
783
        for (const auto& [k, v] : in) {
  Branch (218:33): [True: 783, False: 27]
219
783
            const bool inserted{out.emplace(v, k).second};
220
783
            assert(inserted);
  Branch (220:13): [True: 783, False: 0]
221
783
        }
222
27
        return out;
223
27
    }(LOG_CATEGORIES_BY_STR)
224
};
225
226
std::optional<BCLog::LogFlags> BCLog::Logger::GetLogCategory(std::string_view str)
227
81
{
228
81
    if (str.empty() || str == "1" || str == "all") {
  Branch (228:9): [True: 27, False: 54]
  Branch (228:24): [True: 0, False: 54]
  Branch (228:38): [True: 0, False: 54]
229
27
        return BCLog::ALL;
230
27
    }
231
54
    auto it = LOG_CATEGORIES_BY_STR.find(str);
232
54
    if (it != LOG_CATEGORIES_BY_STR.end()) {
  Branch (232:9): [True: 27, False: 27]
233
27
        return it->second;
234
27
    }
235
27
    if (str == "libevent") {
  Branch (235:9): [True: 27, False: 0]
236
27
       LogWarning("The logging category `%s` is deprecated, does nothing, and will be removed in a future version", str);
237
27
       return BCLog::NONE;
238
27
    }
239
0
    return std::nullopt;
240
27
}
241
242
std::string BCLog::Logger::LogLevelToStr(BCLog::Level level)
243
27.3k
{
244
27.3k
    switch (level) {
  Branch (244:13): [True: 0, False: 27.3k]
245
27
    case BCLog::Level::Trace:
  Branch (245:5): [True: 27, False: 27.3k]
246
27
        return "trace";
247
54
    case BCLog::Level::Debug:
  Branch (247:5): [True: 54, False: 27.3k]
248
54
        return "debug";
249
27
    case BCLog::Level::Info:
  Branch (249:5): [True: 27, False: 27.3k]
250
27
        return "info";
251
300
    case BCLog::Level::Warning:
  Branch (251:5): [True: 300, False: 27.0k]
252
300
        return "warning";
253
26.9k
    case BCLog::Level::Error:
  Branch (253:5): [True: 26.9k, False: 408]
254
26.9k
        return "error";
255
27.3k
    }
256
27.3k
    assert(false);
  Branch (256:5): [Folded - Ignored]
257
0
}
258
259
static std::string LogCategoryToStr(BCLog::LogFlags category)
260
49.2M
{
261
49.2M
    if (category == BCLog::ALL) {
  Branch (261:9): [True: 0, False: 49.2M]
262
0
        return "all";
263
0
    }
264
49.2M
    auto it = LOG_CATEGORIES_BY_FLAG.find(category);
265
49.2M
    assert(it != LOG_CATEGORIES_BY_FLAG.end());
  Branch (265:5): [True: 49.2M, False: 18.4E]
266
49.2M
    return it->second;
267
49.2M
}
268
269
static std::optional<BCLog::Level> GetLogLevel(std::string_view level_str)
270
0
{
271
0
    if (level_str == "trace") {
  Branch (271:9): [True: 0, False: 0]
272
0
        return BCLog::Level::Trace;
273
0
    } else if (level_str == "debug") {
  Branch (273:16): [True: 0, False: 0]
274
0
        return BCLog::Level::Debug;
275
0
    } else if (level_str == "info") {
  Branch (275:16): [True: 0, False: 0]
276
0
        return BCLog::Level::Info;
277
0
    } else if (level_str == "warning") {
  Branch (277:16): [True: 0, False: 0]
278
0
        return BCLog::Level::Warning;
279
0
    } else if (level_str == "error") {
  Branch (279:16): [True: 0, False: 0]
280
0
        return BCLog::Level::Error;
281
0
    } else {
282
0
        return std::nullopt;
283
0
    }
284
0
}
285
286
std::vector<LogCategory> BCLog::Logger::LogCategoriesList() const
287
108
{
288
108
    std::vector<LogCategory> ret;
289
108
    ret.reserve(LOG_CATEGORIES_BY_STR.size());
290
3.13k
    for (const auto& [category, flag] : LOG_CATEGORIES_BY_STR) {
  Branch (290:39): [True: 3.13k, False: 108]
291
3.13k
        ret.push_back(LogCategory{.category = category, .active = WillLogCategory(flag)});
292
3.13k
    }
293
108
    return ret;
294
108
}
295
296
/** Log severity levels that can be selected by the user. */
297
static constexpr std::array<BCLog::Level, 3> LogLevelsList()
298
27
{
299
27
    return {BCLog::Level::Info, BCLog::Level::Debug, BCLog::Level::Trace};
300
27
}
301
302
std::string BCLog::Logger::LogLevelsString() const
303
27
{
304
27
    const auto& levels = LogLevelsList();
305
81
    return Join(std::vector<BCLog::Level>{levels.begin(), levels.end()}, ", ", [](BCLog::Level level) { return LogLevelToStr(level); });
306
27
}
307
308
std::string BCLog::Logger::LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
309
51.8M
{
310
51.8M
    std::string strStamped;
311
312
51.8M
    if (!m_log_timestamps)
  Branch (312:9): [True: 0, False: 51.8M]
313
0
        return strStamped;
314
315
51.8M
    const auto now_seconds{std::chrono::time_point_cast<std::chrono::seconds>(now)};
316
51.8M
    strStamped = FormatISO8601DateTime(TicksSinceEpoch<std::chrono::seconds>(now_seconds));
317
51.8M
    if (m_log_time_micros && !strStamped.empty()) {
  Branch (317:9): [True: 0, False: 51.8M]
  Branch (317:30): [True: 0, False: 0]
318
0
        strStamped.pop_back();
319
0
        strStamped += strprintf(".%06dZ", Ticks<std::chrono::microseconds>(now - now_seconds));
320
0
    }
321
51.8M
    if (mocktime > 0s) {
  Branch (321:9): [True: 51.8M, False: 4.96k]
322
51.8M
        strStamped += " (mocktime: " + FormatISO8601DateTime(count_seconds(mocktime)) + ")";
323
51.8M
    }
324
51.8M
    strStamped += ' ';
325
326
51.8M
    return strStamped;
327
51.8M
}
328
329
namespace BCLog {
330
    /** Belts and suspenders: make sure outgoing log messages don't contain
331
     * potentially suspicious characters, such as terminal control codes.
332
     *
333
     * This escapes control characters except newline ('\n') in C syntax.
334
     * It escapes instead of removes them to still allow for troubleshooting
335
     * issues where they accidentally end up in strings.
336
     */
337
51.9M
    std::string LogEscapeMessage(std::string_view str) {
338
51.9M
        std::string ret;
339
3.09G
        for (char ch_in : str) {
  Branch (339:25): [True: 3.09G, False: 51.9M]
340
3.09G
            uint8_t ch = (uint8_t)ch_in;
341
3.09G
            if ((ch >= 32 || ch == '\n') && ch != '\x7f') {
  Branch (341:18): [True: 3.05G, False: 40.2M]
  Branch (341:30): [True: 40.2M, False: 0]
  Branch (341:45): [True: 3.08G, False: 0]
342
3.08G
                ret += ch_in;
343
3.08G
            } else {
344
4.21M
                ret += strprintf("\\x%02x", ch);
345
4.21M
            }
346
3.09G
        }
347
51.9M
        return ret;
348
51.9M
    }
349
} // namespace BCLog
350
351
std::string BCLog::Logger::GetLogPrefix(BCLog::LogFlags category, BCLog::Level level) const
352
51.8M
{
353
51.8M
    if (category == LogFlags::NONE) category = LogFlags::ALL;
  Branch (353:9): [True: 0, False: 51.8M]
354
355
51.8M
    const bool has_category{m_always_print_category_level || category != LogFlags::ALL};
  Branch (355:29): [True: 0, False: 51.8M]
  Branch (355:62): [True: 49.2M, False: 2.66M]
356
357
    // If there is no category, Info is implied
358
51.8M
    if (!has_category && level == Level::Info) return {};
  Branch (358:9): [True: 2.66M, False: 49.2M]
  Branch (358:26): [True: 2.63M, False: 27.2k]
359
360
49.2M
    std::string s{"["};
361
49.2M
    if (has_category) {
  Branch (361:9): [True: 49.2M, False: 27.2k]
362
49.2M
        s += LogCategoryToStr(category);
363
49.2M
    }
364
365
49.2M
    if (m_always_print_category_level || !has_category || level != Level::Debug) {
  Branch (365:9): [True: 18.4E, False: 49.2M]
  Branch (365:42): [True: 27.2k, False: 49.2M]
  Branch (365:59): [True: 0, False: 49.2M]
366
        // If there is a category, Debug is implied, so don't add the level
367
368
        // Only add separator if we have a category
369
27.2k
        if (has_category) s += ":";
  Branch (369:13): [True: 0, False: 27.2k]
370
27.2k
        s += Logger::LogLevelToStr(level);
371
27.2k
    }
372
373
49.2M
    s += "] ";
374
49.2M
    return s;
375
51.8M
}
376
377
static size_t MemUsage(const util::log::Entry& log)
378
243
{
379
243
    return memusage::DynamicUsage(log.message) +
380
243
           memusage::DynamicUsage(log.thread_name) +
381
243
           memusage::MallocUsage(sizeof(memusage::list_node<util::log::Entry>));
382
243
}
383
384
BCLog::LogRateLimiter::LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window)
385
27
    : m_max_bytes{max_bytes}, m_reset_window{reset_window} {}
386
387
std::shared_ptr<BCLog::LogRateLimiter> BCLog::LogRateLimiter::Create(
388
    SchedulerFunction&& scheduler_func, uint64_t max_bytes, std::chrono::seconds reset_window)
389
27
{
390
27
    auto limiter{std::shared_ptr<LogRateLimiter>(new LogRateLimiter(max_bytes, reset_window))};
391
27
    std::weak_ptr<LogRateLimiter> weak_limiter{limiter};
392
62.1k
    auto reset = [weak_limiter] {
393
62.1k
        if (auto shared_limiter{weak_limiter.lock()}) shared_limiter->Reset();
  Branch (393:18): [True: 62.1k, False: 0]
394
62.1k
    };
395
27
    scheduler_func(reset, limiter->m_reset_window);
396
27
    return limiter;
397
27
}
398
399
BCLog::LogRateLimiter::Status BCLog::LogRateLimiter::Consume(
400
    const SourceLocation& source_loc,
401
    const std::string& str)
402
2.59M
{
403
2.59M
    STDLOCK(m_mutex);
404
2.59M
    auto& stats{m_source_locations.try_emplace(source_loc, m_max_bytes).first->second};
405
2.59M
    Status status{stats.m_dropped_bytes > 0 ? Status::STILL_SUPPRESSED : Status::UNSUPPRESSED};
  Branch (405:19): [True: 0, False: 2.59M]
406
407
2.59M
    if (!stats.Consume(str.size()) && status == Status::UNSUPPRESSED) {
  Branch (407:9): [True: 0, False: 2.59M]
  Branch (407:39): [True: 0, False: 0]
408
0
        status = Status::NEWLY_SUPPRESSED;
409
0
        m_suppression_active = true;
410
0
    }
411
412
2.59M
    return status;
413
2.59M
}
414
415
std::string BCLog::Logger::Format(const util::log::Entry& entry) const
416
51.8M
{
417
51.8M
    std::string result{LogTimestampStr(entry.timestamp, entry.mocktime)};
418
419
51.8M
    if (m_log_threadnames) {
  Branch (419:9): [True: 0, False: 51.8M]
420
0
        result += strprintf("[%s] ", (entry.thread_name.empty() ? "unknown" : entry.thread_name));
  Branch (420:39): [True: 0, False: 0]
421
0
    }
422
423
51.8M
    if (m_log_sourcelocations) {
  Branch (423:9): [True: 0, False: 51.8M]
424
0
        result += strprintf("[%s:%d] [%s] ", RemovePrefixView(entry.source_loc.file_name(), "./"), entry.source_loc.line(), entry.source_loc.function_name_short());
425
0
    }
426
427
51.8M
    result += GetLogPrefix(static_cast<LogFlags>(entry.category), entry.level);
428
51.8M
    result += LogEscapeMessage(entry.message);
429
430
51.8M
    if (!result.ends_with('\n')) result += '\n';
  Branch (430:9): [True: 11.6M, False: 40.2M]
431
51.8M
    return result;
432
51.8M
}
433
434
void BCLog::Logger::LogPrint(util::log::Entry entry)
435
51.8M
{
436
51.8M
    STDLOCK(m_cs);
437
51.8M
    return LogPrint_(std::move(entry));
438
51.8M
}
439
440
// NOLINTNEXTLINE(misc-no-recursion)
441
void BCLog::Logger::LogPrint_(util::log::Entry entry)
442
51.8M
{
443
51.8M
    if (m_buffering) {
  Branch (443:9): [True: 243, False: 51.8M]
444
243
        {
445
243
            m_cur_buffer_memusage += MemUsage(entry);
446
243
            m_msgs_before_open.push_back(std::move(entry));
447
243
        }
448
449
243
        while (m_cur_buffer_memusage > m_max_buffer_memusage) {
  Branch (449:16): [True: 0, False: 243]
450
0
            if (m_msgs_before_open.empty()) {
  Branch (450:17): [True: 0, False: 0]
451
0
                m_cur_buffer_memusage = 0;
452
0
                break;
453
0
            }
454
0
            m_cur_buffer_memusage -= MemUsage(m_msgs_before_open.front());
455
0
            m_msgs_before_open.pop_front();
456
0
            ++m_buffer_lines_discarded;
457
0
        }
458
459
243
        return;
460
243
    }
461
462
51.8M
    std::string str_prefixed{Format(entry)};
463
51.8M
    bool ratelimit{false};
464
51.8M
    if (entry.should_ratelimit && m_limiter) {
  Branch (464:9): [True: 2.59M, False: 49.2M]
  Branch (464:35): [True: 2.59M, False: 783]
465
2.59M
        auto status{m_limiter->Consume(entry.source_loc, str_prefixed)};
466
2.59M
        if (status == LogRateLimiter::Status::NEWLY_SUPPRESSED) {
  Branch (466:13): [True: 0, False: 2.59M]
467
            // NOLINTNEXTLINE(misc-no-recursion)
468
0
            LogPrint_({
469
0
                .category = LogFlags::ALL,
470
0
                .level = Level::Warning,
471
0
                .should_ratelimit = false, // with should_ratelimit=false, this cannot lead to infinite recursion
472
0
                .source_loc = SourceLocation{__func__},
473
0
                .message = strprintf(
474
0
                    "Excessive logging detected from %s:%d (%s): >%d bytes logged during "
475
0
                    "the last time window of %is. Suppressing logging to disk from this "
476
0
                    "source location until time window resets. Console logging "
477
0
                    "unaffected. Last log entry.",
478
0
                    entry.source_loc.file_name(), entry.source_loc.line(), entry.source_loc.function_name_short(),
479
0
                    m_limiter->m_max_bytes,
480
0
                    Ticks<std::chrono::seconds>(m_limiter->m_reset_window)),
481
0
            });
482
2.59M
        } else if (status == LogRateLimiter::Status::STILL_SUPPRESSED) {
  Branch (482:20): [True: 0, False: 2.59M]
483
0
            ratelimit = true;
484
0
        }
485
2.59M
    }
486
487
    // To avoid confusion caused by dropped log messages when debugging an issue,
488
    // we prefix log lines with "[*]" when there are any suppressed source locations.
489
51.8M
    if (m_limiter && m_limiter->SuppressionsActive()) {
  Branch (489:9): [True: 51.8M, False: 79]
  Branch (489:22): [True: 0, False: 51.8M]
490
0
        str_prefixed.insert(0, "[*] ");
491
0
    }
492
493
51.8M
    if (m_print_to_console) {
  Branch (493:9): [True: 51.8M, False: 18.4E]
494
        // print to console
495
51.8M
        fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
496
51.8M
        fflush(stdout);
497
51.8M
    }
498
51.8M
    for (const auto& cb : m_print_callbacks) {
  Branch (498:25): [True: 0, False: 51.8M]
499
0
        cb(str_prefixed);
500
0
    }
501
51.8M
    if (m_print_to_file && !ratelimit) {
  Branch (501:9): [True: 51.8M, False: 18.4E]
  Branch (501:28): [True: 51.8M, False: 0]
502
51.8M
        assert(m_fileout != nullptr);
  Branch (502:9): [True: 51.8M, False: 0]
503
504
        // reopen the log file, if requested
505
51.8M
        if (m_reopen_file) {
  Branch (505:13): [True: 0, False: 51.8M]
506
0
            m_reopen_file = false;
507
0
            FILE* new_fileout = fsbridge::fopen(m_file_path, "a");
508
0
            if (new_fileout) {
  Branch (508:17): [True: 0, False: 0]
509
0
                setbuf(new_fileout, nullptr); // unbuffered
510
0
                fclose(m_fileout);
511
0
                m_fileout = new_fileout;
512
0
            }
513
0
        }
514
51.8M
        FileWriteStr(str_prefixed, m_fileout);
515
51.8M
    }
516
51.8M
}
517
518
void BCLog::Logger::ShrinkDebugFile()
519
0
{
520
0
    STDLOCK(m_cs);
521
522
    // Amount of debug.log to save at end when shrinking (must fit in memory)
523
0
    constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
524
525
0
    assert(!m_file_path.empty());
  Branch (525:5): [True: 0, False: 0]
526
527
    // Scroll debug.log if it's getting too big
528
0
    FILE* file = fsbridge::fopen(m_file_path, "r");
529
530
    // Special files (e.g. device nodes) may not have a size.
531
0
    size_t log_size = 0;
532
0
    try {
533
0
        log_size = fs::file_size(m_file_path);
534
0
    } catch (const fs::filesystem_error&) {}
535
536
    // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
537
    // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
538
0
    if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
  Branch (538:9): [True: 0, False: 0]
  Branch (538:17): [True: 0, False: 0]
539
0
    {
540
        // Restart the file with some of the end
541
0
        std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
542
0
        if (fseek(file, -((long)vch.size()), SEEK_END)) {
  Branch (542:13): [True: 0, False: 0]
543
            // LogWarning, except with m_cs held
544
0
            LogPrint_({
545
0
                .category = BCLog::ALL,
546
0
                .level = Level::Warning,
547
0
                .should_ratelimit = true,
548
0
                .source_loc = SourceLocation{__func__},
549
0
                .message = "Failed to shrink debug log file: fseek(...) failed",
550
0
            });
551
0
            fclose(file);
552
0
            return;
553
0
        }
554
0
        int nBytes = fread(vch.data(), 1, vch.size(), file);
555
0
        fclose(file);
556
557
0
        file = fsbridge::fopen(m_file_path, "w");
558
0
        if (file)
  Branch (558:13): [True: 0, False: 0]
559
0
        {
560
0
            fwrite(vch.data(), 1, nBytes, file);
561
0
            fclose(file);
562
0
        }
563
0
    }
564
0
    else if (file != nullptr)
  Branch (564:14): [True: 0, False: 0]
565
0
        fclose(file);
566
0
}
567
568
void BCLog::LogRateLimiter::Reset()
569
62.1k
{
570
62.1k
    decltype(m_source_locations) source_locations;
571
62.1k
    {
572
62.1k
        STDLOCK(m_mutex);
573
62.1k
        source_locations.swap(m_source_locations);
574
62.1k
        m_suppression_active = false;
575
62.1k
    }
576
1.26M
    for (const auto& [source_loc, stats] : source_locations) {
  Branch (576:42): [True: 1.26M, False: 62.1k]
577
1.26M
        if (stats.m_dropped_bytes == 0) continue;
  Branch (577:13): [True: 1.26M, False: 0]
578
0
        LogWarning(util::log::NO_RATE_LIMIT,
579
0
            "Restarting logging from %s:%d (%s): %d bytes were dropped during the last %ss.",
580
0
            source_loc.file_name(), source_loc.line(), source_loc.function_name_short(),
581
0
            stats.m_dropped_bytes, Ticks<std::chrono::seconds>(m_reset_window));
582
0
    }
583
62.1k
}
584
585
bool BCLog::LogRateLimiter::Stats::Consume(uint64_t bytes)
586
2.59M
{
587
2.59M
    if (bytes > m_available_bytes) {
  Branch (587:9): [True: 0, False: 2.59M]
588
0
        m_dropped_bytes += bytes;
589
0
        m_available_bytes = 0;
590
0
        return false;
591
0
    }
592
593
2.59M
    m_available_bytes -= bytes;
594
2.59M
    return true;
595
2.59M
}
596
597
bool BCLog::Logger::SetLogLevel(std::string_view level_str)
598
0
{
599
0
    const auto level = GetLogLevel(level_str);
600
0
    if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
  Branch (600:9): [True: 0, False: 0]
  Branch (600:31): [True: 0, False: 0]
601
0
    m_log_level = level.value();
602
0
    return true;
603
0
}
604
605
bool BCLog::Logger::SetCategoryLogLevel(std::string_view category_str, std::string_view level_str)
606
0
{
607
0
    const auto flag{GetLogCategory(category_str)};
608
0
    if (!flag) return false;
  Branch (608:9): [True: 0, False: 0]
609
610
0
    const auto level = GetLogLevel(level_str);
611
0
    if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
  Branch (611:9): [True: 0, False: 0]
  Branch (611:31): [True: 0, False: 0]
612
0
    if (*flag == BCLog::NONE) return true;
  Branch (612:9): [True: 0, False: 0]
613
614
0
    STDLOCK(m_cs);
615
0
    m_category_log_levels[*flag] = level.value();
616
0
    return true;
617
0
}
618
619
bool util::log::ShouldDebugLog(Category category)
620
51.0M
{
621
51.0M
    return LogInstance().WillLogCategoryLevel(static_cast<BCLog::LogFlags>(category), util::log::Level::Debug);
622
51.0M
}
623
624
bool util::log::ShouldTraceLog(Category category)
625
0
{
626
0
    return LogInstance().WillLogCategoryLevel(static_cast<BCLog::LogFlags>(category), util::log::Level::Trace);
627
0
}
628
629
void util::log::Log(util::log::Entry entry)
630
51.8M
{
631
51.8M
    BCLog::Logger& logger{LogInstance()};
632
51.8M
    if (logger.Enabled()) {
  Branch (632:9): [True: 51.8M, False: 23.6k]
633
51.8M
        logger.LogPrint(std::move(entry));
634
51.8M
    }
635
51.8M
}