Bitcoin Core  31.0.0
P2P Digital Currency
logging.h
Go to the documentation of this file.
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 <threadsafety.h>
12 #include <util/fs.h>
13 #include <util/log.h> // IWYU pragma: export
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 <string>
24 #include <unordered_map>
25 #include <vector>
26 
27 static const bool DEFAULT_LOGTIMEMICROS = false;
28 static const bool DEFAULT_LOGIPS = false;
29 static const bool DEFAULT_LOGTIMESTAMPS = true;
30 static const bool DEFAULT_LOGTHREADNAMES = false;
31 static const bool DEFAULT_LOGSOURCELOCATIONS = false;
32 static constexpr bool DEFAULT_LOGLEVELALWAYS = false;
33 extern const char * const DEFAULT_DEBUGLOGFILE;
34 
35 extern bool fLogIPs;
36 
38  bool operator()(const SourceLocation& lhs, const SourceLocation& rhs) const noexcept
39  {
40  return lhs.line() == rhs.line() && std::string_view(lhs.file_name()) == std::string_view(rhs.file_name());
41  }
42 };
43 
45  size_t operator()(const SourceLocation& s) const noexcept
46  {
47  // Use CSipHasher(0, 0) as a simple way to get uniform distribution.
48  return size_t(CSipHasher(0, 0)
49  .Write(s.line())
50  .Write(MakeUCharSpan(std::string_view{s.file_name()}))
51  .Finalize());
52  }
53 };
54 
55 struct LogCategory {
56  std::string category;
57  bool active;
58 };
59 
60 namespace BCLog {
61  constexpr auto DEFAULT_LOG_LEVEL{Level::Debug};
62  constexpr size_t DEFAULT_MAX_LOG_BUFFER{1'000'000}; // buffer up to 1MB of log data prior to StartLogging
63  constexpr uint64_t RATELIMIT_MAX_BYTES{1024 * 1024}; // maximum number of bytes per source location that can be logged within the RATELIMIT_WINDOW
64  constexpr auto RATELIMIT_WINDOW{1h}; // time window after which log ratelimit stats are reset
65  constexpr bool DEFAULT_LOGRATELIMIT{true};
66 
69  {
70  public:
72  struct Stats {
76  uint64_t m_dropped_bytes{0};
77 
78  Stats(uint64_t max_bytes) : m_available_bytes{max_bytes} {}
80  bool Consume(uint64_t bytes);
81  };
82 
83  private:
84  mutable StdMutex m_mutex;
85 
87  std::unordered_map<SourceLocation, Stats, SourceLocationHasher, SourceLocationEqual> m_source_locations GUARDED_BY(m_mutex);
89  std::atomic<bool> m_suppression_active{false};
90  LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window);
91 
92  public:
93  using SchedulerFunction = std::function<void(std::function<void()>, std::chrono::milliseconds)>;
102  static std::shared_ptr<LogRateLimiter> Create(
103  SchedulerFunction&& scheduler_func,
104  uint64_t max_bytes,
105  std::chrono::seconds reset_window);
107  const uint64_t m_max_bytes;
109  const std::chrono::seconds m_reset_window;
111  enum class Status {
112  UNSUPPRESSED, // string fits within the limit
113  NEWLY_SUPPRESSED, // suppression has started since this string
114  STILL_SUPPRESSED, // suppression is still ongoing
115  };
118  [[nodiscard]] Status Consume(
119  const SourceLocation& source_loc,
120  const std::string& str) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
124  bool SuppressionsActive() const { return m_suppression_active; }
125  };
126 
127  class Logger
128  {
129  public:
130  struct BufferedLog {
131  SystemClock::time_point now;
132  std::chrono::seconds mocktime;
133  std::string str, threadname;
137  };
138 
139  private:
140  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
141 
142  FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
143  std::list<BufferedLog> m_msgs_before_open GUARDED_BY(m_cs);
144  bool m_buffering GUARDED_BY(m_cs) = true;
145  size_t m_max_buffer_memusage GUARDED_BY(m_cs){DEFAULT_MAX_LOG_BUFFER};
146  size_t m_cur_buffer_memusage GUARDED_BY(m_cs){0};
147  size_t m_buffer_lines_discarded GUARDED_BY(m_cs){0};
148 
150  std::shared_ptr<LogRateLimiter> m_limiter GUARDED_BY(m_cs);
151 
153  std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs);
154 
157  std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL};
158 
160  std::atomic<CategoryMask> m_categories{BCLog::NONE};
161 
162  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;
163 
164  std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const;
165 
167  std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
168 
170  void LogPrintStr_(std::string_view str, SourceLocation&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
172 
173  std::string GetLogPrefix(LogFlags category, Level level) const;
174 
175  public:
176  bool m_print_to_console = false;
177  bool m_print_to_file = false;
178 
184 
186  std::atomic<bool> m_reopen_file{false};
187 
189  void LogPrintStr(std::string_view str, SourceLocation&& source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit)
191 
194  {
195  StdLockGuard scoped_lock(m_cs);
196  return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
197  }
198 
200  std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
201  {
202  StdLockGuard scoped_lock(m_cs);
203  m_print_callbacks.push_back(std::move(fun));
204  return --m_print_callbacks.end();
205  }
206 
208  void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
209  {
210  StdLockGuard scoped_lock(m_cs);
211  m_print_callbacks.erase(it);
212  }
213 
214  size_t NumConnections()
215  {
216  StdLockGuard scoped_lock(m_cs);
217  return m_print_callbacks.size();
218  }
219 
224 
226  {
227  StdLockGuard scoped_lock(m_cs);
228  m_limiter = std::move(limiter);
229  }
230 
238 
239  void ShrinkDebugFile();
240 
242  {
243  StdLockGuard scoped_lock(m_cs);
244  return m_category_log_levels;
245  }
246  void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
247  {
248  StdLockGuard scoped_lock(m_cs);
249  m_category_log_levels = levels;
250  }
251  void AddCategoryLogLevel(LogFlags category, Level level)
252  {
253  StdLockGuard scoped_lock(m_cs);
254  m_category_log_levels[category] = level;
255  }
256  bool SetCategoryLogLevel(std::string_view category_str, std::string_view level_str) EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
257 
258  Level LogLevel() const { return m_log_level.load(); }
259  void SetLogLevel(Level level) { m_log_level = level; }
260  bool SetLogLevel(std::string_view level);
261 
262  CategoryMask GetCategoryMask() const { return m_categories.load(); }
263 
264  void EnableCategory(LogFlags flag);
265  bool EnableCategory(std::string_view str);
266  void DisableCategory(LogFlags flag);
267  bool DisableCategory(std::string_view str);
268 
269  bool WillLogCategory(LogFlags category) const;
270  bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
271 
273  std::vector<LogCategory> LogCategoriesList() const;
275  std::string LogCategoriesString() const
276  {
277  return util::Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
278  };
279 
281  std::string LogLevelsString() const;
282 
284  static std::string LogLevelToStr(BCLog::Level level);
285 
286  bool DefaultShrinkDebugFile() const;
287  };
288 
289 } // namespace BCLog
290 
292 
294 static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
295 {
296  return LogInstance().WillLogCategoryLevel(category, level);
297 }
298 
300 bool GetLogCategory(BCLog::LogFlags& flag, std::string_view str);
301 
302 #endif // BITCOIN_LOGGING_H
void EnableCategory(LogFlags flag)
Definition: logging.cpp:123
void DisableLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Disable logging This offers a slight speedup and slightly smaller memory usage compared to leaving th...
Definition: logging.cpp:111
StdMutex m_cs
Definition: logging.h:140
size_t m_buffer_lines_discarded GUARDED_BY(m_cs)
Definition: logging.h:147
constexpr auto MakeUCharSpan(const V &v) -> decltype(UCharSpanCast(std::span
Like the std::span constructor, but for (const) unsigned char member types only.
Definition: span.h:111
FILE *m_fileout GUARDED_BY(m_cs)
bool SuppressionsActive() const
Returns true if any log locations are currently being suppressed.
Definition: logging.h:124
Level
Definition: log.h:41
std::unordered_map< LogFlags, Level > CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:241
fs::path m_file_path
Definition: logging.h:185
Status
Suppression status of a source log location.
Definition: logging.h:111
std::string threadname
Definition: logging.h:133
Status Consume(const SourceLocation &source_loc, const std::string &str) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Consumes source_loc&#39;s available bytes corresponding to the size of the (formatted) str and returns it...
Definition: logging.cpp:391
Level LogLevel() const
Definition: logging.h:258
bool fLogIPs
Definition: logging.cpp:47
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:30
std::chrono::seconds mocktime
Definition: logging.h:132
size_t NumConnections()
Definition: logging.h:214
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:27
std::atomic< bool > m_reopen_file
Definition: logging.h:186
constexpr uint64_t RATELIMIT_MAX_BYTES
Definition: logging.h:63
bool m_print_to_console
Definition: logging.h:176
SystemClock::time_point now
Definition: logging.h:131
Definition: common.h:29
std::atomic< Level > m_log_level
If there is no category-specific log level, all logs with a severity level lower than m_log_level wil...
Definition: logging.h:157
const uint64_t m_max_bytes
Maximum number of bytes logged per location per window.
Definition: logging.h:107
BCLog::Logger & LogInstance()
Definition: logging.cpp:26
LogFlags
Definition: categories.h:14
bool operator()(const SourceLocation &lhs, const SourceLocation &rhs) const noexcept
Definition: logging.h:38
bool m_log_sourcelocations
Definition: logging.h:182
void AddCategoryLogLevel(LogFlags category, Level level)
Definition: logging.h:251
bool m_print_to_file
Definition: logging.h:177
constexpr auto DEFAULT_LOG_LEVEL
Definition: logging.h:61
Fixed window rate limiter for logging.
Definition: logging.h:68
size_t operator()(const SourceLocation &s) const noexcept
Definition: logging.h:45
bool Enabled() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Returns whether logs will be written to any output.
Definition: logging.h:193
static constexpr bool DEFAULT_LOGLEVELALWAYS
Definition: logging.h:32
void LogPrintStr(std::string_view str, SourceLocation &&source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Send a string to the log output.
Definition: logging.cpp:424
std::string category
Definition: logging.h:56
bool m_log_threadnames
Definition: logging.h:181
bool m_always_print_category_level
Definition: logging.h:183
std::function< void(std::function< void()>, std::chrono::milliseconds)> SchedulerFunction
Definition: logging.h:93
bool m_log_time_micros
Definition: logging.h:180
std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
Definition: logging.cpp:300
static std::shared_ptr< LogRateLimiter > Create(SchedulerFunction &&scheduler_func, uint64_t max_bytes, std::chrono::seconds reset_window)
Definition: logging.cpp:379
uint64_t m_available_bytes
Remaining bytes.
Definition: logging.h:74
constexpr size_t DEFAULT_MAX_LOG_BUFFER
Definition: logging.h:62
uint64_t m_dropped_bytes
Number of bytes that were consumed but didn&#39;t fit in the available bytes.
Definition: logging.h:76
constexpr bool DEFAULT_LOGRATELIMIT
Definition: logging.h:65
void DisableCategory(LogFlags flag)
Definition: logging.cpp:136
StdMutex m_mutex
Definition: logging.h:84
void SetCategoryLogLevel(const std::unordered_map< LogFlags, Level > &levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:246
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: siphash.cpp:73
void SetLogLevel(Level level)
Definition: logging.h:259
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:149
void DeleteCallback(std::list< std::function< void(const std::string &)>>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Delete a connection.
Definition: logging.h:208
std::string GetLogPrefix(LogFlags category, Level level) const
Definition: logging.cpp:343
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
Definition: logging.cpp:407
void LogPrintStr_(std::string_view str, SourceLocation &&source_loc, BCLog::LogFlags category, BCLog::Level level, bool should_ratelimit) EXCLUSIVE_LOCKS_REQUIRED(m_cs)
Send a string to the log output (internal)
Definition: logging.cpp:431
void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Only for testing.
Definition: logging.cpp:98
void Reset() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Resets all usage to zero. Called periodically by the scheduler.
Definition: logging.cpp:555
std::atomic< bool > m_suppression_active
Whether any log locations are suppressed. Cached view on m_source_locations for performance reasons...
Definition: logging.h:89
Keeps track of an individual source location and how many available bytes are left for logging from i...
Definition: logging.h:72
static std::string LogLevelToStr(BCLog::Level level)
Returns the string representation of a log level.
Definition: logging.cpp:234
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
std::list< std::function< void(const std::string &)> > m_print_callbacks GUARDED_BY(m_cs)
Slots that connect to the print signal.
Definition: logging.h:167
CategoryMask GetCategoryMask() const
Definition: logging.h:262
std::list< std::function< void(const std::string &)> >::iterator PushBackCallback(std::function< void(const std::string &)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Connect a slot to the print signal and return the connection.
Definition: logging.h:200
Stats(uint64_t max_bytes)
Definition: logging.h:78
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:31
uint64_t CategoryMask
Definition: categories.h:12
bool active
Definition: logging.h:57
std::atomic< CategoryMask > m_categories
Log categories bitfield.
Definition: logging.h:160
bool Consume(uint64_t bytes)
Updates internal accounting and returns true if enough available_bytes were remaining.
Definition: logging.cpp:573
General SipHash-2-4 implementation.
Definition: siphash.h:26
bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Start logging (and flush all buffered messages)
Definition: logging.cpp:54
std::string LogLevelsString() const
Returns a string with all user-selectable log levels.
Definition: logging.cpp:294
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:278
SourceLocation source_loc
Definition: logging.h:134
size_t m_cur_buffer_memusage GUARDED_BY(m_cs)
Definition: logging.h:146
static bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
Return true if log accepts specified category, at the specified level.
Definition: logging.h:294
bool m_log_timestamps
Definition: logging.h:179
static const bool DEFAULT_LOGIPS
Definition: logging.h:28
Like std::source_location, but allowing to override the function name.
Definition: log.h:18
size_t m_max_buffer_memusage GUARDED_BY(m_cs)
Definition: logging.h:145
bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.cpp:154
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:23
constexpr auto RATELIMIT_WINDOW
Definition: logging.h:64
LogRateLimiter(uint64_t max_bytes, std::chrono::seconds reset_window)
Definition: logging.cpp:376
std::unordered_map< SourceLocation, Stats, SourceLocationHasher, SourceLocationEqual > m_source_locations GUARDED_BY(m_mutex)
Stats for each source location that has attempted to log something.
const std::chrono::seconds m_reset_window
Interval after which the window is reset.
Definition: logging.h:109
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:205
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:29
bool GetLogCategory(BCLog::LogFlags &flag, std::string_view str)
Return true if str parses as a log category and set the flag.
Definition: logging.cpp:220
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:275
void ShrinkDebugFile()
Definition: logging.cpp:514
void SetRateLimiting(std::shared_ptr< LogRateLimiter > limiter) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:225
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:167