Skip to content

Commit a6a35cc

Browse files
Crypt-iQdergoeggestickies-v
committed
log: use std::source_location in place of __func__, __FILE__, __LINE__
The std::source_location conveniently stores the file name, line number, and function name of a source code location. We switch to using it instead of the __func__ identifier and the __FILE__ and __LINE__ macros. BufferedLog is changed to have a std::source_location member, replacing the source_file, source_line, and logging_function members. As a result, MemUsage no longer explicitly counts source_file or logging_function as the std::source_location memory usage is included in the MallocUsage call. This also changes the behavior of -logsourcelocations as std::source_location includes the entire function signature. Because of this, the functional test feature_config_args.py must be changed to no longer include the function signature as the function signature can differ across platforms. Co-Authored-By: Niklas Gogge <[email protected]> Co-Authored-By: stickies-v <[email protected]>
1 parent afb9e39 commit a6a35cc

File tree

4 files changed

+56
-41
lines changed

4 files changed

+56
-41
lines changed

src/logging.cpp

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,10 @@
1212
#include <util/time.h>
1313

1414
#include <array>
15+
#include <cstring>
1516
#include <map>
1617
#include <optional>
18+
#include <utility>
1719

1820
using util::Join;
1921
using util::RemovePrefixView;
@@ -73,12 +75,12 @@ bool BCLog::Logger::StartLogging()
7375
// dump buffered messages from before we opened the log
7476
m_buffering = false;
7577
if (m_buffer_lines_discarded > 0) {
76-
LogPrintStr_(strprintf("Early logging buffer overflowed, %d log lines discarded.\n", m_buffer_lines_discarded), __func__, __FILE__, __LINE__, BCLog::ALL, Level::Info);
78+
LogPrintStr_(strprintf("Early logging buffer overflowed, %d log lines discarded.\n", m_buffer_lines_discarded), std::source_location::current(), BCLog::ALL, Level::Info);
7779
}
7880
while (!m_msgs_before_open.empty()) {
7981
const auto& buflog = m_msgs_before_open.front();
8082
std::string s{buflog.str};
81-
FormatLogStrInPlace(s, buflog.category, buflog.level, buflog.source_file, buflog.source_line, buflog.logging_function, buflog.threadname, buflog.now, buflog.mocktime);
83+
FormatLogStrInPlace(s, buflog.category, buflog.level, buflog.source_loc, buflog.threadname, buflog.now, buflog.mocktime);
8284
m_msgs_before_open.pop_front();
8385

8486
if (m_print_to_file) FileWriteStr(s, m_fileout);
@@ -364,7 +366,9 @@ std::string BCLog::Logger::GetLogPrefix(BCLog::LogFlags category, BCLog::Level l
364366

365367
static size_t MemUsage(const BCLog::Logger::BufferedLog& buflog)
366368
{
367-
return buflog.str.size() + buflog.logging_function.size() + buflog.source_file.size() + buflog.threadname.size() + memusage::MallocUsage(sizeof(memusage::list_node<BCLog::Logger::BufferedLog>));
369+
return memusage::DynamicUsage(buflog.str) +
370+
memusage::DynamicUsage(buflog.threadname) +
371+
memusage::MallocUsage(sizeof(memusage::list_node<BCLog::Logger::BufferedLog>));
368372
}
369373

370374
BCLog::LogRateLimiter::LogRateLimiter(
@@ -391,14 +395,14 @@ BCLog::LogRateLimiter::Status BCLog::LogRateLimiter::Consume(
391395
return status;
392396
}
393397

394-
void BCLog::Logger::FormatLogStrInPlace(std::string& str, BCLog::LogFlags category, BCLog::Level level, std::string_view source_file, int source_line, std::string_view logging_function, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const
398+
void BCLog::Logger::FormatLogStrInPlace(std::string& str, BCLog::LogFlags category, BCLog::Level level, const std::source_location& source_loc, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const
395399
{
396400
if (!str.ends_with('\n')) str.push_back('\n');
397401

398402
str.insert(0, GetLogPrefix(category, level));
399403

400404
if (m_log_sourcelocations) {
401-
str.insert(0, strprintf("[%s:%d] [%s] ", RemovePrefixView(source_file, "./"), source_line, logging_function));
405+
str.insert(0, strprintf("[%s:%d] [%s] ", RemovePrefixView(source_loc.file_name(), "./"), source_loc.line(), source_loc.function_name()));
402406
}
403407

404408
if (m_log_threadnames) {
@@ -408,28 +412,26 @@ void BCLog::Logger::FormatLogStrInPlace(std::string& str, BCLog::LogFlags catego
408412
str.insert(0, LogTimestampStr(now, mocktime));
409413
}
410414

411-
void BCLog::Logger::LogPrintStr(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
415+
void BCLog::Logger::LogPrintStr(std::string_view str, std::source_location&& source_loc, BCLog::LogFlags category, BCLog::Level level)
412416
{
413417
StdLockGuard scoped_lock(m_cs);
414-
return LogPrintStr_(str, logging_function, source_file, source_line, category, level);
418+
return LogPrintStr_(str, std::move(source_loc), category, level);
415419
}
416420

417-
void BCLog::Logger::LogPrintStr_(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
421+
void BCLog::Logger::LogPrintStr_(std::string_view str, std::source_location&& source_loc, BCLog::LogFlags category, BCLog::Level level)
418422
{
419423
std::string str_prefixed = LogEscapeMessage(str);
420424

421425
if (m_buffering) {
422426
{
423427
BufferedLog buf{
424-
.now=SystemClock::now(),
425-
.mocktime=GetMockTime(),
426-
.str=str_prefixed,
427-
.logging_function=std::string(logging_function),
428-
.source_file=std::string(source_file),
429-
.threadname=util::ThreadGetInternalName(),
430-
.source_line=source_line,
431-
.category=category,
432-
.level=level,
428+
.now = SystemClock::now(),
429+
.mocktime = GetMockTime(),
430+
.str = str_prefixed,
431+
.threadname = util::ThreadGetInternalName(),
432+
.source_loc = std::move(source_loc),
433+
.category = category,
434+
.level = level,
433435
};
434436
m_cur_buffer_memusage += MemUsage(buf);
435437
m_msgs_before_open.push_back(std::move(buf));
@@ -448,7 +450,7 @@ void BCLog::Logger::LogPrintStr_(std::string_view str, std::string_view logging_
448450
return;
449451
}
450452

451-
FormatLogStrInPlace(str_prefixed, category, level, source_file, source_line, logging_function, util::ThreadGetInternalName(), SystemClock::now(), GetMockTime());
453+
FormatLogStrInPlace(str_prefixed, category, level, source_loc, util::ThreadGetInternalName(), SystemClock::now(), GetMockTime());
452454

453455
if (m_print_to_console) {
454456
// print to console

src/logging.h

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,8 @@ namespace BCLog {
184184
struct BufferedLog {
185185
SystemClock::time_point now;
186186
std::chrono::seconds mocktime;
187-
std::string str, logging_function, source_file, threadname;
188-
int source_line;
187+
std::string str, threadname;
188+
std::source_location source_loc;
189189
LogFlags category;
190190
Level level;
191191
};
@@ -210,15 +210,15 @@ namespace BCLog {
210210
/** Log categories bitfield. */
211211
std::atomic<CategoryMask> m_categories{BCLog::NONE};
212212

213-
void FormatLogStrInPlace(std::string& str, LogFlags category, Level level, std::string_view source_file, int source_line, std::string_view logging_function, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const;
213+
void FormatLogStrInPlace(std::string& str, LogFlags category, Level level, const std::source_location& source_loc, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const;
214214

215215
std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const;
216216

217217
/** Slots that connect to the print signal */
218218
std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
219219

220220
/** Send a string to the log output (internal) */
221-
void LogPrintStr_(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
221+
void LogPrintStr_(std::string_view str, std::source_location&& source_loc, BCLog::LogFlags category, BCLog::Level level)
222222
EXCLUSIVE_LOCKS_REQUIRED(m_cs);
223223

224224
std::string GetLogPrefix(LogFlags category, Level level) const;
@@ -237,7 +237,7 @@ namespace BCLog {
237237
std::atomic<bool> m_reopen_file{false};
238238

239239
/** Send a string to the log output */
240-
void LogPrintStr(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
240+
void LogPrintStr(std::string_view str, std::source_location&& source_loc, BCLog::LogFlags category, BCLog::Level level)
241241
EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
242242

243243
/** Returns whether logs will be written to any output */
@@ -334,7 +334,7 @@ static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level leve
334334
bool GetLogCategory(BCLog::LogFlags& flag, std::string_view str);
335335

336336
template <typename... Args>
337-
inline void LogPrintFormatInternal(std::string_view logging_function, std::string_view source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args)
337+
inline void LogPrintFormatInternal(std::source_location&& source_loc, const BCLog::LogFlags flag, const BCLog::Level level, util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args)
338338
{
339339
if (LogInstance().Enabled()) {
340340
std::string log_msg;
@@ -343,11 +343,11 @@ inline void LogPrintFormatInternal(std::string_view logging_function, std::strin
343343
} catch (tinyformat::format_error& fmterr) {
344344
log_msg = "Error \"" + std::string{fmterr.what()} + "\" while formatting log message: " + fmt.fmt;
345345
}
346-
LogInstance().LogPrintStr(log_msg, logging_function, source_file, source_line, flag, level);
346+
LogInstance().LogPrintStr(log_msg, std::move(source_loc), flag, level);
347347
}
348348
}
349349

350-
#define LogPrintLevel_(category, level, ...) LogPrintFormatInternal(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
350+
#define LogPrintLevel_(category, level, ...) LogPrintFormatInternal(std::source_location::current(), category, level, __VA_ARGS__)
351351

352352
// Log unconditionally.
353353
// Be conservative when using functions that unconditionally log to debug.log!

src/test/logging_tests.cpp

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,16 @@
77
#include <logging/timer.h>
88
#include <scheduler.h>
99
#include <test/util/setup_common.h>
10+
#include <tinyformat.h>
11+
#include <util/fs.h>
12+
#include <util/fs_helpers.h>
1013
#include <util/string.h>
1114

1215
#include <chrono>
1316
#include <fstream>
1417
#include <future>
1518
#include <iostream>
19+
#include <source_location>
1620
#include <unordered_map>
1721
#include <utility>
1822
#include <vector>
@@ -88,25 +92,34 @@ BOOST_AUTO_TEST_CASE(logging_timer)
8892
BOOST_FIXTURE_TEST_CASE(logging_LogPrintStr, LogSetup)
8993
{
9094
LogInstance().m_log_sourcelocations = true;
91-
LogInstance().LogPrintStr("foo1: bar1", "fn1", "src1", 1, BCLog::LogFlags::NET, BCLog::Level::Debug);
92-
LogInstance().LogPrintStr("foo2: bar2", "fn2", "src2", 2, BCLog::LogFlags::NET, BCLog::Level::Info);
93-
LogInstance().LogPrintStr("foo3: bar3", "fn3", "src3", 3, BCLog::LogFlags::ALL, BCLog::Level::Debug);
94-
LogInstance().LogPrintStr("foo4: bar4", "fn4", "src4", 4, BCLog::LogFlags::ALL, BCLog::Level::Info);
95-
LogInstance().LogPrintStr("foo5: bar5", "fn5", "src5", 5, BCLog::LogFlags::NONE, BCLog::Level::Debug);
96-
LogInstance().LogPrintStr("foo6: bar6", "fn6", "src6", 6, BCLog::LogFlags::NONE, BCLog::Level::Info);
95+
96+
struct Case {
97+
std::string msg;
98+
BCLog::LogFlags category;
99+
BCLog::Level level;
100+
std::string prefix;
101+
std::source_location loc;
102+
};
103+
104+
std::vector<Case> cases = {
105+
{"foo1: bar1", BCLog::NET, BCLog::Level::Debug, "[net] ", std::source_location::current()},
106+
{"foo2: bar2", BCLog::NET, BCLog::Level::Info, "[net:info] ", std::source_location::current()},
107+
{"foo3: bar3", BCLog::ALL, BCLog::Level::Debug, "[debug] ", std::source_location::current()},
108+
{"foo4: bar4", BCLog::ALL, BCLog::Level::Info, "", std::source_location::current()},
109+
{"foo5: bar5", BCLog::NONE, BCLog::Level::Debug, "[debug] ", std::source_location::current()},
110+
{"foo6: bar6", BCLog::NONE, BCLog::Level::Info, "", std::source_location::current()},
111+
};
112+
113+
std::vector<std::string> expected;
114+
for (auto& [msg, category, level, prefix, loc] : cases) {
115+
expected.push_back(tfm::format("[%s:%s] [%s] %s%s", util::RemovePrefix(loc.file_name(), "./"), loc.line(), loc.function_name(), prefix, msg));
116+
LogInstance().LogPrintStr(msg, std::move(loc), category, level);
117+
}
97118
std::ifstream file{tmp_log_path};
98119
std::vector<std::string> log_lines;
99120
for (std::string log; std::getline(file, log);) {
100121
log_lines.push_back(log);
101122
}
102-
std::vector<std::string> expected = {
103-
"[src1:1] [fn1] [net] foo1: bar1",
104-
"[src2:2] [fn2] [net:info] foo2: bar2",
105-
"[src3:3] [fn3] [debug] foo3: bar3",
106-
"[src4:4] [fn4] foo4: bar4",
107-
"[src5:5] [fn5] [debug] foo5: bar5",
108-
"[src6:6] [fn6] foo6: bar6",
109-
};
110123
BOOST_CHECK_EQUAL_COLLECTIONS(log_lines.begin(), log_lines.end(), expected.begin(), expected.end());
111124
}
112125

test/functional/feature_config_args.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def test_negated_config(self):
8282

8383
self.log.debug('Verifying that disabling of the config file means garbage inside of it does ' \
8484
'not prevent the node from starting, and message about existing config file is logged')
85-
ignored_file_message = [f'[InitConfig] Data directory "{self.nodes[0].datadir_path}" contains a "bitcoin.conf" file which is explicitly ignored using -noconf.']
85+
ignored_file_message = [f'Data directory "{self.nodes[0].datadir_path}" contains a "bitcoin.conf" file which is explicitly ignored using -noconf.']
8686
with self.nodes[0].assert_debug_log(timeout=60, expected_msgs=ignored_file_message):
8787
self.start_node(0, extra_args=settings + ['-noconf'])
8888
self.stop_node(0)

0 commit comments

Comments
 (0)