Coverage Report

Created: 2026-10-07 13:27

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