Bitcoin Core  27.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::Info, "foo2: %s\n", "bar2");
88  LogPrintf_("fn3", "src3", 3, BCLog::LogFlags::ALL, BCLog::Level::Debug, "foo3: %s\n", "bar3");
89  LogPrintf_("fn4", "src4", 4, BCLog::LogFlags::ALL, BCLog::Level::Info, "foo4: %s\n", "bar4");
90  LogPrintf_("fn5", "src5", 5, BCLog::LogFlags::NONE, BCLog::Level::Debug, "foo5: %s\n", "bar5");
91  LogPrintf_("fn6", "src6", 6, BCLog::LogFlags::NONE, BCLog::Level::Info, "foo6: %s\n", "bar6");
92  std::ifstream file{tmp_log_path};
93  std::vector<std::string> log_lines;
94  for (std::string log; std::getline(file, log);) {
95  log_lines.push_back(log);
96  }
97  std::vector<std::string> expected = {
98  "[src1:1] [fn1] [net] foo1: bar1",
99  "[src2:2] [fn2] [net:info] foo2: bar2",
100  "[src3:3] [fn3] [debug] foo3: bar3",
101  "[src4:4] [fn4] foo4: bar4",
102  "[src5:5] [fn5] [debug] foo5: bar5",
103  "[src6:6] [fn6] foo6: bar6",
104  };
105  BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
106 }
107 
108 BOOST_FIXTURE_TEST_CASE(logging_LogPrintMacrosDeprecated, LogSetup)
109 {
110  LogPrintf("foo5: %s\n", "bar5");
111  LogPrint(BCLog::NET, "foo6: %s\n", "bar6");
112  LogPrintLevel(BCLog::NET, BCLog::Level::Trace, "foo4: %s\n", "bar4"); // not logged
113  LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "foo7: %s\n", "bar7");
114  LogPrintLevel(BCLog::NET, BCLog::Level::Info, "foo8: %s\n", "bar8");
115  LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "foo9: %s\n", "bar9");
116  LogPrintLevel(BCLog::NET, BCLog::Level::Error, "foo10: %s\n", "bar10");
117  LogPrintfCategory(BCLog::VALIDATION, "foo11: %s\n", "bar11");
118  std::ifstream file{tmp_log_path};
119  std::vector<std::string> log_lines;
120  for (std::string log; std::getline(file, log);) {
121  log_lines.push_back(log);
122  }
123  std::vector<std::string> expected = {
124  "foo5: bar5",
125  "[net] foo6: bar6",
126  "[net] foo7: bar7",
127  "[net:info] foo8: bar8",
128  "[net:warning] foo9: bar9",
129  "[net:error] foo10: bar10",
130  "[validation:info] foo11: bar11",
131  };
132  BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
133 }
134 
135 BOOST_FIXTURE_TEST_CASE(logging_LogPrintMacros, LogSetup)
136 {
137  LogTrace(BCLog::NET, "foo6: %s\n", "bar6"); // not logged
138  LogDebug(BCLog::NET, "foo7: %s\n", "bar7");
139  LogInfo("foo8: %s\n", "bar8");
140  LogWarning("foo9: %s\n", "bar9");
141  LogError("foo10: %s\n", "bar10");
142  std::ifstream file{tmp_log_path};
143  std::vector<std::string> log_lines;
144  for (std::string log; std::getline(file, log);) {
145  log_lines.push_back(log);
146  }
147  std::vector<std::string> expected = {
148  "[net] foo7: bar7",
149  "foo8: bar8",
150  "[warning] foo9: bar9",
151  "[error] foo10: bar10",
152  };
153  BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
154 }
155 
156 BOOST_FIXTURE_TEST_CASE(logging_LogPrintMacros_CategoryName, LogSetup)
157 {
159  const auto concatenated_category_names = LogInstance().LogCategoriesString();
160  std::vector<std::pair<BCLog::LogFlags, std::string>> expected_category_names;
161  const auto category_names = SplitString(concatenated_category_names, ',');
162  for (const auto& category_name : category_names) {
163  BCLog::LogFlags category;
164  const auto trimmed_category_name = TrimString(category_name);
165  BOOST_REQUIRE(GetLogCategory(category, trimmed_category_name));
166  expected_category_names.emplace_back(category, trimmed_category_name);
167  }
168 
169  std::vector<std::string> expected;
170  for (const auto& [category, name] : expected_category_names) {
171  LogPrint(category, "foo: %s\n", "bar");
172  std::string expected_log = "[";
173  expected_log += name;
174  expected_log += "] foo: bar";
175  expected.push_back(expected_log);
176  }
177 
178  std::ifstream file{tmp_log_path};
179  std::vector<std::string> log_lines;
180  for (std::string log; std::getline(file, log);) {
181  log_lines.push_back(log);
182  }
183  BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
184 }
185 
186 BOOST_FIXTURE_TEST_CASE(logging_SeverityLevels, LogSetup)
187 {
189 
191  LogInstance().SetCategoryLogLevel(/*category_str=*/"net", /*level_str=*/"info");
192 
193  // Global log level
194  LogPrintLevel(BCLog::HTTP, BCLog::Level::Info, "foo1: %s\n", "bar1");
195  LogPrintLevel(BCLog::MEMPOOL, BCLog::Level::Trace, "foo2: %s. This log level is lower than the global one.\n", "bar2");
196  LogPrintLevel(BCLog::VALIDATION, BCLog::Level::Warning, "foo3: %s\n", "bar3");
197  LogPrintLevel(BCLog::RPC, BCLog::Level::Error, "foo4: %s\n", "bar4");
198 
199  // Category-specific log level
200  LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "foo5: %s\n", "bar5");
201  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");
202  LogPrintLevel(BCLog::NET, BCLog::Level::Error, "foo7: %s\n", "bar7");
203 
204  std::vector<std::string> expected = {
205  "[http:info] foo1: bar1",
206  "[validation:warning] foo3: bar3",
207  "[rpc:error] foo4: bar4",
208  "[net:warning] foo5: bar5",
209  "[net:error] foo7: bar7",
210  };
211  std::ifstream file{tmp_log_path};
212  std::vector<std::string> log_lines;
213  for (std::string log; std::getline(file, log);) {
214  log_lines.push_back(log);
215  }
216  BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
217 }
218 
220 {
221  // Set global log level
222  {
223  ResetLogger();
226  const char* argv_test[] = {"bitcoind", "-loglevel=debug"};
227  std::string err;
228  BOOST_REQUIRE(args.ParseParameters(2, argv_test, err));
229 
230  auto result = init::SetLoggingLevel(args);
231  BOOST_REQUIRE(result);
233  }
234 
235  // Set category-specific log level
236  {
237  ResetLogger();
240  const char* argv_test[] = {"bitcoind", "-loglevel=net:trace"};
241  std::string err;
242  BOOST_REQUIRE(args.ParseParameters(2, argv_test, err));
243 
244  auto result = init::SetLoggingLevel(args);
245  BOOST_REQUIRE(result);
247 
248  const auto& category_levels{LogInstance().CategoryLevels()};
249  const auto net_it{category_levels.find(BCLog::LogFlags::NET)};
250  BOOST_REQUIRE(net_it != category_levels.end());
251  BOOST_CHECK_EQUAL(net_it->second, BCLog::Level::Trace);
252  }
253 
254  // Set both global log level and category-specific log level
255  {
256  ResetLogger();
259  const char* argv_test[] = {"bitcoind", "-loglevel=debug", "-loglevel=net:trace", "-loglevel=http:info"};
260  std::string err;
261  BOOST_REQUIRE(args.ParseParameters(4, argv_test, err));
262 
263  auto result = init::SetLoggingLevel(args);
264  BOOST_REQUIRE(result);
266 
267  const auto& category_levels{LogInstance().CategoryLevels()};
268  BOOST_CHECK_EQUAL(category_levels.size(), 2);
269 
270  const auto net_it{category_levels.find(BCLog::LogFlags::NET)};
271  BOOST_CHECK(net_it != category_levels.end());
272  BOOST_CHECK_EQUAL(net_it->second, BCLog::Level::Trace);
273 
274  const auto http_it{category_levels.find(BCLog::LogFlags::HTTP)};
275  BOOST_CHECK(http_it != category_levels.end());
276  BOOST_CHECK_EQUAL(http_it->second, BCLog::Level::Info);
277  }
278 }
279 
ArgsManager & args
Definition: bitcoind.cpp:268
@ ALLOW_ANY
disable validation
Definition: args.h:104
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: args.cpp:177
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:562
bool m_log_sourcelocations
Definition: logging.h:121
void SetLogLevel(Level level)
Definition: logging.h:174
fs::path m_file_path
Definition: logging.h:124
std::unordered_map< LogFlags, Level > CategoryLevels() const
Definition: logging.h:161
bool m_log_threadnames
Definition: logging.h:120
void EnableCategory(LogFlags flag)
Definition: logging.cpp:95
bool m_log_timestamps
Definition: logging.h:118
std::atomic< bool > m_reopen_file
Definition: logging.h:125
bool m_print_to_file
Definition: logging.h:116
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels)
Definition: logging.h:166
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:190
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:33
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:197
BCLog::Logger & LogInstance()
Definition: logging.cpp:19
#define LogPrintLevel(category, level,...)
Definition: logging.h:251
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:222
#define LogWarning(...)
Definition: logging.h:240
#define LogPrint(category,...)
Definition: logging.h:263
#define LogInfo(...)
Definition: logging.h:239
#define LogError(...)
Definition: logging.h:241
#define LogTrace(category,...)
Definition: logging.h:260
#define LogDebug(category,...)
Definition: logging.h:259
#define LogPrintfCategory(category,...)
Definition: logging.h:245
#define LogPrintf(...)
Definition: logging.h:244
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:39
@ ALL
Definition: logging.h:72
@ RPC
Definition: logging.h:48
@ HTTP
Definition: logging.h:44
@ NONE
Definition: logging.h:40
@ VALIDATION
Definition: logging.h:62
@ MEMPOOL
Definition: logging.h:43
@ NET
Definition: logging.h:41
constexpr auto DEFAULT_LOG_LEVEL
Definition: logging.h:81
util::Result< void > SetLoggingLevel(const ArgsManager &args)
Definition: common.cpp:64
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
const char * name
Definition: rest.cpp:50
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:52
ArgsManager m_args
Definition: setup_common.h:62
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