Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #ifndef BITCOIN_LOGGING_H
7 : : #define BITCOIN_LOGGING_H
8 : :
9 : : #include <crypto/siphash.h>
10 : : #include <threadsafety.h>
11 : : #include <tinyformat.h>
12 : : #include <util/check.h>
13 : : #include <util/fs.h>
14 : : #include <util/string.h>
15 : : #include <util/time.h>
16 : :
17 : : #include <atomic>
18 : : #include <cstdint>
19 : : #include <cstring>
20 : : #include <functional>
21 : : #include <list>
22 : : #include <memory>
23 : : #include <mutex>
24 : : #include <source_location>
25 : : #include <string>
26 : : #include <unordered_map>
27 : : #include <unordered_set>
28 : : #include <vector>
29 : :
30 : : static const bool DEFAULT_LOGTIMEMICROS = false;
31 : : static const bool DEFAULT_LOGIPS = false;
32 : : static const bool DEFAULT_LOGTIMESTAMPS = true;
33 : : static const bool DEFAULT_LOGTHREADNAMES = false;
34 : : static const bool DEFAULT_LOGSOURCELOCATIONS = false;
35 : : static constexpr bool DEFAULT_LOGLEVELALWAYS = false;
36 : : extern const char * const DEFAULT_DEBUGLOGFILE;
37 : :
38 : : extern bool fLogIPs;
39 : :
40 : : /// Like std::source_location, but allowing to override the function name.
41 : : class SourceLocation
42 : : {
43 : : public:
44 : : /// The func argument must be constructed from the C++11 __func__ macro.
45 : : /// Ref: https://en.cppreference.com/w/cpp/language/function.html#func
46 : : /// Non-static string literals are not supported.
47 : 5661288 : SourceLocation(const char* func,
48 : : std::source_location loc = std::source_location::current())
49 [ + - + - : 5660210 : : m_func{func}, m_loc{loc} {}
+ - ][ + -
+ - + - +
- + - + -
+ - + - ]
[ + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
- - - - +
- - - - -
- - + - +
- + - - -
- - + - -
- + - - -
- - - - -
- - - + -
+ - - - +
- - - + -
+ - + - +
- + - + -
+ - + - -
- - - ][ +
- + - # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ - - +
- + - + -
+ - - - -
- - - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - ][ + -
+ - + - +
- + - - -
+ - - - -
- + - - -
+ - + - +
- + - + -
+ - + - -
- + - + -
+ - + - +
- + - - -
- - + - +
- + - + -
- - + - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
+ - + - -
- + - - -
- - - - +
- - - - -
+ - + - -
- + - + -
- - + - +
- - - + -
+ - + - +
- + - + -
- - - - -
- + - + -
- - + - +
- + - + -
- - - - +
- + - - -
- - - - +
- + - + -
+ - + - +
- + - + -
- - - - +
- + - + -
+ - + - +
- + - - -
+ - - - ]
[ + - - -
- - + - +
- + - + -
+ - + - -
- - - + -
+ - - - +
- + - + -
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ + - +
- - - - -
+ - + - +
- + - + -
+ - + - +
- + - # #
# # # # #
# ][ - - +
- + - + -
+ - + - +
- + - + -
+ - - - +
- + - + -
+ - + - +
- + - + -
+ - - - +
- + - + -
+ - + - +
- - - + -
+ - - - +
- + - - -
- - + - +
- + - + -
+ - - - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- - - + -
+ - + - -
- - - + -
- - + - -
- - - - -
+ - + - +
- - - + -
+ - + - +
- + - + -
+ - + - +
- - - + -
- - - - -
- - - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - -
- + - + -
+ - + - +
- + - - -
- - - - -
- + - + -
+ - + - +
- + - + -
+ - + - +
- - - + -
+ - + - +
- + - + -
+ - - - +
- + - + -
- - - - -
- - - + -
+ - + - +
- + - + -
+ - + - +
- ][ + - -
- + - + -
+ - ][ - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - -
- ][ + - -
- - - - -
- - - - -
- - - - -
- - + - -
- + - - -
- - + - -
- - - - -
- - - - -
- - - - -
- - - - -
- + - -
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ + - - +
- + - + -
+ - - - +
- - - + -
+ - + - -
- ][ + - +
- + - - -
- - + - +
- + - + -
+ - + - +
- - - - -
+ - - - +
- - - - -
- - - - -
- ][ + - +
- + - + -
+ - - - -
- - - - -
- - - - ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- - - ][ +
- + - + -
+ - - - -
- - - - -
- - - - -
- - - - -
+ - # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
- - - - -
- - - - +
- + - + -
- - - - +
- - - - -
+ - - - +
- + - - -
- - + - -
- + - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - + -
+ - - - -
- ][ - - +
- + - - -
+ - + - +
- + - + -
+ - + - -
- + - + -
+ - + - +
- + - + -
+ - - - +
- + - + -
+ - - - -
- - - - -
- - - - +
- - - + -
+ - + - +
- + - + -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - +
- - - + -
- - - - +
- + - + -
- - ][ + -
+ - + - +
- + - + -
+ - + - +
- - - - -
- - - - -
- + - - -
- - - - +
- - - + -
+ - + - +
- + - + -
+ - + - -
- - - - -
+ - - - -
- + - - -
+ - + - -
- + - + -
+ - + - -
- - - + -
+ - + - +
- - - - -
- - + - -
- + - - -
- - + - +
- + - + -
+ - + - -
- + - - -
+ - + - -
- + - - -
- - + - +
- - - ][ +
- # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
50 : :
51 [ + - ]: 5638646 : std::string_view file_name() const { return m_loc.file_name(); }
52 [ + - - - : 5638371 : std::uint_least32_t line() const { return m_loc.line(); }
- - ][ + -
+ - + - ]
53 [ + - - - : 5638370 : std::string_view function_name_short() const { return m_func; }
+ - ][ + -
+ - + - ]
54 : :
55 : : private:
56 : : std::string_view m_func;
57 : : std::source_location m_loc;
58 : : };
59 : :
60 : : struct SourceLocationEqual {
61 : 73 : bool operator()(const SourceLocation& lhs, const SourceLocation& rhs) const noexcept
62 : : {
63 [ + - + - : 219 : return lhs.line() == rhs.line() && std::string_view(lhs.file_name()) == std::string_view(rhs.file_name());
+ + - + ]
64 : : }
65 : : };
66 : :
67 : : struct SourceLocationHasher {
68 : 194 : size_t operator()(const SourceLocation& s) const noexcept
69 : : {
70 : : // Use CSipHasher(0, 0) as a simple way to get uniform distribution.
71 [ + - ]: 194 : return size_t(CSipHasher(0, 0)
72 : 194 : .Write(s.line())
73 : 194 : .Write(MakeUCharSpan(std::string_view{s.file_name()}))
74 : 194 : .Finalize());
75 : : }
76 : : };
77 : :
78 : 548190 : struct LogCategory {
79 : : std::string category;
80 : : bool active;
81 : : };
82 : :
83 : : namespace BCLog {
84 : : using CategoryMask = uint64_t;
85 : : enum LogFlags : CategoryMask {
86 : : NONE = CategoryMask{0},
87 : : NET = (CategoryMask{1} << 0),
88 : : TOR = (CategoryMask{1} << 1),
89 : : MEMPOOL = (CategoryMask{1} << 2),
90 : : HTTP = (CategoryMask{1} << 3),
91 : : BENCH = (CategoryMask{1} << 4),
92 : : ZMQ = (CategoryMask{1} << 5),
93 : : WALLETDB = (CategoryMask{1} << 6),
94 : : RPC = (CategoryMask{1} << 7),
95 : : ESTIMATEFEE = (CategoryMask{1} << 8),
96 : : ADDRMAN = (CategoryMask{1} << 9),
97 : : SELECTCOINS = (CategoryMask{1} << 10),
98 : : REINDEX = (CategoryMask{1} << 11),
99 : : CMPCTBLOCK = (CategoryMask{1} << 12),
100 : : RAND = (CategoryMask{1} << 13),
101 : : PRUNE = (CategoryMask{1} << 14),
102 : : PROXY = (CategoryMask{1} << 15),
103 : : MEMPOOLREJ = (CategoryMask{1} << 16),
104 : : LIBEVENT = (CategoryMask{1} << 17),
105 : : COINDB = (CategoryMask{1} << 18),
106 : : QT = (CategoryMask{1} << 19),
107 : : LEVELDB = (CategoryMask{1} << 20),
108 : : VALIDATION = (CategoryMask{1} << 21),
109 : : I2P = (CategoryMask{1} << 22),
110 : : IPC = (CategoryMask{1} << 23),
111 : : #ifdef DEBUG_LOCKCONTENTION
112 : : LOCK = (CategoryMask{1} << 24),
113 : : #endif
114 : : BLOCKSTORAGE = (CategoryMask{1} << 25),
115 : : TXRECONCILIATION = (CategoryMask{1} << 26),
116 : : SCAN = (CategoryMask{1} << 27),
117 : : TXPACKAGES = (CategoryMask{1} << 28),
118 : : KERNEL = (CategoryMask{1} << 29),
119 : : PRIVBROADCAST = (CategoryMask{1} << 30),
120 : : ALL = ~NONE,
121 : : };
122 : : enum class Level {
123 : : Trace = 0, // High-volume or detailed logging for development/debugging
124 : : Debug, // Reasonably noisy logging, but still usable in production
125 : : Info, // Default
126 : : Warning,
127 : : Error,
128 : : };
129 : : constexpr auto DEFAULT_LOG_LEVEL{Level::Debug};
130 : : constexpr size_t DEFAULT_MAX_LOG_BUFFER{1'000'000}; // buffer up to 1MB of log data prior to StartLogging
131 : : constexpr uint64_t RATELIMIT_MAX_BYTES{1024 * 1024}; // maximum number of bytes per source location that can be logged within the RATELIMIT_WINDOW
132 : : constexpr auto RATELIMIT_WINDOW{1h}; // time window after which log ratelimit stats are reset
133 : : constexpr bool DEFAULT_LOGRATELIMIT{true};
134 : :
135 : : //! Fixed window rate limiter for logging.
136 : 2 : class LogRateLimiter
137 : : {
138 : : public:
139 : : //! Keeps track of an individual source location and how many available bytes are left for logging from it.
140 : : struct Stats {
141 : : //! Remaining bytes
142 : : uint64_t m_available_bytes;
143 : : //! Number of bytes that were consumed but didn't fit in the available bytes.
144 : : uint64_t m_dropped_bytes{0};
145 : :
146 : 53 : Stats(uint64_t max_bytes) : m_available_bytes{max_bytes} {}
147 : : //! Updates internal accounting and returns true if enough available_bytes were remaining
148 : : bool Consume(uint64_t bytes);
149 : : };
150 : :
151 : : private:
152 : : mutable StdMutex m_mutex;
153 : :
154 : : //! Stats for each source location that has attempted to log something.
155 : : std::unordered_map<SourceLocation, Stats, SourceLocationHasher, SourceLocationEqual> m_source_locations GUARDED_BY(m_mutex);
156 : : //! Whether any log locations are suppressed. Cached view on m_source_locations for performance reasons.
157 : : std::atomic<bool> m_suppression_active{false};
158 : : LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window);
159 : :
160 : : public:
161 : : using SchedulerFunction = std::function<void(std::function<void()>, std::chrono::milliseconds)>;
162 : : /**
163 : : * @param scheduler_func Callable object used to schedule resetting the window. The first
164 : : * parameter is the function to be executed, and the second is the
165 : : * reset_window interval.
166 : : * @param max_bytes Maximum number of bytes that can be logged for each source
167 : : * location.
168 : : * @param reset_window Time window after which the stats are reset.
169 : : */
170 : : static std::shared_ptr<LogRateLimiter> Create(
171 : : SchedulerFunction&& scheduler_func,
172 : : uint64_t max_bytes,
173 : : std::chrono::seconds reset_window);
174 : : //! Maximum number of bytes logged per location per window.
175 : : const uint64_t m_max_bytes;
176 : : //! Interval after which the window is reset.
177 : : const std::chrono::seconds m_reset_window;
178 : : //! Suppression status of a source log location.
179 : : enum class Status {
180 : : UNSUPPRESSED, // string fits within the limit
181 : : NEWLY_SUPPRESSED, // suppression has started since this string
182 : : STILL_SUPPRESSED, // suppression is still ongoing
183 : : };
184 : : //! Consumes `source_loc`'s available bytes corresponding to the size of the (formatted)
185 : : //! `str` and returns its status.
186 : : [[nodiscard]] Status Consume(
187 : : const SourceLocation& source_loc,
188 : : const std::string& str) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
189 : : //! Resets all usage to zero. Called periodically by the scheduler.
190 : : void Reset() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
191 : : //! Returns true if any log locations are currently being suppressed.
192 [ + - + - : 175 : bool SuppressionsActive() const { return m_suppression_active; }
+ - + - +
- + - +
- ][ + + ]
193 : : };
194 : :
195 : : class Logger
196 : : {
197 : : public:
198 : 36640 : struct BufferedLog {
199 : : SystemClock::time_point now;
200 : : std::chrono::seconds mocktime;
201 : : std::string str, threadname;
202 : : SourceLocation source_loc;
203 : : LogFlags category;
204 : : Level level;
205 : : };
206 : :
207 : : private:
208 : : mutable StdMutex m_cs; // Can not use Mutex from sync.h because in debug mode it would cause a deadlock when a potential deadlock was detected
209 : :
210 : : FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
211 : : std::list<BufferedLog> m_msgs_before_open GUARDED_BY(m_cs);
212 : : bool m_buffering GUARDED_BY(m_cs) = true; //!< Buffer messages before logging can be started.
213 : : size_t m_max_buffer_memusage GUARDED_BY(m_cs){DEFAULT_MAX_LOG_BUFFER};
214 : : size_t m_cur_buffer_memusage GUARDED_BY(m_cs){0};
215 : : size_t m_buffer_lines_discarded GUARDED_BY(m_cs){0};
216 : :
217 : : //! Manages the rate limiting of each log location.
218 : : std::shared_ptr<LogRateLimiter> m_limiter GUARDED_BY(m_cs);
219 : :
220 : : //! Category-specific log level. Overrides `m_log_level`.
221 : : std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs);
222 : :
223 : : //! If there is no category-specific log level, all logs with a severity
224 : : //! level lower than `m_log_level` will be ignored.
225 : : std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL};
226 : :
227 : : /** Log categories bitfield. */
228 : : std::atomic<CategoryMask> m_categories{BCLog::NONE};
229 : :
230 : : void FormatLogStrInPlace(std::string& str, LogFlags category, Level level, const SourceLocation& source_loc, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const;
231 : :
232 : : std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const;
233 : :
234 : : /** Slots that connect to the print signal */
235 : : std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
236 : :
237 : : /** Send a string to the log output (internal) */
238 : : void LogPrintStr_(std::string_view str, SourceLocation&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
239 : : EXCLUSIVE_LOCKS_REQUIRED(m_cs);
240 : :
241 : : std::string GetLogPrefix(LogFlags category, Level level) const;
242 : :
243 : : public:
244 : : bool m_print_to_console = false;
245 : : bool m_print_to_file = false;
246 : :
247 : : bool m_log_timestamps = DEFAULT_LOGTIMESTAMPS;
248 : : bool m_log_time_micros = DEFAULT_LOGTIMEMICROS;
249 : : bool m_log_threadnames = DEFAULT_LOGTHREADNAMES;
250 : : bool m_log_sourcelocations = DEFAULT_LOGSOURCELOCATIONS;
251 : : bool m_always_print_category_level = DEFAULT_LOGLEVELALWAYS;
252 : :
253 : : fs::path m_file_path;
254 : : std::atomic<bool> m_reopen_file{false};
255 : :
256 : : /** Send a string to the log output */
257 : : void LogPrintStr(std::string_view str, SourceLocation&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
258 : : EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
259 : :
260 : : /** Returns whether logs will be written to any output */
261 : 5661280 : bool Enabled() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
262 : : {
263 : 5661280 : StdLockGuard scoped_lock(m_cs);
264 [ + + + - : 5661424 : return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
+ + + + ]
265 : 5661280 : }
266 : :
267 : : /** Connect a slot to the print signal and return the connection */
268 : 703 : std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
269 : : {
270 : 703 : StdLockGuard scoped_lock(m_cs);
271 [ + - ]: 703 : m_print_callbacks.push_back(std::move(fun));
272 : 703 : return --m_print_callbacks.end();
273 : 703 : }
274 : :
275 : : /** Delete a connection */
276 : 64 : void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
277 : : {
278 : 64 : StdLockGuard scoped_lock(m_cs);
279 : 64 : m_print_callbacks.erase(it);
280 : 64 : }
281 : :
282 : 16 : size_t NumConnections()
283 : : {
284 : 16 : StdLockGuard scoped_lock(m_cs);
285 : 16 : return m_print_callbacks.size();
286 : 16 : }
287 : :
288 : : /** Start logging (and flush all buffered messages) */
289 : : bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
290 : : /** Only for testing */
291 : : void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
292 : :
293 : 14 : void SetRateLimiting(std::shared_ptr<LogRateLimiter> limiter) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
294 : : {
295 : 14 : StdLockGuard scoped_lock(m_cs);
296 : 14 : m_limiter = std::move(limiter);
297 : 14 : }
298 : :
299 : : /** Disable logging
300 : : * This offers a slight speedup and slightly smaller memory usage
301 : : * compared to leaving the logging system in its default state.
302 : : * Mostly intended for libbitcoin-kernel apps that don't want any logging.
303 : : * Should be used instead of StartLogging().
304 : : */
305 : : void DisableLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
306 : :
307 : : void ShrinkDebugFile();
308 : :
309 : 8 : std::unordered_map<LogFlags, Level> CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
310 : : {
311 : 8 : StdLockGuard scoped_lock(m_cs);
312 [ + - ]: 8 : return m_category_log_levels;
313 : 8 : }
314 : 15 : void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
315 : : {
316 : 15 : StdLockGuard scoped_lock(m_cs);
317 [ + - ]: 15 : m_category_log_levels = levels;
318 : 15 : }
319 : 2 : void AddCategoryLogLevel(LogFlags category, Level level)
320 : : {
321 : 2 : StdLockGuard scoped_lock(m_cs);
322 [ + - ]: 2 : m_category_log_levels[category] = level;
323 : 2 : }
324 : : bool SetCategoryLogLevel(std::string_view category_str, std::string_view level_str) EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
325 : :
326 [ + - + - : 5214924 : Level LogLevel() const { return m_log_level.load(); }
+ - + - ]
[ + - # #
# # # # ]
327 [ + - ]: 22 : void SetLogLevel(Level level) { m_log_level = level; }
328 : : bool SetLogLevel(std::string_view level);
329 : :
330 [ + + ]: 26 : CategoryMask GetCategoryMask() const { return m_categories.load(); }
331 : :
332 : : void EnableCategory(LogFlags flag);
333 : : bool EnableCategory(std::string_view str);
334 : : void DisableCategory(LogFlags flag);
335 : : bool DisableCategory(std::string_view str);
336 : :
337 : : bool WillLogCategory(LogFlags category) const;
338 : : bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
339 : :
340 : : /** Returns a vector of the log categories in alphabetical order. */
341 : : std::vector<LogCategory> LogCategoriesList() const;
342 : : /** Returns a string with the log categories in alphabetical order. */
343 : 6081 : std::string LogCategoriesString() const
344 : : {
345 [ + - - + : 370941 : return util::Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
- + ]
346 : : };
347 : :
348 : : //! Returns a string with all user-selectable log levels.
349 : : std::string LogLevelsString() const;
350 : :
351 : : //! Returns the string representation of a log level.
352 : : static std::string LogLevelToStr(BCLog::Level level);
353 : :
354 : : bool DefaultShrinkDebugFile() const;
355 : : };
356 : :
357 : : } // namespace BCLog
358 : :
359 : : BCLog::Logger& LogInstance();
360 : :
361 : : /** Return true if log accepts specified category, at the specified level. */
362 : 5278025 : static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
363 : : {
364 : 5278025 : return LogInstance().WillLogCategoryLevel(category, level);
365 : : }
366 : :
367 : : /** Return true if str parses as a log category and set the flag */
368 : : bool GetLogCategory(BCLog::LogFlags& flag, std::string_view str);
369 : :
370 : : template <typename... Args>
371 : 5661280 : inline void LogPrintFormatInternal(SourceLocation&& source_loc, BCLog::LogFlags flag, BCLog::Level level, bool should_ratelimit, util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args)
372 : : {
373 [ + + ]: 5661280 : if (LogInstance().Enabled()) {
374 [ + - ]: 5661119 : std::string log_msg;
375 : : try {
376 [ + - ]: 5661119 : log_msg = tfm::format(fmt, args...);
377 [ - - ]: 0 : } catch (tinyformat::format_error& fmterr) {
378 [ - - - - : 0 : log_msg = "Error \"" + std::string{fmterr.what()} + "\" while formatting log message: " + fmt.fmt;
- - ]
379 : : }
380 [ + - - + : 5661119 : LogInstance().LogPrintStr(log_msg, std::move(source_loc), flag, level, should_ratelimit);
+ - ]
381 : 5661119 : }
382 : 5661280 : }
383 : :
384 : : // Allow __func__ to be used in any context without warnings:
385 : : // NOLINTNEXTLINE(bugprone-lambda-function-name)
386 : : #define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(SourceLocation{__func__}, category, level, should_ratelimit, __VA_ARGS__)
387 : :
388 : : // Log unconditionally. Uses basic rate limiting to mitigate disk filling attacks.
389 : : // Be conservative when using functions that unconditionally log to debug.log!
390 : : // It should not be the case that an inbound peer can fill up a user's storage
391 : : // with debug.log entries.
392 : : #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
393 : : #define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, /*should_ratelimit=*/true, __VA_ARGS__)
394 : : #define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
395 : :
396 : : // Use a macro instead of a function for conditional logging to prevent
397 : : // evaluating arguments when logging for the category is not enabled.
398 : :
399 : : // Log by prefixing the output with the passed category name and severity level. This logs conditionally if
400 : : // the category is allowed. No rate limiting is applied, because users specifying -debug are assumed to be
401 : : // developers or power users who are aware that -debug may cause excessive disk usage due to logging.
402 : : #define detail_LogIfCategoryAndLevelEnabled(category, level, ...) \
403 : : do { \
404 : : if (LogAcceptCategory((category), (level))) { \
405 : : bool rate_limit{level >= BCLog::Level::Info}; \
406 : : Assume(!rate_limit);/*Only called with the levels below*/ \
407 : : LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \
408 : : } \
409 : : } while (0)
410 : :
411 : : // Log conditionally, prefixing the output with the passed category name.
412 : : #define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Debug, __VA_ARGS__)
413 : : #define LogTrace(category, ...) detail_LogIfCategoryAndLevelEnabled(category, BCLog::Level::Trace, __VA_ARGS__)
414 : :
415 : : #endif // BITCOIN_LOGGING_H
|