Bitcoin Core 22.99.0
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
21static const bool DEFAULT_LOGTIMEMICROS = false;
22static const bool DEFAULT_LOGIPS = false;
23static const bool DEFAULT_LOGTIMESTAMPS = true;
24static const bool DEFAULT_LOGTHREADNAMES = false;
25static const bool DEFAULT_LOGSOURCELOCATIONS = false;
26extern const char * const DEFAULT_DEBUGLOGFILE;
27
28extern bool fLogIPs;
29
31 std::string category;
32 bool active;
33};
34
35namespace BCLog {
36 enum LogFlags : uint32_t {
37 NONE = 0,
38 NET = (1 << 0),
39 TOR = (1 << 1),
40 MEMPOOL = (1 << 2),
41 HTTP = (1 << 3),
42 BENCH = (1 << 4),
43 ZMQ = (1 << 5),
44 WALLETDB = (1 << 6),
45 RPC = (1 << 7),
46 ESTIMATEFEE = (1 << 8),
47 ADDRMAN = (1 << 9),
48 SELECTCOINS = (1 << 10),
49 REINDEX = (1 << 11),
50 CMPCTBLOCK = (1 << 12),
51 RAND = (1 << 13),
52 PRUNE = (1 << 14),
53 PROXY = (1 << 15),
54 MEMPOOLREJ = (1 << 16),
55 LIBEVENT = (1 << 17),
56 COINDB = (1 << 18),
57 QT = (1 << 19),
58 LEVELDB = (1 << 20),
59 VALIDATION = (1 << 21),
60 I2P = (1 << 22),
61 IPC = (1 << 23),
62 LOCK = (1 << 24),
63 UTIL = (1 << 25),
64 BLOCKSTORE = (1 << 26),
65 ALL = ~(uint32_t)0,
66 };
67
68 class Logger
69 {
70 private:
71 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
72
73 FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
74 std::list<std::string> m_msgs_before_open GUARDED_BY(m_cs);
75 bool m_buffering GUARDED_BY(m_cs) = true;
76
82 std::atomic_bool m_started_new_line{true};
83
85 std::atomic<uint32_t> m_categories{0};
86
87 std::string LogTimestampStr(const std::string& str);
88
90 std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
91
92 public:
93 bool m_print_to_console = false;
94 bool m_print_to_file = false;
95
100
102 std::atomic<bool> m_reopen_file{false};
103
105 void LogPrintStr(const std::string& str, const std::string& logging_function, const std::string& source_file, const int source_line);
106
108 bool Enabled() const
109 {
110 StdLockGuard scoped_lock(m_cs);
111 return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
112 }
113
115 std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun)
116 {
117 StdLockGuard scoped_lock(m_cs);
118 m_print_callbacks.push_back(std::move(fun));
119 return --m_print_callbacks.end();
120 }
121
123 void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it)
124 {
125 StdLockGuard scoped_lock(m_cs);
126 m_print_callbacks.erase(it);
127 }
128
130 bool StartLogging();
133
134 void ShrinkDebugFile();
135
136 uint32_t GetCategoryMask() const { return m_categories.load(); }
137
138 void EnableCategory(LogFlags flag);
139 bool EnableCategory(const std::string& str);
140 void DisableCategory(LogFlags flag);
141 bool DisableCategory(const std::string& str);
142
143 bool WillLogCategory(LogFlags category) const;
145 std::vector<LogCategory> LogCategoriesList() const;
147 std::string LogCategoriesString() const
148 {
149 return Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
150 };
151
152 bool DefaultShrinkDebugFile() const;
153 };
154
155} // namespace BCLog
156
158
160static inline bool LogAcceptCategory(BCLog::LogFlags category)
161{
162 return LogInstance().WillLogCategory(category);
163}
164
166bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str);
167
168// Be conservative when using LogPrintf/error or other things which
169// unconditionally log to debug.log! It should not be the case that an inbound
170// peer can fill up a user's disk with debug.log entries.
171
172template <typename... Args>
173static inline void LogPrintf_(const std::string& logging_function, const std::string& source_file, const int source_line, const char* fmt, const Args&... args)
174{
175 if (LogInstance().Enabled()) {
176 std::string log_msg;
177 try {
178 log_msg = tfm::format(fmt, args...);
179 } catch (tinyformat::format_error& fmterr) {
180 /* Original format string will have newline so don't add one here */
181 log_msg = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + fmt;
182 }
183 LogInstance().LogPrintStr(log_msg, logging_function, source_file, source_line);
184 }
185}
186
187#define LogPrintf(...) LogPrintf_(__func__, __FILE__, __LINE__, __VA_ARGS__)
188
189// Use a macro instead of a function for conditional logging to prevent
190// evaluating arguments when logging for the category is not enabled.
191#define LogPrint(category, ...) \
192 do { \
193 if (LogAcceptCategory((category))) { \
194 LogPrintf(__VA_ARGS__); \
195 } \
196 } while (0)
197
198#endif // BITCOIN_LOGGING_H
FILE *m_fileout GUARDED_BY(m_cs)
bool m_buffering GUARDED_BY(m_cs)
Buffer messages before logging can be started.
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:119
bool Enabled() const
Returns whether logs will be written to any output.
Definition: logging.h:108
std::string LogTimestampStr(const std::string &str)
Definition: logging.cpp:202
void DisconnectTestLogger()
Only for testing.
Definition: logging.cpp:84
std::list< std::function< void(conststd::string &)> >::iterator PushBackCallback(std::function< void(const std::string &)> fun)
Connect a slot to the print signal and return the connection.
Definition: logging.h:115
std::list< std::string > m_msgs_before_open GUARDED_BY(m_cs)
std::atomic< uint32_t > m_categories
Log categories bitfield.
Definition: logging.h:85
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:124
bool m_log_sourcelocations
Definition: logging.h:99
fs::path m_file_path
Definition: logging.h:101
bool m_log_time_micros
Definition: logging.h:97
bool m_log_threadnames
Definition: logging.h:98
std::atomic_bool m_started_new_line
m_started_new_line is a state variable that will suppress printing of the timestamp when multiple cal...
Definition: logging.h:82
std::vector< LogCategory > LogCategoriesList() const
Returns a vector of the log categories in alphabetical order.
Definition: logging.cpp:184
void EnableCategory(LogFlags flag)
Definition: logging.cpp:93
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:45
bool m_log_timestamps
Definition: logging.h:96
std::atomic< bool > m_reopen_file
Definition: logging.h:102
void ShrinkDebugFile()
Definition: logging.cpp:297
bool m_print_to_file
Definition: logging.h:94
uint32_t GetCategoryMask() const
Definition: logging.h:136
bool m_print_to_console
Definition: logging.h:93
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:90
StdMutex m_cs
Definition: logging.h:71
void LogPrintStr(const std::string &str, const std::string &logging_function, const std::string &source_file, const int source_line)
Send a string to the log output.
Definition: logging.cpp:249
std::string LogCategoriesString() const
Returns a string with the log categories in alphabetical order.
Definition: logging.h:147
void DeleteCallback(std::list< std::function< void(const std::string &)> >::iterator it)
Delete a connection.
Definition: logging.h:123
void DisableCategory(LogFlags flag)
Definition: logging.cpp:106
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:34
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:23
static void LogPrintf_(const std::string &logging_function, const std::string &source_file, const int source_line, const char *fmt, const Args &... args)
Definition: logging.h:173
static bool LogAcceptCategory(BCLog::LogFlags category)
Return true if log accepts specified category.
Definition: logging.h:160
static const bool DEFAULT_LOGIPS
Definition: logging.h:22
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:24
BCLog::Logger & LogInstance()
Definition: logging.cpp:17
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:169
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:25
bool fLogIPs
Definition: logging.cpp:38
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:21
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:15
LogFlags
Definition: logging.h:36
@ ESTIMATEFEE
Definition: logging.h:46
@ RAND
Definition: logging.h:51
@ COINDB
Definition: logging.h:56
@ REINDEX
Definition: logging.h:49
@ WALLETDB
Definition: logging.h:44
@ ADDRMAN
Definition: logging.h:47
@ ALL
Definition: logging.h:65
@ RPC
Definition: logging.h:45
@ HTTP
Definition: logging.h:41
@ LEVELDB
Definition: logging.h:58
@ NONE
Definition: logging.h:37
@ VALIDATION
Definition: logging.h:59
@ MEMPOOLREJ
Definition: logging.h:54
@ PRUNE
Definition: logging.h:52
@ TOR
Definition: logging.h:39
@ LIBEVENT
Definition: logging.h:55
@ LOCK
Definition: logging.h:62
@ CMPCTBLOCK
Definition: logging.h:50
@ PROXY
Definition: logging.h:53
@ ZMQ
Definition: logging.h:43
@ IPC
Definition: logging.h:61
@ MEMPOOL
Definition: logging.h:40
@ SELECTCOINS
Definition: logging.h:48
@ I2P
Definition: logging.h:60
@ BENCH
Definition: logging.h:42
@ NET
Definition: logging.h:38
@ UTIL
Definition: logging.h:63
@ QT
Definition: logging.h:57
@ BLOCKSTORE
Definition: logging.h:64
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
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:44
bool active
Definition: logging.h:32
std::string category
Definition: logging.h:31