Bitcoin Core  0.20.99
P2P Digital Currency
logging.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 <fs.h>
10 #include <tinyformat.h>
11 #include <threadsafety.h>
12 #include <util/string.h>
13 
14 #include <atomic>
15 #include <cstdint>
16 #include <list>
17 #include <mutex>
18 #include <string>
19 #include <vector>
20 
21 static const bool DEFAULT_LOGTIMEMICROS = false;
22 static const bool DEFAULT_LOGIPS = false;
23 static const bool DEFAULT_LOGTIMESTAMPS = true;
24 static const bool DEFAULT_LOGTHREADNAMES = false;
25 extern const char * const DEFAULT_DEBUGLOGFILE;
26 
27 extern bool fLogIPs;
28 
29 struct LogCategory {
30  std::string category;
31  bool active;
32 };
33 
34 namespace BCLog {
35  enum LogFlags : uint32_t {
36  NONE = 0,
37  NET = (1 << 0),
38  TOR = (1 << 1),
39  MEMPOOL = (1 << 2),
40  HTTP = (1 << 3),
41  BENCH = (1 << 4),
42  ZMQ = (1 << 5),
43  WALLETDB = (1 << 6),
44  RPC = (1 << 7),
45  ESTIMATEFEE = (1 << 8),
46  ADDRMAN = (1 << 9),
47  SELECTCOINS = (1 << 10),
48  REINDEX = (1 << 11),
49  CMPCTBLOCK = (1 << 12),
50  RAND = (1 << 13),
51  PRUNE = (1 << 14),
52  PROXY = (1 << 15),
53  MEMPOOLREJ = (1 << 16),
54  LIBEVENT = (1 << 17),
55  COINDB = (1 << 18),
56  QT = (1 << 19),
57  LEVELDB = (1 << 20),
58  VALIDATION = (1 << 21),
59  ALL = ~(uint32_t)0,
60  };
61 
62  class Logger
63  {
64  private:
65  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
66 
67  FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
68  std::list<std::string> m_msgs_before_open GUARDED_BY(m_cs);
69  bool m_buffering GUARDED_BY(m_cs) = true;
70 
76  std::atomic_bool m_started_new_line{true};
77 
79  std::atomic<uint32_t> m_categories{0};
80 
81  std::string LogTimestampStr(const std::string& str);
82 
84  std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
85 
86  public:
87  bool m_print_to_console = false;
88  bool m_print_to_file = false;
89 
90  bool m_log_timestamps = DEFAULT_LOGTIMESTAMPS;
91  bool m_log_time_micros = DEFAULT_LOGTIMEMICROS;
92  bool m_log_threadnames = DEFAULT_LOGTHREADNAMES;
93 
94  fs::path m_file_path;
95  std::atomic<bool> m_reopen_file{false};
96 
98  void LogPrintStr(const std::string& str);
99 
101  bool Enabled() const
102  {
103  StdLockGuard scoped_lock(m_cs);
104  return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
105  }
106 
108  std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun)
109  {
110  StdLockGuard scoped_lock(m_cs);
111  m_print_callbacks.push_back(std::move(fun));
112  return --m_print_callbacks.end();
113  }
114 
116  void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it)
117  {
118  StdLockGuard scoped_lock(m_cs);
119  m_print_callbacks.erase(it);
120  }
121 
123  bool StartLogging();
125  void DisconnectTestLogger();
126 
127  void ShrinkDebugFile();
128 
129  uint32_t GetCategoryMask() const { return m_categories.load(); }
130 
131  void EnableCategory(LogFlags flag);
132  bool EnableCategory(const std::string& str);
133  void DisableCategory(LogFlags flag);
134  bool DisableCategory(const std::string& str);
135 
136  bool WillLogCategory(LogFlags category) const;
138  std::vector<LogCategory> LogCategoriesList();
140  std::string LogCategoriesString()
141  {
142  return Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
143  };
144 
145  bool DefaultShrinkDebugFile() const;
146  };
147 
148 } // namespace BCLog
149 
151 
154 {
155  return LogInstance().WillLogCategory(category);
156 }
157 
159 bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str);
160 
161 // Be conservative when using LogPrintf/error or other things which
162 // unconditionally log to debug.log! It should not be the case that an inbound
163 // peer can fill up a user's disk with debug.log entries.
164 
165 template <typename... Args>
166 static inline void LogPrintf(const char* fmt, const Args&... args)
167 {
168  if (LogInstance().Enabled()) {
169  std::string log_msg;
170  try {
171  log_msg = tfm::format(fmt, args...);
172  } catch (tinyformat::format_error& fmterr) {
173  /* Original format string will have newline so don't add one here */
174  log_msg = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + fmt;
175  }
176  LogInstance().LogPrintStr(log_msg);
177  }
178 }
179 
180 // Use a macro instead of a function for conditional logging to prevent
181 // evaluating arguments when logging for the category is not enabled.
182 #define LogPrint(category, ...) \
183  do { \
184  if (LogAcceptCategory((category))) { \
185  LogPrintf(__VA_ARGS__); \
186  } \
187  } while (0)
188 
189 #endif // BITCOIN_LOGGING_H
StdMutex m_cs
Definition: logging.h:65
std::deque< CInv >::iterator it
fs::path m_file_path
Definition: logging.h:94
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:36
Definition: timer.h:17
bool fLogIPs
Definition: logging.cpp:35
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:24
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:21
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
BCLog::Logger & LogInstance()
Definition: logging.cpp:14
std::list< std::function< void(const std::string &)> >::iterator PushBackCallback(std::function< void(const std::string &)> fun)
Connect a slot to the print signal and return the connection.
Definition: logging.h:108
void LogPrintStr(const std::string &str)
Send a string to the log output.
Definition: logging.cpp:239
std::string category
Definition: logging.h:30
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1062
uint32_t GetCategoryMask() const
Definition: logging.h:129
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:116
static bool LogAcceptCategory(BCLog::LogFlags category)
Return true if log accepts specified category.
Definition: logging.h:153
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:84
void DeleteCallback(std::list< std::function< void(const std::string &)>>::iterator it)
Delete a connection.
Definition: logging.h:116
std::string LogCategoriesString()
Returns a string with the log categories.
Definition: logging.h:140
bool active
Definition: logging.h:31
LogFlags
Definition: logging.h:35
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:162
#define GUARDED_BY(x)
Definition: threadsafety.h:38
static const bool DEFAULT_LOGIPS
Definition: logging.h:22
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:12
bool Enabled() const
Returns whether logs will be written to any output.
Definition: logging.h:101
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:23