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 <logging/categories.h> // IWYU pragma: export
11 : : #include <span.h>
12 : : #include <util/fs.h>
13 : : #include <util/log.h> // IWYU pragma: export
14 : : #include <util/stdmutex.h>
15 : : #include <util/string.h>
16 : : #include <util/time.h>
17 : :
18 : : #include <atomic>
19 : : #include <cstdint>
20 : : #include <cstring>
21 : : #include <functional>
22 : : #include <list>
23 : : #include <memory>
24 : : #include <optional>
25 : : #include <string>
26 : : #include <unordered_map>
27 : : #include <vector>
28 : :
29 : : static const bool DEFAULT_LOGTIMEMICROS = false;
30 : : static const bool DEFAULT_LOGIPS = false;
31 : : static const bool DEFAULT_LOGTIMESTAMPS = true;
32 : : static const bool DEFAULT_LOGTHREADNAMES = false;
33 : : static const bool DEFAULT_LOGSOURCELOCATIONS = false;
34 : : static constexpr bool DEFAULT_LOGLEVELALWAYS = false;
35 : : extern const char * const DEFAULT_DEBUGLOGFILE;
36 : :
37 : : extern bool fLogIPs;
38 : :
39 : : struct SourceLocationEqual {
40 : 87 : bool operator()(const SourceLocation& lhs, const SourceLocation& rhs) const noexcept
41 : : {
42 [ + - + - : 261 : return lhs.line() == rhs.line() && std::string_view(lhs.file_name()) == std::string_view(rhs.file_name());
+ + - + ]
43 : : }
44 : : };
45 : :
46 : : struct SourceLocationHasher {
47 : 206 : size_t operator()(const SourceLocation& s) const noexcept
48 : : {
49 : : // Use CSipHasher(0, 0) as a simple way to get uniform distribution.
50 [ + - ]: 206 : return size_t(CSipHasher(0, 0)
51 : 206 : .Write(s.line())
52 : 206 : .Write(MakeUCharSpan(std::string_view{s.file_name()}))
53 : 206 : .Finalize());
54 : : }
55 : : };
56 : :
57 : 554490 : struct LogCategory {
58 : : std::string category;
59 : : bool active;
60 : : };
61 : :
62 : : namespace BCLog {
63 : : constexpr auto DEFAULT_LOG_LEVEL{Level::Debug};
64 : : constexpr size_t DEFAULT_MAX_LOG_BUFFER{1'000'000}; // buffer up to 1MB of log data prior to StartLogging
65 : : constexpr uint64_t RATELIMIT_MAX_BYTES{1024 * 1024}; // maximum number of bytes per source location that can be logged within the RATELIMIT_WINDOW
66 : : constexpr auto RATELIMIT_WINDOW{1h}; // time window after which log ratelimit stats are reset
67 : : constexpr bool DEFAULT_LOGRATELIMIT{true};
68 : :
69 : : //! Fixed window rate limiter for logging.
70 : 2 : class LogRateLimiter
71 : : {
72 : : public:
73 : : //! Keeps track of an individual source location and how many available bytes are left for logging from it.
74 : : struct Stats {
75 : : //! Remaining bytes
76 : : uint64_t m_available_bytes;
77 : : //! Number of bytes that were consumed but didn't fit in the available bytes.
78 : : uint64_t m_dropped_bytes{0};
79 : :
80 : 52 : Stats(uint64_t max_bytes) : m_available_bytes{max_bytes} {}
81 : : //! Updates internal accounting and returns true if enough available_bytes were remaining
82 : : bool Consume(uint64_t bytes);
83 : : };
84 : :
85 : : private:
86 : : mutable StdMutex m_mutex;
87 : :
88 : : //! Stats for each source location that has attempted to log something.
89 : : std::unordered_map<SourceLocation, Stats, SourceLocationHasher, SourceLocationEqual> m_source_locations GUARDED_BY(m_mutex);
90 : : //! Whether any log locations are suppressed. Cached view on m_source_locations for performance reasons.
91 : : std::atomic<bool> m_suppression_active{false};
92 : : LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window);
93 : :
94 : : public:
95 : : using SchedulerFunction = std::function<void(std::function<void()>, std::chrono::milliseconds)>;
96 : : /**
97 : : * @param scheduler_func Callable object used to schedule resetting the window. The first
98 : : * parameter is the function to be executed, and the second is the
99 : : * reset_window interval.
100 : : * @param max_bytes Maximum number of bytes that can be logged for each source
101 : : * location.
102 : : * @param reset_window Time window after which the stats are reset.
103 : : */
104 : : static std::shared_ptr<LogRateLimiter> Create(
105 : : SchedulerFunction&& scheduler_func,
106 : : uint64_t max_bytes,
107 : : std::chrono::seconds reset_window);
108 : : //! Maximum number of bytes logged per location per window.
109 : : const uint64_t m_max_bytes;
110 : : //! Interval after which the window is reset.
111 : : const std::chrono::seconds m_reset_window;
112 : : //! Suppression status of a source log location.
113 : : enum class Status {
114 : : UNSUPPRESSED, // string fits within the limit
115 : : NEWLY_SUPPRESSED, // suppression has started since this string
116 : : STILL_SUPPRESSED, // suppression is still ongoing
117 : : };
118 : : //! Consumes `source_loc`'s available bytes corresponding to the size of the (formatted)
119 : : //! `str` and returns its status.
120 : : [[nodiscard]] Status Consume(
121 : : const SourceLocation& source_loc,
122 : : const std::string& str) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
123 : : //! Resets all usage to zero. Called periodically by the scheduler.
124 : : void Reset() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
125 : : //! Returns true if any log locations are currently being suppressed.
126 [ + + ][ + - : 176 : bool SuppressionsActive() const { return m_suppression_active; }
+ - + - +
- + - + -
+ - ]
127 : : };
128 : :
129 : : class Logger
130 : : {
131 : : public:
132 : 41139 : struct BufferedLog {
133 : : SystemClock::time_point now;
134 : : std::chrono::seconds mocktime;
135 : : std::string str, threadname;
136 : : SourceLocation source_loc;
137 : : LogFlags category;
138 : : Level level;
139 : : };
140 : :
141 : : private:
142 : : 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
143 : :
144 : : FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
145 : : std::list<BufferedLog> m_msgs_before_open GUARDED_BY(m_cs);
146 : : bool m_buffering GUARDED_BY(m_cs) = true; //!< Buffer messages before logging can be started.
147 : : size_t m_max_buffer_memusage GUARDED_BY(m_cs){DEFAULT_MAX_LOG_BUFFER};
148 : : size_t m_cur_buffer_memusage GUARDED_BY(m_cs){0};
149 : : size_t m_buffer_lines_discarded GUARDED_BY(m_cs){0};
150 : :
151 : : //! Manages the rate limiting of each log location.
152 : : std::shared_ptr<LogRateLimiter> m_limiter GUARDED_BY(m_cs);
153 : :
154 : : //! Category-specific log level. Overrides `m_log_level`.
155 : : std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs);
156 : :
157 : : //! If there is no category-specific log level, all logs with a severity
158 : : //! level lower than `m_log_level` will be ignored.
159 : : std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL};
160 : :
161 : : /** Log categories bitfield. */
162 : : std::atomic<CategoryMask> m_categories{BCLog::NONE};
163 : :
164 : : 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;
165 : :
166 : : std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const;
167 : :
168 : : /** Slots that connect to the print signal */
169 : : std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
170 : :
171 : : /** Send a string to the log output (internal) */
172 : : void LogPrintStr_(std::string_view str, SourceLocation&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
173 : : EXCLUSIVE_LOCKS_REQUIRED(m_cs);
174 : :
175 : : std::string GetLogPrefix(LogFlags category, Level level) const;
176 : :
177 : : public:
178 : : bool m_print_to_console = false;
179 : : bool m_print_to_file = false;
180 : :
181 : : bool m_log_timestamps = DEFAULT_LOGTIMESTAMPS;
182 : : bool m_log_time_micros = DEFAULT_LOGTIMEMICROS;
183 : : bool m_log_threadnames = DEFAULT_LOGTHREADNAMES;
184 : : bool m_log_sourcelocations = DEFAULT_LOGSOURCELOCATIONS;
185 : : bool m_always_print_category_level = DEFAULT_LOGLEVELALWAYS;
186 : :
187 : : fs::path m_file_path;
188 : : std::atomic<bool> m_reopen_file{false};
189 : :
190 : : /** Send a string to the log output */
191 : : void LogPrintStr(std::string_view str, SourceLocation&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
192 : : EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
193 : :
194 : : /** Returns whether logs will be written to any output */
195 : 5653390 : bool Enabled() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
196 : : {
197 : 5653390 : STDLOCK(m_cs);
198 [ + + + + : 5653610 : return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
+ + + + ]
199 : 5653390 : }
200 : :
201 : : /** Connect a slot to the print signal and return the connection */
202 : 72 : std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
203 : : {
204 : 72 : STDLOCK(m_cs);
205 [ + - ]: 72 : m_print_callbacks.push_back(std::move(fun));
206 : 72 : return --m_print_callbacks.end();
207 : 72 : }
208 : :
209 : : /** Delete a connection */
210 : 64 : void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
211 : : {
212 : 64 : STDLOCK(m_cs);
213 : 64 : m_print_callbacks.erase(it);
214 : 64 : }
215 : :
216 : 18 : size_t NumConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
217 : : {
218 : 18 : STDLOCK(m_cs);
219 : 18 : return m_print_callbacks.size();
220 : 18 : }
221 : :
222 : : /** Start logging (and flush all buffered messages) */
223 : : bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
224 : : /** Only for testing */
225 : : void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
226 : :
227 : 14 : void SetRateLimiting(std::shared_ptr<LogRateLimiter> limiter) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
228 : : {
229 : 14 : STDLOCK(m_cs);
230 : 14 : m_limiter = std::move(limiter);
231 : 14 : }
232 : :
233 : : /** Disable logging
234 : : * This offers a slight speedup and slightly smaller memory usage
235 : : * compared to leaving the logging system in its default state.
236 : : * Mostly intended for libbitcoin-kernel apps that don't want any logging.
237 : : * Should be used instead of StartLogging().
238 : : */
239 : : void DisableLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
240 : :
241 : : void ShrinkDebugFile();
242 : :
243 : 8 : std::unordered_map<LogFlags, Level> CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
244 : : {
245 : 8 : STDLOCK(m_cs);
246 [ + - ]: 8 : return m_category_log_levels;
247 : 8 : }
248 : 15 : void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
249 : : {
250 : 15 : STDLOCK(m_cs);
251 [ + - ]: 15 : m_category_log_levels = levels;
252 : 15 : }
253 : 2 : void AddCategoryLogLevel(LogFlags category, Level level) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
254 : : {
255 : 2 : STDLOCK(m_cs);
256 [ + - ]: 2 : m_category_log_levels[category] = level;
257 : 2 : }
258 : : bool SetCategoryLogLevel(std::string_view category_str, std::string_view level_str) EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
259 : :
260 [ + - + - : 5670156 : Level LogLevel() const { return m_log_level.load(); }
+ - + - ]
[ + - ]
261 [ + - ]: 22 : void SetLogLevel(Level level) { m_log_level = level; }
262 : : bool SetLogLevel(std::string_view level);
263 : :
264 [ + + ]: 26 : CategoryMask GetCategoryMask() const { return m_categories.load(); }
265 : :
266 : : void EnableCategory(LogFlags flag);
267 : : bool EnableCategory(std::string_view str);
268 : : void DisableCategory(LogFlags flag);
269 : : bool DisableCategory(std::string_view str);
270 : :
271 : : bool WillLogCategory(LogFlags category) const;
272 : : bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
273 : :
274 : : /** Returns a vector of the log categories in alphabetical order. */
275 : : std::vector<LogCategory> LogCategoriesList() const;
276 : : /** Returns a string with the log categories in alphabetical order. */
277 : 6151 : std::string LogCategoriesString() const
278 : : {
279 [ + - - + : 375211 : return util::Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
- + ]
280 : : };
281 : :
282 : : //! Returns a string with all user-selectable log levels.
283 : : std::string LogLevelsString() const;
284 : :
285 : : //! Returns the string representation of a log level.
286 : : static std::string LogLevelToStr(BCLog::Level level);
287 : :
288 : : bool DefaultShrinkDebugFile() const;
289 : : };
290 : :
291 : : } // namespace BCLog
292 : :
293 : : BCLog::Logger& LogInstance();
294 : :
295 : : /** Return true if log accepts specified category, at the specified level. */
296 : 76888 : static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
297 : : {
298 : 76888 : return LogInstance().WillLogCategoryLevel(category, level);
299 : : }
300 : :
301 : : /// Return log flag if str parses as a log category.
302 : : std::optional<BCLog::LogFlags> GetLogCategory(std::string_view str);
303 : :
304 : : #endif // BITCOIN_LOGGING_H
|