Bitcoin Core  25.99.0
P2P Digital Currency
logging_tests.cpp
Go to the documentation of this file.
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>
9 #include <util/string.h>
10 
11 #include <chrono>
12 #include <fstream>
13 #include <iostream>
14 #include <unordered_map>
15 #include <utility>
16 #include <vector>
17 
18 #include <boost/test/unit_test.hpp>
19 
20 BOOST_FIXTURE_TEST_SUITE(logging_tests, BasicTestingSetup)
21 
22 static void ResetLogger()
23 {
26 }
27 
28 struct LogSetup : public BasicTestingSetup {
36  std::unordered_map<BCLog::LogFlags, BCLog::Level> prev_category_levels;
38 
39  LogSetup() : prev_log_path{LogInstance().m_file_path},
40  tmp_log_path{m_args.GetDataDirBase() / "tmp_debug.log"},
41  prev_reopen_file{LogInstance().m_reopen_file},
42  prev_print_to_file{LogInstance().m_print_to_file},
43  prev_log_timestamps{LogInstance().m_log_timestamps},
44  prev_log_threadnames{LogInstance().m_log_threadnames},
45  prev_log_sourcelocations{LogInstance().m_log_sourcelocations},
46  prev_category_levels{LogInstance().CategoryLevels()},
47  prev_log_level{LogInstance().LogLevel()}
48  {
50  LogInstance().m_reopen_file = true;
52  LogInstance().m_log_timestamps = false;
54 
55  // Prevent tests from failing when the line number of the logs changes.
57 
60  }
61 
63  {
65  LogPrintf("Sentinel log to reopen log file\n");
73  }
74 };
75 
76 BOOST_AUTO_TEST_CASE(logging_timer)
77 {
78  auto micro_timer = BCLog::Timer<std::chrono::microseconds>("tests", "end_msg");
79  const std::string_view result_prefix{"tests: msg ("};
80  BOOST_CHECK_EQUAL(micro_timer.LogMsg("msg").substr(0, result_prefix.size()), result_prefix);
81 }
82 
83 BOOST_FIXTURE_TEST_CASE(logging_LogPrintf_, LogSetup)
84 {
86  LogPrintf_("fn1", "src1", 1, BCLog::LogFlags::NET, BCLog::Level::Debug, "foo1: %s\n", "bar1");
87  LogPrintf_("fn2", "src2", 2, BCLog::LogFlags::NET, BCLog::Level::None, "foo2: %s\n", "bar2");
88  LogPrintf_("fn3", "src3", 3, BCLog::LogFlags::NONE, BCLog::Level::Debug, "foo3: %s\n", "bar3");
89  LogPrintf_("fn4", "src4", 4, BCLog::LogFlags::NONE, BCLog::Level::None, "foo4: %s\n", "bar4");
90  std::ifstream file{tmp_log_path};
91  std::vector<std::string> log_lines;
92  for (std::string log; std::getline(file, log);) {
93  log_lines.push_back(log);
94  }
95  std::vector<std::string> expected = {
96  "[src1:1] [fn1] [net:debug] foo1: bar1",
97  "[src2:2] [fn2] [net] foo2: bar2",
98  "[src3:3] [fn3] [debug] foo3: bar3",
99  "[src4:4] [fn4] foo4: bar4",
100  };
101  BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
102 }
103 
104 BOOST_FIXTURE_TEST_CASE(logging_LogPrintMacros, LogSetup)
105 {
106  LogPrintf("foo5: %s\n", "bar5");
107  LogPrint(BCLog::NET, "foo6: %s\n", "bar6");
108  LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "foo7: %s\n", "bar7");
109  LogPrintLevel(BCLog::NET, BCLog::Level::Info, "foo8: %s\n", "bar8");
110  LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "foo9: %s\n", "bar9");
111  LogPrintLevel(BCLog::NET, BCLog::Level::Error, "foo10: %s\n", "bar10");
112  LogPrintfCategory(BCLog::VALIDATION, "foo11: %s\n", "bar11");
113  std::ifstream file{tmp_log_path};
114  std::vector<std::string> log_lines;
115  for (std::string log; std::getline(file, log);) {
116  log_lines.push_back(log);
117  }
118  std::vector<std::string> expected = {
119  "foo5: bar5",
120  "[net] foo6: bar6",
121  "[net:debug] foo7: bar7",
122  "[net:info] foo8: bar8",
123  "[net:warning] foo9: bar9",
124  "[net:error] foo10: bar10",
125  "[validation] foo11: bar11",
126  };
127  BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
128 }
129 
130 BOOST_FIXTURE_TEST_CASE(logging_LogPrintMacros_CategoryName, LogSetup)
131 {
133  const auto concatenated_category_names = LogInstance().LogCategoriesString();
134  std::vector<std::pair<BCLog::LogFlags, std::string>> expected_category_names;
135  const auto category_names = SplitString(concatenated_category_names, ',');
136  for (const auto& category_name : category_names) {
137  BCLog::LogFlags category;
138  const auto trimmed_category_name = TrimString(category_name);
139  BOOST_REQUIRE(GetLogCategory(category, trimmed_category_name));
140  expected_category_names.emplace_back(category, trimmed_category_name);
141  }
142 
143  std::vector<std::string> expected;
144  for (const auto& [category, name] : expected_category_names) {
145  LogPrint(category, "foo: %s\n", "bar");
146  std::string expected_log = "[";
147  expected_log += name;
148  expected_log += "] foo: bar";
149  expected.push_back(expected_log);
150  }
151 
152  std::ifstream file{tmp_log_path};
153  std::vector<std::string> log_lines;
154  for (std::string log; std::getline(file, log);) {
155  log_lines.push_back(log);
156  }
157  BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
158 }
159 
160 BOOST_FIXTURE_TEST_CASE(logging_SeverityLevels, LogSetup)
161 {
163 
165  LogInstance().SetCategoryLogLevel(/*category_str=*/"net", /*level_str=*/"info");
166 
167  // Global log level
168  LogPrintLevel(BCLog::HTTP, BCLog::Level::Info, "foo1: %s\n", "bar1");
169  LogPrintLevel(BCLog::MEMPOOL, BCLog::Level::Trace, "foo2: %s. This log level is lower than the global one.\n", "bar2");
170  LogPrintLevel(BCLog::VALIDATION, BCLog::Level::Warning, "foo3: %s\n", "bar3");
171  LogPrintLevel(BCLog::RPC, BCLog::Level::Error, "foo4: %s\n", "bar4");
172 
173  // Category-specific log level
174  LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "foo5: %s\n", "bar5");
175  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");
176  LogPrintLevel(BCLog::NET, BCLog::Level::Error, "foo7: %s\n", "bar7");
177 
178  std::vector<std::string> expected = {
179  "[http:info] foo1: bar1",
180  "[validation:warning] foo3: bar3",
181  "[rpc:error] foo4: bar4",
182  "[net:warning] foo5: bar5",
183  "[net:error] foo7: bar7",
184  };
185  std::ifstream file{tmp_log_path};
186  std::vector<std::string> log_lines;
187  for (std::string log; std::getline(file, log);) {
188  log_lines.push_back(log);
189  }
190  BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
191 }
192 
194 {
195  // Set global log level
196  {
197  ResetLogger();
200  const char* argv_test[] = {"bitcoind", "-loglevel=debug"};
201  std::string err;
202  BOOST_REQUIRE(args.ParseParameters(2, argv_test, err));
203 
204  auto result = init::SetLoggingLevel(args);
205  BOOST_REQUIRE(result);
207  }
208 
209  // Set category-specific log level
210  {
211  ResetLogger();
214  const char* argv_test[] = {"bitcoind", "-loglevel=net:trace"};
215  std::string err;
216  BOOST_REQUIRE(args.ParseParameters(2, argv_test, err));
217 
218  auto result = init::SetLoggingLevel(args);
219  BOOST_REQUIRE(result);
221 
222  const auto& category_levels{LogInstance().CategoryLevels()};
223  const auto net_it{category_levels.find(BCLog::LogFlags::NET)};
224  BOOST_REQUIRE(net_it != category_levels.end());
225  BOOST_CHECK_EQUAL(net_it->second, BCLog::Level::Trace);
226  }
227 
228  // Set both global log level and category-specific log level
229  {
230  ResetLogger();
233  const char* argv_test[] = {"bitcoind", "-loglevel=debug", "-loglevel=net:trace", "-loglevel=http:info"};
234  std::string err;
235  BOOST_REQUIRE(args.ParseParameters(4, argv_test, err));
236 
237  auto result = init::SetLoggingLevel(args);
238  BOOST_REQUIRE(result);
240 
241  const auto& category_levels{LogInstance().CategoryLevels()};
242  BOOST_CHECK_EQUAL(category_levels.size(), 2);
243 
244  const auto net_it{category_levels.find(BCLog::LogFlags::NET)};
245  BOOST_CHECK(net_it != category_levels.end());
246  BOOST_CHECK_EQUAL(net_it->second, BCLog::Level::Trace);
247 
248  const auto http_it{category_levels.find(BCLog::LogFlags::HTTP)};
249  BOOST_CHECK(http_it != category_levels.end());
250  BOOST_CHECK_EQUAL(http_it->second, BCLog::Level::Info);
251  }
252 }
253 
ArgsManager & args
Definition: bitcoind.cpp:269
@ ALLOW_ANY
disable validation
Definition: args.h:104
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: args.cpp:178
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:563
bool m_log_sourcelocations
Definition: logging.h:122
void SetLogLevel(Level level)
Definition: logging.h:172
fs::path m_file_path
Definition: logging.h:124
std::unordered_map< LogFlags, Level > CategoryLevels() const
Definition: logging.h:159
bool m_log_threadnames
Definition: logging.h:121
void EnableCategory(LogFlags flag)
Definition: logging.cpp:96
bool m_log_timestamps
Definition: logging.h:119
std::atomic< bool > m_reopen_file
Definition: logging.h:125
bool m_print_to_file
Definition: logging.h:117
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels)
Definition: logging.h:164
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:188
RAII-style object that outputs timing information to logs.
Definition: timer.h:24
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:31
BOOST_AUTO_TEST_SUITE_END()
Common init functions shared by bitcoin-node, bitcoin-wallet, etc.
bool GetLogCategory(BCLog::LogFlags &flag, const std::string &str)
Return true if str parses as a log category and set the flag.
Definition: logging.cpp:190
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
#define LogPrintLevel(category, level,...)
Definition: logging.h:254
static void LogPrintf_(const std::string &logging_function, const std::string &source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, const char *fmt, const Args &... args)
Definition: logging.h:220
#define LogPrint(category,...)
Definition: logging.h:246
#define LogPrintfCategory(category,...)
Definition: logging.h:240
#define LogPrintf(...)
Definition: logging.h:237
BOOST_AUTO_TEST_CASE(logging_timer)
BOOST_FIXTURE_TEST_CASE(logging_LogPrintf_, LogSetup)
static void ResetLogger()
Level
Definition: logging.h:74
LogFlags
Definition: logging.h:38
@ ALL
Definition: logging.h:72
@ RPC
Definition: logging.h:47
@ HTTP
Definition: logging.h:43
@ NONE
Definition: logging.h:39
@ VALIDATION
Definition: logging.h:61
@ MEMPOOL
Definition: logging.h:42
@ NET
Definition: logging.h:40
constexpr auto DEFAULT_LOG_LEVEL
Definition: logging.h:82
util::Result< void > SetLoggingLevel(const ArgsManager &args)
Definition: common.cpp:62
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
const char * name
Definition: rest.cpp:45
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:41
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:21
Basic testing setup.
Definition: setup_common.h:49
ArgsManager m_args
Definition: setup_common.h:56
fs::path tmp_log_path
bool prev_reopen_file
fs::path prev_log_path
std::unordered_map< BCLog::LogFlags, BCLog::Level > prev_category_levels
bool prev_print_to_file
BCLog::Level prev_log_level
bool prev_log_threadnames
bool prev_log_sourcelocations
bool prev_log_timestamps