LCOV - code coverage report
Current view: top level - src/test - logging_tests.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 99.0 % 305 302
Test Date: 2026-11-27 06:02:19 Functions: 100.0 % 33 33
Branches: 50.9 % 1453 740

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2019-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <init/common.h>
       6                 :             : #include <logging.h>
       7                 :             : #include <logging/timer.h>
       8                 :             : #include <scheduler.h>
       9                 :             : #include <test/util/common.h>
      10                 :             : #include <test/util/logging.h>
      11                 :             : #include <test/util/setup_common.h>
      12                 :             : #include <tinyformat.h>
      13                 :             : #include <util/check.h>
      14                 :             : #include <util/fs.h>
      15                 :             : #include <util/fs_helpers.h>
      16                 :             : #include <util/string.h>
      17                 :             : 
      18                 :             : #include <boost/test/unit_test.hpp>
      19                 :             : 
      20                 :             : #include <chrono>
      21                 :             : #include <fstream>
      22                 :             : #include <future>
      23                 :             : #include <ios>
      24                 :             : #include <iostream>
      25                 :             : #include <source_location>
      26                 :             : #include <string>
      27                 :             : #include <type_traits>
      28                 :             : #include <unordered_map>
      29                 :             : #include <utility>
      30                 :             : #include <vector>
      31                 :             : 
      32                 :             : using util::SplitString;
      33                 :             : using util::TrimString;
      34                 :             : 
      35                 :             : /* defined in logging.cpp */
      36                 :             : namespace BCLog {
      37                 :             :     std::string LogEscapeMessage(std::string_view str);
      38                 :             : }
      39                 :             : 
      40                 :             : template <auto str>
      41                 :             : concept IsLogFormatString = requires { typename std::bool_constant<(util::log::FormatString<0>{str()}, true)>; };
      42                 :             : 
      43                 :             : static_assert(IsLogFormatString<[] { return "format string without a trailing newline"; }>);
      44                 :             : static_assert(!IsLogFormatString<[] { return "format string ending in a newline\n"; }>);
      45                 :             : 
      46                 :             : BOOST_FIXTURE_TEST_SUITE(logging_tests, BasicTestingSetup)
      47                 :             : 
      48                 :           5 : static void ResetLogger()
      49                 :             : {
      50                 :           5 :     LogInstance().SetLogLevel(BCLog::DEFAULT_LOG_LEVEL);
      51         [ +  - ]:           5 :     LogInstance().SetCategoryLogLevel({});
      52                 :           5 : }
      53                 :             : 
      54                 :          44 : static std::vector<std::string> ReadDebugLogLines()
      55                 :             : {
      56                 :          44 :     std::vector<std::string> lines;
      57   [ +  -  +  - ]:          44 :     std::ifstream ifs{LogInstance().m_file_path.std_path()};
      58         [ +  + ]:         174 :     for (std::string line; std::getline(ifs, line);) {
      59   [ +  -  +  - ]:         216 :         lines.push_back(std::move(line));
      60                 :           0 :     }
      61                 :          44 :     return lines;
      62                 :          44 : }
      63                 :             : 
      64                 :             : struct LogSetup : public BasicTestingSetup {
      65                 :             :     fs::path prev_log_path;
      66                 :             :     fs::path tmp_log_path;
      67                 :             :     bool prev_reopen_file;
      68                 :             :     bool prev_print_to_file;
      69                 :             :     bool prev_log_timestamps;
      70                 :             :     bool prev_log_threadnames;
      71                 :             :     bool prev_log_sourcelocations;
      72                 :             :     std::unordered_map<BCLog::LogFlags, BCLog::Level> prev_category_levels;
      73                 :             :     BCLog::Level prev_log_level;
      74                 :             :     BCLog::CategoryMask prev_category_mask;
      75                 :             : 
      76         [ +  - ]:           7 :     LogSetup() : prev_log_path{LogInstance().m_file_path},
      77         [ +  - ]:          14 :                  tmp_log_path{m_args.GetDataDirBase() / "tmp_debug.log"},
      78   [ +  -  +  - ]:           7 :                  prev_reopen_file{LogInstance().m_reopen_file},
      79         [ +  - ]:           7 :                  prev_print_to_file{LogInstance().m_print_to_file},
      80         [ +  - ]:           7 :                  prev_log_timestamps{LogInstance().m_log_timestamps},
      81         [ +  - ]:           7 :                  prev_log_threadnames{LogInstance().m_log_threadnames},
      82         [ +  - ]:           7 :                  prev_log_sourcelocations{LogInstance().m_log_sourcelocations},
      83   [ +  -  +  - ]:           7 :                  prev_category_levels{LogInstance().CategoryLevels()},
      84   [ +  -  +  - ]:           7 :                  prev_log_level{LogInstance().LogLevel()},
      85   [ +  -  +  -  :          21 :                  prev_category_mask{LogInstance().GetCategoryMask()}
             +  -  +  - ]
      86                 :             :     {
      87   [ +  -  +  - ]:           7 :         LogInstance().m_file_path = tmp_log_path;
      88   [ +  -  +  - ]:           7 :         LogInstance().m_reopen_file = true;
      89         [ +  - ]:           7 :         LogInstance().m_print_to_file = true;
      90         [ +  - ]:           7 :         LogInstance().m_log_timestamps = false;
      91         [ +  - ]:           7 :         LogInstance().m_log_threadnames = false;
      92                 :             : 
      93                 :             :         // Prevent tests from failing when the line number of the logs changes.
      94         [ +  - ]:           7 :         LogInstance().m_log_sourcelocations = false;
      95                 :             : 
      96   [ +  -  +  - ]:           7 :         LogInstance().SetLogLevel(BCLog::Level::Debug);
      97   [ +  -  +  - ]:           7 :         LogInstance().DisableCategory(BCLog::LogFlags::ALL);
      98   [ +  -  +  - ]:           7 :         LogInstance().SetCategoryLogLevel({});
      99   [ +  -  +  - ]:           7 :         LogInstance().SetRateLimiting(nullptr);
     100                 :           7 :     }
     101                 :             : 
     102                 :           7 :     ~LogSetup()
     103                 :             :     {
     104                 :           7 :         LogInstance().m_file_path = prev_log_path;
     105                 :           7 :         LogInfo("Sentinel log to reopen log file");
     106                 :           7 :         LogInstance().m_print_to_file = prev_print_to_file;
     107                 :           7 :         LogInstance().m_reopen_file = prev_reopen_file;
     108                 :           7 :         LogInstance().m_log_timestamps = prev_log_timestamps;
     109                 :           7 :         LogInstance().m_log_threadnames = prev_log_threadnames;
     110                 :           7 :         LogInstance().m_log_sourcelocations = prev_log_sourcelocations;
     111                 :           7 :         LogInstance().SetLogLevel(prev_log_level);
     112                 :           7 :         LogInstance().SetCategoryLogLevel(prev_category_levels);
     113         [ -  + ]:           7 :         LogInstance().SetRateLimiting(nullptr);
     114                 :           7 :         LogInstance().DisableCategory(BCLog::LogFlags::ALL);
     115                 :           7 :         LogInstance().EnableCategory(BCLog::LogFlags{prev_category_mask});
     116                 :          21 :     }
     117                 :             : };
     118                 :             : 
     119   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(logging_timer)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     120                 :             : {
     121   [ +  -  +  - ]:           2 :     auto micro_timer = BCLog::Timer<std::chrono::microseconds>("tests", "end_msg");
     122         [ +  - ]:           1 :     const std::string_view result_prefix{"tests: msg ("};
     123   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(micro_timer.LogMsg("msg").substr(0, result_prefix.size()), result_prefix);
          +  -  +  -  +  
                      - ]
     124                 :           1 : }
     125                 :             : 
     126   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(test_LogEscapeMessage)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     127                 :             : {
     128                 :             :     // ASCII and UTF-8 must pass through unaltered.
     129         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("Valid log message貓"), "Valid log message貓");
     130                 :             :     // Newlines are escaped too, so a message can't forge log lines.
     131         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("Message\n with newlines\n"), R"(Message\x0a with newlines\x0a)");
     132                 :             :     // Other control characters are escaped in C syntax.
     133         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("\x01\x7f Corrupted log message\x0d"), R"(\x01\x7f Corrupted log message\x0d)");
     134                 :             :     // Embedded NULL characters are escaped too.
     135                 :           1 :     const std::string NUL("O\x00O", 3);
     136   [ +  -  -  +  :           1 :     BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage(NUL), R"(O\x00O)");
             +  -  +  - ]
     137                 :           1 : }
     138                 :             : 
     139   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(logging_LogPrint, LogSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     140                 :             : {
     141                 :           1 :     LogInstance().m_log_sourcelocations = true;
     142                 :             : 
     143                 :          12 :     struct Case {
     144                 :             :         std::string msg;
     145                 :             :         BCLog::LogFlags category;
     146                 :             :         BCLog::Level level;
     147                 :             :         std::string prefix;
     148                 :             :         SourceLocation loc;
     149                 :             :     };
     150                 :             : 
     151                 :           1 :     std::vector<Case> cases = {
     152                 :             :         {"foo1: bar1", BCLog::NET, BCLog::Level::Debug, "[net] ", SourceLocation{__func__}},
     153                 :             :         {"foo2: bar2", BCLog::NET, BCLog::Level::Info, "[net:info] ", SourceLocation{__func__}},
     154                 :             :         {"foo3: bar3", BCLog::ALL, BCLog::Level::Debug, "[debug] ", SourceLocation{__func__}},
     155                 :             :         {"foo4: bar4", BCLog::ALL, BCLog::Level::Info, "", SourceLocation{__func__}},
     156                 :             :         {"foo5: bar5", BCLog::NONE, BCLog::Level::Debug, "[debug] ", SourceLocation{__func__}},
     157                 :             :         {"foo6: bar6", BCLog::NONE, BCLog::Level::Info, "", SourceLocation{__func__}},
     158   [ -  +  +  +  :           7 :     };
                   -  - ]
     159                 :             : 
     160                 :           1 :     std::vector<std::string> expected;
     161         [ +  + ]:           7 :     for (auto& [msg, category, level, prefix, loc] : cases) {
     162   [ +  -  +  -  :          18 :         expected.push_back(tfm::format("[%s:%s] [%s] %s%s", util::RemovePrefix(loc.file_name(), "./"), loc.line(), loc.function_name_short(), prefix, msg));
                   +  - ]
     163   [ +  -  +  - ]:          18 :         LogInstance().LogPrint({.category = category, .level = level, .should_ratelimit = false, .source_loc = std::move(loc), .message = msg});
     164                 :             :     }
     165         [ +  - ]:           1 :     std::vector<std::string> log_lines{ReadDebugLogLines()};
     166   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
                   +  - ]
     167   [ +  -  +  -  :          20 : }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          -  +  +  -  -  
             +  +  -  -  
                      - ]
     168                 :             : 
     169   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(logging_LogPrintMacros, LogSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     170                 :             : {
     171                 :           1 :     LogInstance().EnableCategory(BCLog::NET);
     172         [ -  + ]:           1 :     LogTrace(BCLog::NET, "foo6: %s", "bar6"); // not logged
     173         [ +  - ]:           1 :     LogDebug(BCLog::NET, "foo7: %s", "bar7");
     174                 :           1 :     LogInfo("foo8: %s", "bar8");
     175                 :           1 :     LogWarning("foo9: %s", "bar9");
     176                 :           1 :     LogError("foo10: %s", "bar10");
     177                 :           1 :     std::vector<std::string> log_lines{ReadDebugLogLines()};
     178                 :           1 :     std::vector<std::string> expected = {
     179                 :             :         "[net] foo7: bar7",
     180                 :             :         "foo8: bar8",
     181                 :             :         "[warning] foo9: bar9",
     182                 :             :         "[error] foo10: bar10",
     183         [ +  - ]:           1 :     };
     184   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
                   +  - ]
     185                 :           1 : }
     186                 :             : 
     187   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(logging_LogPrintMacros_CategoryName, LogSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     188                 :             : {
     189                 :           1 :     LogInstance().EnableCategory(BCLog::LogFlags::ALL);
     190                 :           1 :     const auto concatenated_category_names = LogInstance().LogCategoriesString();
     191                 :           1 :     std::vector<std::pair<BCLog::LogFlags, std::string>> expected_category_names;
     192   [ -  +  +  - ]:           1 :     const auto category_names = SplitString(concatenated_category_names, ',');
     193         [ +  + ]:          31 :     for (const auto& category_name : category_names) {
     194   [ -  +  +  - ]:          30 :         const auto trimmed_category_name = TrimString(category_name);
     195   [ -  +  +  -  :          30 :         const auto category{*Assert(BCLog::Logger::GetLogCategory(trimmed_category_name))};
             +  -  +  - ]
     196         [ +  - ]:          30 :         expected_category_names.emplace_back(category, trimmed_category_name);
     197                 :          30 :     }
     198                 :             : 
     199                 :           1 :     std::vector<std::string> expected;
     200   [ +  -  +  + ]:          31 :     for (const auto& [category, name] : expected_category_names) {
     201   [ +  -  +  -  :          30 :         LogDebug(category, "foo: %s\n", "bar");
                   +  - ]
     202         [ +  - ]:          30 :         std::string expected_log = "[";
     203         [ -  + ]:          30 :         expected_log += name;
     204         [ +  - ]:          30 :         expected_log += "] foo: bar";
     205         [ +  - ]:          30 :         expected.push_back(expected_log);
     206                 :          30 :     }
     207                 :             : 
     208         [ +  - ]:           1 :     std::vector<std::string> log_lines{ReadDebugLogLines()};
     209   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
                   +  - ]
     210                 :           1 : }
     211                 :             : 
     212   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(logging_SeverityLevels, LogSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     213                 :             : {
     214                 :           1 :     LogInstance().SetLogLevel(BCLog::Level::Debug);
     215                 :           1 :     LogInstance().EnableCategory(BCLog::LogFlags::ALL);
     216                 :           1 :     LogInstance().SetCategoryLogLevel(/*category_str=*/"net", /*level_str=*/"info");
     217                 :             : 
     218                 :             :     // Global log level
     219                 :           1 :     LogInfo("info_%s", 1);
     220         [ -  + ]:           1 :     LogTrace(BCLog::HTTP, "trace_%s. This log level is lower than the global one.", 2);
     221         [ +  - ]:           1 :     LogDebug(BCLog::HTTP, "debug_%s", 3);
     222                 :           1 :     LogWarning("warn_%s", 4);
     223                 :           1 :     LogError("err_%s", 5);
     224                 :             : 
     225                 :             :     // Category-specific log level
     226         [ -  + ]:           1 :     LogDebug(BCLog::NET, "debug_%s. This log level is the same as the global one but lower than the category-specific one, which takes precedence.", 6);
     227                 :             : 
     228                 :           1 :     std::vector<std::string> expected = {
     229                 :             :         "info_1",
     230                 :             :         "[http] debug_3",
     231                 :             :         "[warning] warn_4",
     232                 :             :         "[error] err_5",
     233                 :           1 :     };
     234         [ +  - ]:           1 :     std::vector<std::string> log_lines{ReadDebugLogLines()};
     235   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
                   +  - ]
     236                 :           1 : }
     237                 :             : 
     238                 :             : namespace {
     239                 :           3 : void CheckLogWarnThenDebug(std::string_view message)
     240                 :             : {
     241   [ +  +  +  + ]:           3 :     LogWarnThenDebug(BCLog::NET, "warn_then_debug: %s", message);
     242                 :           3 : }
     243                 :             : } // namespace
     244                 :             : 
     245   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(logging_LogWarnThenDebug, LogSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     246                 :             : {
     247                 :           1 :     ResetLogger();
     248                 :           1 :     CheckLogWarnThenDebug("first");
     249                 :           1 :     CheckLogWarnThenDebug("suppressed");
     250                 :           1 :     LogInstance().EnableCategory(BCLog::NET);
     251                 :           1 :     CheckLogWarnThenDebug("debug");
     252                 :             : 
     253                 :           1 :     std::vector log_lines{ReadDebugLogLines()};
     254                 :           1 :     std::vector<std::string> expected = {
     255                 :             :         "[warning] warn_then_debug: first",
     256                 :             :         "[net] warn_then_debug: debug",
     257         [ +  - ]:           1 :     };
     258   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
                   +  - ]
     259                 :           1 : }
     260                 :             : 
     261   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(logging_Conf, LogSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     262                 :             : {
     263                 :             :     // Set global log level
     264                 :           1 :     {
     265                 :           1 :         ResetLogger();
     266                 :           1 :         ArgsManager args;
     267   [ +  -  +  -  :           2 :         args.AddArg("-loglevel", "...", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
                   +  - ]
     268                 :           1 :         const char* argv_test[] = {"bitcoind", "-loglevel=debug"};
     269         [ +  - ]:           1 :         std::string err;
     270   [ +  -  +  -  :           2 :         BOOST_REQUIRE(args.ParseParameters(2, argv_test, err));
             +  -  +  - ]
     271                 :             : 
     272         [ +  - ]:           1 :         auto result = init::SetLoggingLevel(args);
     273   [ +  -  +  -  :           2 :         BOOST_REQUIRE(result);
                   +  - ]
     274   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(LogInstance().LogLevel(), BCLog::Level::Debug);
                   +  - ]
     275                 :           1 :     }
     276                 :             : 
     277                 :             :     // Set category-specific log level
     278                 :           1 :     {
     279                 :           1 :         ResetLogger();
     280                 :           1 :         ArgsManager args;
     281   [ +  -  +  -  :           2 :         args.AddArg("-loglevel", "...", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
                   +  - ]
     282                 :           1 :         const char* argv_test[] = {"bitcoind", "-loglevel=net:trace"};
     283         [ +  - ]:           1 :         std::string err;
     284   [ +  -  +  -  :           2 :         BOOST_REQUIRE(args.ParseParameters(2, argv_test, err));
             +  -  +  - ]
     285                 :             : 
     286         [ +  - ]:           1 :         auto result = init::SetLoggingLevel(args);
     287   [ +  -  +  -  :           2 :         BOOST_REQUIRE(result);
                   +  - ]
     288   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(LogInstance().LogLevel(), BCLog::DEFAULT_LOG_LEVEL);
                   +  - ]
     289                 :             : 
     290   [ +  -  +  - ]:           1 :         const auto& category_levels{LogInstance().CategoryLevels()};
     291                 :           1 :         const auto net_it{category_levels.find(BCLog::LogFlags::NET)};
     292   [ +  -  +  -  :           3 :         BOOST_REQUIRE(net_it != category_levels.end());
             +  -  +  - ]
     293   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(net_it->second, BCLog::Level::Trace);
     294                 :           1 :     }
     295                 :             : 
     296                 :             :     // Set both global log level and category-specific log level
     297                 :           1 :     {
     298                 :           1 :         ResetLogger();
     299                 :           1 :         ArgsManager args;
     300   [ +  -  +  -  :           2 :         args.AddArg("-loglevel", "...", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
                   +  - ]
     301                 :           1 :         const char* argv_test[] = {"bitcoind", "-loglevel=debug", "-loglevel=net:trace", "-loglevel=http:info"};
     302         [ +  - ]:           1 :         std::string err;
     303   [ +  -  +  -  :           2 :         BOOST_REQUIRE(args.ParseParameters(4, argv_test, err));
             +  -  +  - ]
     304                 :             : 
     305         [ +  - ]:           1 :         auto result = init::SetLoggingLevel(args);
     306   [ +  -  +  -  :           2 :         BOOST_REQUIRE(result);
                   +  - ]
     307   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(LogInstance().LogLevel(), BCLog::Level::Debug);
                   +  - ]
     308                 :             : 
     309   [ +  -  +  - ]:           2 :         const auto& category_levels{LogInstance().CategoryLevels()};
     310   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(category_levels.size(), 2);
     311                 :             : 
     312                 :           1 :         const auto net_it{category_levels.find(BCLog::LogFlags::NET)};
     313   [ +  -  +  -  :           3 :         BOOST_CHECK(net_it != category_levels.end());
             +  -  +  - ]
     314   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(net_it->second, BCLog::Level::Trace);
     315                 :             : 
     316                 :           1 :         const auto http_it{category_levels.find(BCLog::LogFlags::HTTP)};
     317   [ +  -  +  -  :           3 :         BOOST_CHECK(http_it != category_levels.end());
             +  -  +  - ]
     318   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(http_it->second, BCLog::Level::Info);
     319                 :           1 :     }
     320                 :             : 
     321                 :             :     // Removed categories (like "libevent") should not store a category-specific level
     322                 :           1 :     {
     323                 :           1 :         ResetLogger();
     324   [ +  -  +  -  :           2 :         BOOST_CHECK(LogInstance().SetCategoryLogLevel(/*category_str=*/"libevent", /*level_str=*/"trace"));
                   +  - ]
     325   [ +  -  +  -  :           2 :         BOOST_CHECK(LogInstance().CategoryLevels().empty());
                   +  - ]
     326                 :             :     }
     327                 :           1 : }
     328                 :             : 
     329                 :             : struct ScopedScheduler {
     330                 :             :     CScheduler scheduler{};
     331                 :             : 
     332                 :           2 :     ScopedScheduler()
     333                 :           2 :     {
     334         [ +  - ]:           4 :         scheduler.m_service_thread = std::thread([this] { scheduler.serviceQueue(); });
     335                 :           2 :     }
     336                 :           2 :     ~ScopedScheduler()
     337                 :             :     {
     338                 :           0 :         scheduler.stop();
     339                 :           2 :     }
     340                 :           2 :     void MockForwardAndSync(std::chrono::seconds duration)
     341                 :             :     {
     342                 :           2 :         scheduler.MockForward(duration);
     343                 :           2 :         std::promise<void> promise;
     344         [ +  - ]:           4 :         scheduler.scheduleFromNow([&promise] { promise.set_value(); }, 0ms);
     345   [ +  -  +  - ]:           4 :         promise.get_future().wait();
     346                 :           2 :     }
     347                 :           2 :     std::shared_ptr<BCLog::LogRateLimiter> GetLimiter(size_t max_bytes, std::chrono::seconds window)
     348                 :             :     {
     349                 :           4 :         auto sched_func = [this](auto func, auto w) {
     350         [ +  - ]:           2 :             scheduler.scheduleEvery(std::move(func), w);
     351                 :           2 :         };
     352         [ +  - ]:           4 :         return BCLog::LogRateLimiter::Create(sched_func, max_bytes, window);
     353                 :             :     }
     354                 :             : };
     355                 :             : 
     356   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(logging_log_rate_limiter)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     357                 :             : {
     358                 :           1 :     uint64_t max_bytes{1024};
     359                 :           1 :     auto reset_window{1min};
     360                 :           1 :     ScopedScheduler scheduler{};
     361         [ +  - ]:           1 :     auto limiter_{scheduler.GetLimiter(max_bytes, reset_window)};
     362   [ +  -  +  - ]:           1 :     auto& limiter{*Assert(limiter_)};
     363                 :             : 
     364                 :           1 :     using Status = BCLog::LogRateLimiter::Status;
     365         [ +  - ]:           1 :     auto source_loc_1{SourceLocation{__func__}};
     366                 :           1 :     auto source_loc_2{SourceLocation{__func__}};
     367                 :             : 
     368                 :             :     // A fresh limiter should not have any suppressions
     369   [ +  -  +  -  :           2 :     BOOST_CHECK(!limiter.SuppressionsActive());
                   +  - ]
     370                 :             : 
     371                 :             :     // Resetting an unused limiter is fine
     372         [ +  - ]:           1 :     limiter.Reset();
     373   [ +  -  +  -  :           2 :     BOOST_CHECK(!limiter.SuppressionsActive());
                   +  - ]
     374                 :             : 
     375                 :             :     // No suppression should happen until more than max_bytes have been consumed
     376   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(limiter.Consume(source_loc_1, std::string(max_bytes - 1, 'a')), Status::UNSUPPRESSED);
             +  -  +  - ]
     377   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(limiter.Consume(source_loc_1, "a"), Status::UNSUPPRESSED);
             +  -  +  - ]
     378   [ +  -  +  -  :           2 :     BOOST_CHECK(!limiter.SuppressionsActive());
                   +  - ]
     379   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(limiter.Consume(source_loc_1, "a"), Status::NEWLY_SUPPRESSED);
             +  -  +  - ]
     380   [ +  -  +  -  :           2 :     BOOST_CHECK(limiter.SuppressionsActive());
                   +  - ]
     381   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(limiter.Consume(source_loc_1, "a"), Status::STILL_SUPPRESSED);
             +  -  +  - ]
     382   [ +  -  +  -  :           2 :     BOOST_CHECK(limiter.SuppressionsActive());
                   +  - ]
     383                 :             : 
     384                 :             :     // Location 2  should not be affected by location 1's suppression
     385   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(limiter.Consume(source_loc_2, std::string(max_bytes, 'a')), Status::UNSUPPRESSED);
             +  -  +  - ]
     386   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(limiter.Consume(source_loc_2, "a"), Status::NEWLY_SUPPRESSED);
             +  -  +  - ]
     387   [ +  -  +  - ]:           2 :     BOOST_CHECK(limiter.SuppressionsActive());
     388                 :             : 
     389                 :             :     // After reset_window time has passed, all suppressions should be cleared.
     390         [ +  - ]:           1 :     scheduler.MockForwardAndSync(reset_window);
     391                 :             : 
     392   [ +  -  +  -  :           2 :     BOOST_CHECK(!limiter.SuppressionsActive());
                   +  - ]
     393   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(limiter.Consume(source_loc_1, std::string(max_bytes, 'a')), Status::UNSUPPRESSED);
             +  -  +  - ]
     394   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(limiter.Consume(source_loc_2, std::string(max_bytes, 'a')), Status::UNSUPPRESSED);
          +  -  +  -  +  
                      - ]
     395                 :           2 : }
     396                 :             : 
     397   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(logging_log_limit_stats)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     398                 :             : {
     399                 :           1 :     BCLog::LogRateLimiter::Stats stats(BCLog::RATELIMIT_MAX_BYTES);
     400                 :             : 
     401                 :             :     // Check that stats gets initialized correctly.
     402         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(stats.m_available_bytes, BCLog::RATELIMIT_MAX_BYTES);
     403         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(stats.m_dropped_bytes, uint64_t{0});
     404                 :             : 
     405                 :           1 :     const uint64_t MESSAGE_SIZE{BCLog::RATELIMIT_MAX_BYTES / 2};
     406   [ +  -  +  - ]:           2 :     BOOST_CHECK(stats.Consume(MESSAGE_SIZE));
     407         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(stats.m_available_bytes, BCLog::RATELIMIT_MAX_BYTES - MESSAGE_SIZE);
     408         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(stats.m_dropped_bytes, uint64_t{0});
     409                 :             : 
     410   [ +  -  +  - ]:           2 :     BOOST_CHECK(stats.Consume(MESSAGE_SIZE));
     411         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(stats.m_available_bytes, BCLog::RATELIMIT_MAX_BYTES - MESSAGE_SIZE * 2);
     412         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(stats.m_dropped_bytes, uint64_t{0});
     413                 :             : 
     414                 :             :     // Consuming more bytes after already having consumed RATELIMIT_MAX_BYTES should fail.
     415   [ +  -  +  - ]:           2 :     BOOST_CHECK(!stats.Consume(500));
     416         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(stats.m_available_bytes, uint64_t{0});
     417         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(stats.m_dropped_bytes, uint64_t{500});
     418                 :           1 : }
     419                 :             : 
     420                 :             : namespace {
     421                 :             : 
     422                 :             : enum class Location {
     423                 :             :     INFO_1,
     424                 :             :     INFO_2,
     425                 :             :     DEBUG_LOG,
     426                 :             :     INFO_NOLIMIT,
     427                 :             : };
     428                 :             : 
     429                 :          38 : void LogFromLocation(Location location, const std::string& message) {
     430   [ +  +  +  +  :          38 :     switch (location) {
                      - ]
     431                 :          13 :     case Location::INFO_1:
     432                 :          13 :         LogInfo("%s\n", message);
     433                 :          13 :         return;
     434                 :           1 :     case Location::INFO_2:
     435                 :           1 :         LogInfo("%s\n", message);
     436                 :           1 :         return;
     437                 :          12 :     case Location::DEBUG_LOG:
     438         [ +  - ]:          12 :         LogDebug(BCLog::LogFlags::HTTP, "%s\n", message);
     439                 :             :         return;
     440                 :          12 :     case Location::INFO_NOLIMIT:
     441                 :          12 :         LogInfo(util::log::NO_RATE_LIMIT, "%s\n", message);
     442                 :          12 :         return;
     443                 :             :     } // no default case, so the compiler can warn about missing cases
     444                 :           0 :     AssertUnreachable();
     445                 :             : }
     446                 :             : 
     447                 :             : /**
     448                 :             :  * For a given `location` and `message`, ensure that the on-disk debug log behaviour resembles what
     449                 :             :  * we'd expect it to be for `status` and `suppressions_active`.
     450                 :             :  */
     451                 :          38 : void TestLogFromLocation(Location location, const std::string& message,
     452                 :             :                          BCLog::LogRateLimiter::Status status, bool suppressions_active,
     453                 :             :                          std::source_location source = std::source_location::current())
     454                 :             : {
     455   [ +  -  +  -  :         151 :     BOOST_TEST_INFO_SCOPE("TestLogFromLocation called from " << source.file_name() << ":" << source.line());
                   +  - ]
     456                 :          38 :     using Status = BCLog::LogRateLimiter::Status;
     457   [ +  +  -  + ]:          38 :     if (!suppressions_active) assert(status == Status::UNSUPPRESSED); // developer error
     458                 :             : 
     459   [ +  -  +  - ]:          38 :     std::ofstream ofs(LogInstance().m_file_path.std_path(), std::ios::out | std::ios::trunc); // clear debug log
     460         [ +  - ]:          38 :     LogFromLocation(location, message);
     461         [ +  - ]:          38 :     auto log_lines{ReadDebugLogLines()};
     462   [ -  +  +  -  :          38 :     BOOST_TEST_INFO_SCOPE(log_lines.size() << " log_lines read: \n" << util::Join(log_lines, "\n"));
             +  -  +  + ]
     463                 :             : 
     464         [ +  + ]:          38 :     if (status == Status::STILL_SUPPRESSED) {
     465   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(log_lines.size(), 0);
                   +  - ]
     466                 :           1 :         return;
     467                 :             :     }
     468                 :             : 
     469         [ +  + ]:          37 :     if (status == Status::NEWLY_SUPPRESSED) {
     470   [ +  -  -  +  :           1 :         BOOST_REQUIRE_EQUAL(log_lines.size(), 2);
                   +  - ]
     471   [ +  -  -  +  :           2 :         BOOST_CHECK(log_lines[0].starts_with("[*] [warning] Excessive logging detected"));
                   +  - ]
     472                 :           1 :         log_lines.erase(log_lines.begin());
     473                 :             :     }
     474   [ +  -  -  +  :          37 :     BOOST_REQUIRE_EQUAL(log_lines.size(), 1);
                   +  - ]
     475                 :          37 :     auto& payload{log_lines.back()};
     476   [ +  -  -  +  :          37 :     BOOST_CHECK_EQUAL(suppressions_active, payload.starts_with("[*]"));
                   +  - ]
     477   [ +  -  -  +  :          74 :     BOOST_CHECK(payload.ends_with(message));
             -  +  +  - ]
     478                 :          38 : }
     479                 :             : 
     480                 :             : } // namespace
     481                 :             : 
     482   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(logging_filesize_rate_limit, LogSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     483                 :             : {
     484                 :           1 :     using Status = BCLog::LogRateLimiter::Status;
     485                 :           1 :     LogInstance().m_log_timestamps = false;
     486                 :           1 :     LogInstance().m_log_sourcelocations = false;
     487                 :           1 :     LogInstance().m_log_threadnames = false;
     488                 :           1 :     LogInstance().EnableCategory(BCLog::LogFlags::HTTP);
     489                 :             : 
     490                 :           1 :     constexpr int64_t line_length{1024};
     491                 :           1 :     constexpr int64_t num_lines{10};
     492                 :           1 :     constexpr int64_t bytes_quota{line_length * num_lines};
     493                 :           1 :     constexpr auto time_window{1h};
     494                 :             : 
     495                 :           1 :     ScopedScheduler scheduler{};
     496         [ +  - ]:           1 :     auto limiter{scheduler.GetLimiter(bytes_quota, time_window)};
     497   [ +  -  +  -  :           2 :     LogInstance().SetRateLimiting(limiter);
                   +  - ]
     498                 :             : 
     499         [ +  - ]:           1 :     const std::string log_message(line_length - 1, 'a'); // subtract one for newline
     500                 :             : 
     501         [ +  + ]:          11 :     for (int i = 0; i < num_lines; ++i) {
     502         [ +  - ]:          10 :         TestLogFromLocation(Location::INFO_1, log_message, Status::UNSUPPRESSED, /*suppressions_active=*/false);
     503                 :             :     }
     504   [ +  -  +  - ]:           1 :     TestLogFromLocation(Location::INFO_1, "a", Status::NEWLY_SUPPRESSED, /*suppressions_active=*/true);
     505   [ +  -  +  - ]:           1 :     TestLogFromLocation(Location::INFO_1, "b", Status::STILL_SUPPRESSED, /*suppressions_active=*/true);
     506   [ +  -  +  - ]:           1 :     TestLogFromLocation(Location::INFO_2, "c", Status::UNSUPPRESSED, /*suppressions_active=*/true);
     507                 :           1 :     {
     508         [ +  - ]:           1 :         scheduler.MockForwardAndSync(time_window);
     509   [ +  -  +  -  :           2 :         BOOST_CHECK(ReadDebugLogLines().back().starts_with("[warning] Restarting logging"));
          -  +  +  -  +  
                      - ]
     510                 :             :     }
     511                 :             :     // Check that logging from previously suppressed location is unsuppressed again.
     512         [ +  - ]:           1 :     TestLogFromLocation(Location::INFO_1, log_message, Status::UNSUPPRESSED, /*suppressions_active=*/false);
     513                 :             :     // Check that conditional logging, and unconditional logging with should_ratelimit=false is
     514                 :             :     // not being ratelimited.
     515         [ +  + ]:           3 :     for (Location location : {Location::DEBUG_LOG, Location::INFO_NOLIMIT}) {
     516         [ +  + ]:          26 :         for (int i = 0; i < num_lines + 2; ++i) {
     517         [ +  - ]:          24 :             TestLogFromLocation(location, log_message, Status::UNSUPPRESSED, /*suppressions_active=*/false);
     518                 :             :         }
     519                 :             :     }
     520         [ +  - ]:           3 : }
     521                 :             : 
     522                 :             : BOOST_AUTO_TEST_SUITE_END()
        

Generated by: LCOV version 2.0-1