LCOV - code coverage report
Current view: top level - src/test - logging_tests.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 99.0 % 292 289
Test Date: 2025-12-07 05:20:42 Functions: 100.0 % 30 30
Branches: 50.8 % 1381 702

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

Generated by: LCOV version 2.0-1