Bitcoin ABC 0.32.12
P2P Digital Currency
common.cpp
Go to the documentation of this file.
1// Copyright (c) 2021 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#if defined(HAVE_CONFIG_H)
6#include <config/bitcoin-config.h>
7#endif
8
9#include <clientversion.h>
10#include <common/args.h>
11#include <logging.h>
12#include <node/miner.h>
13#include <node/ui_interface.h>
14#include <util/fs_helpers.h>
15#include <util/string.h>
16#include <util/time.h>
17#include <util/translation.h>
18
20
22
23namespace init {
25 argsman.AddArg(
26 "-debuglogfile=<file>",
27 strprintf("Specify location of debug log file. Relative paths will be "
28 "prefixed by a net-specific datadir location. "
29 "(-nodebuglogfile to disable; default: %s)",
32 argsman.AddArg("-debug=<category>",
33 "Output debug and trace logging (default: -nodebug, "
34 "supplying <category> is optional). "
35 "If <category> is not supplied or if <category> = 1, output "
36 "all debug and trace logging. <category> can be: " +
37 LogInstance().LogCategoriesString() +
38 ". This option can be specified multiple times to "
39 "output multiple categories.",
41 argsman.AddArg(
42 "-debugexclude=<category>",
44 "Exclude debug and trace logging for a category. Can be used in "
45 "conjunction with -debug=1 to output debug and trace logging for "
46 "all categories except the specified category. This option can be "
47 "specified multiple times to exclude multiple categories."),
49 argsman.AddArg(
50 "-logips",
51 strprintf("Include IP addresses in debug output (default: %u)",
54 argsman.AddArg(
55 "-loglevel=<level>|<category>:<level>",
57 "Set the global or per-category severity level for logging "
58 "categories enabled with the -debug configuration option or the "
59 "logging RPC. Possible values are %s (default=%s); The following "
60 "levels are always logged: error, warning, info. If "
61 "<category>:<level> is supplied, the setting will override the "
62 "global one and may be specified multiple times to set multiple "
63 "category-specific levels. <category> can be: %s.",
64 LogInstance().LogLevelsString(),
66 LogInstance().LogCategoriesString()),
70 argsman.AddArg(
71 "-logtimestamps",
72 strprintf("Prepend debug output with timestamp (default: %u)",
75#ifdef HAVE_THREAD_LOCAL
76 argsman.AddArg(
77 "-logthreadnames",
79 "Prepend debug output with name of the originating thread (only "
80 "available on platforms supporting thread_local) (default: %u)",
83#else
84 argsman.AddHiddenArgs({"-logthreadnames"});
85#endif
86 argsman.AddArg(
87 "-logsourcelocations",
89 "Prepend debug output with name of the originating source location "
90 "(source file, line number and function name) (default: %u)",
93 argsman.AddArg(
94 "-logtimemicros",
95 strprintf("Add microsecond precision to debug timestamps (default: %u)",
99 argsman.AddArg(
100 "-loglevelalways",
101 strprintf("Always prepend a category and level (default: %u)",
104 argsman.AddArg("-logratelimit",
105 strprintf("Apply rate limiting to unconditional logging to "
106 "mitigate disk-filling attacks (default: %u)",
110 argsman.AddArg("-printtoconsole",
111 "Send trace/debug info to console (default: 1 when no "
112 "-daemon. To disable logging to file, set -nodebuglogfile)",
114 argsman.AddArg("-printpriority",
115 strprintf("Log transaction priority and fee per kB when "
116 "mining blocks (default: %d)",
120 argsman.AddArg(
121 "-shrinkdebugfile",
122 "Shrink debug.log file on client startup (default: 1 when no -debug)",
124}
125
127 LogInstance().m_print_to_file = !args.IsArgNegated("-debuglogfile");
129 args, args.GetPathArg("-debuglogfile", DEFAULT_DEBUGLOGFILE));
130
132 args.GetBoolArg("-printtoconsole", !args.GetBoolArg("-daemon", false));
134 args.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
136 args.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
137#ifdef HAVE_THREAD_LOCAL
139 args.GetBoolArg("-logthreadnames", DEFAULT_LOGTHREADNAMES);
140#endif
142 args.GetBoolArg("-logsourcelocations", DEFAULT_LOGSOURCELOCATIONS);
144 args.GetBoolArg("-loglevelalways", DEFAULT_LOGLEVELALWAYS);
145
146 fLogIPs = args.GetBoolArg("-logips", DEFAULT_LOGIPS);
147}
148
149void SetLoggingLevel(const ArgsManager &args) {
150 if (!args.IsArgSet("-loglevel")) {
151 return;
152 }
153 for (const std::string &level_str : args.GetArgs("-loglevel")) {
154 if (level_str.find_first_of(':', 3) == std::string::npos) {
155 // user passed a global log level, i.e. -loglevel=<level>
156 if (!LogInstance().SetLogLevel(level_str)) {
157 InitWarning(strprintf(_("Unsupported global logging level "
158 "-loglevel=%s. Valid values: %s."),
159 level_str,
160 LogInstance().LogLevelsString()));
161 }
162 } else {
163 // user passed a category-specific log level, i.e.
164 // -loglevel=<category>:<level>
165 const auto &toks = SplitString(level_str, ':');
166 if (!(toks.size() == 2 &&
167 LogInstance().SetCategoryLogLevel(toks[0], toks[1]))) {
169 _("Unsupported category-specific logging level "
170 "-loglevel=%s. Expected -loglevel=<category>:<loglevel>. "
171 "Valid categories: %s. Valid loglevels: %s."),
172 level_str, LogInstance().LogCategoriesString(),
173 LogInstance().LogLevelsString()));
174 }
175 }
176 }
177}
178
180 if (args.IsArgSet("-debug")) {
181 // Special-case: if -debug=0/-nodebug is set, turn off debugging
182 // messages
183 const std::vector<std::string> categories = args.GetArgs("-debug");
184
185 if (std::none_of(
186 categories.begin(), categories.end(),
187 [](std::string cat) { return cat == "0" || cat == "none"; })) {
188 for (const auto &cat : categories) {
189 if (!LogInstance().EnableCategory(cat)) {
191 strprintf(_("Unsupported logging category %s=%s."),
192 "-debug", cat));
193 }
194 }
195 }
196 }
197
198 // Now remove the logging categories which were explicitly excluded
199 for (const std::string &cat : args.GetArgs("-debugexclude")) {
200 if (!LogInstance().DisableCategory(cat)) {
201 InitWarning(strprintf(_("Unsupported logging category %s=%s."),
202 "-debugexclude", cat));
203 }
204 }
205}
206
207bool StartLogging(const ArgsManager &args) {
208 BCLog::Logger &logger = LogInstance();
209 if (logger.m_print_to_file) {
210 if (args.GetBoolArg("-shrinkdebugfile",
211 logger.DefaultShrinkDebugFile())) {
212 // Do this first since it both loads a bunch of debug.log into
213 // memory, and because this needs to happen before any other
214 // debug.log printing.
215 logger.ShrinkDebugFile();
216 }
217 }
218
219 if (!logger.StartLogging()) {
220 return InitError(
221 strprintf(Untranslated("Could not open debug log file %s"),
223 }
224
225 if (!logger.m_log_timestamps) {
226 LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
227 }
228 LogPrintf("Default data directory %s\n",
230 LogPrintf("Using data directory %s\n",
232
233 // Only log conf file usage message if conf file actually exists.
234 fs::path config_file_path = args.GetConfigFilePath();
235 if (fs::exists(config_file_path)) {
236 LogPrintf("Config file: %s\n", fs::PathToString(config_file_path));
237 } else if (args.IsArgSet("-conf")) {
238 // Warn if no conf file exists at path provided by user
240 strprintf(_("The specified config file %s does not exist\n"),
241 fs::PathToString(config_file_path)));
242 } else {
243 // Not categorizing as "Warning" because it's the default behavior
244 LogPrintf("Config file: %s (not found, skipping)\n",
245 fs::PathToString(config_file_path));
246 }
247
248 // Log the config arguments to debug.log
249 args.LogArgs();
250
251 return true;
252}
253
255 std::string version_string = FormatFullVersion();
256#ifdef DEBUG
257 version_string += " (debug build)";
258#else
259 version_string += " (release build)";
260#endif
261 LogPrintf("%s version %s\n", CLIENT_NAME, version_string);
262}
263} // namespace init
fs::path GetDefaultDataDir()
Definition: args.cpp:727
ArgsManager gArgs
Definition: args.cpp:39
fs::path AbsPathForConfigVal(const ArgsManager &args, const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: configfile.cpp:239
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: args.cpp:458
@ ALLOW_ANY
disable validation
Definition: args.h:114
@ DISALLOW_NEGATION
unimplemented, draft implementation in #16545
Definition: args.h:124
@ DISALLOW_ELISION
disallow -foo syntax that doesn't assign any value
Definition: args.h:126
@ DEBUG_ONLY
Definition: args.h:128
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: args.cpp:361
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:239
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:371
fs::path GetConfigFilePath() const
Return config file path (read-only)
Definition: args.cpp:757
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: args.cpp:852
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:524
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: args.cpp:610
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:588
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition: args.cpp:285
bool m_always_print_category_level
Definition: logging.h:263
bool DefaultShrinkDebugFile() const
Default for whether ShrinkDebugFile should be run.
Definition: logging.cpp:633
bool m_log_sourcelocations
Definition: logging.h:262
fs::path m_file_path
Definition: logging.h:265
bool m_log_time_micros
Definition: logging.h:260
bool m_log_threadnames
Definition: logging.h:261
bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Start logging (and flush all buffered messages)
Definition: logging.cpp:52
bool m_log_timestamps
Definition: logging.h:259
void ShrinkDebugFile()
Definition: logging.cpp:538
bool m_print_to_file
Definition: logging.h:257
bool m_print_to_console
Definition: logging.h:256
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
std::string FormatFullVersion()
const std::string CLIENT_NAME
BCLog::Logger & LogInstance()
Definition: logging.cpp:28
bool fLogIPs
Definition: logging.cpp:24
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:25
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:33
static const bool DEFAULT_LOGIPS
Definition: logging.h:32
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:34
static const bool DEFAULT_LOGSOURCELOCATIONS
Definition: logging.h:35
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:31
static constexpr bool DEFAULT_LOGLEVELALWAYS
Definition: logging.h:36
#define LogPrintf(...)
Definition: logging.h:424
constexpr bool DEFAULT_LOGRATELIMIT
Definition: logging.h:121
constexpr auto DEFAULT_LOG_LEVEL
Definition: logging.h:113
static bool exists(const path &p)
Definition: fs.h:107
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:147
Definition: common.cpp:23
void AddLoggingArgs(ArgsManager &argsman)
Definition: common.cpp:24
void SetLoggingCategories(const ArgsManager &args)
Definition: common.cpp:179
bool StartLogging(const ArgsManager &args)
Definition: common.cpp:207
void SetLoggingLevel(const ArgsManager &args)
Definition: common.cpp:149
void SetLoggingOptions(const ArgsManager &args)
Definition: common.cpp:126
void LogPackageVersion()
Definition: common.cpp:254
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:37
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:59
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:62
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:78
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.