Bitcoin ABC 0.32.4
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
21namespace init {
23 argsman.AddArg(
24 "-debuglogfile=<file>",
25 strprintf("Specify location of debug log file. Relative paths will be "
26 "prefixed by a net-specific datadir location. "
27 "(-nodebuglogfile to disable; default: %s)",
30 argsman.AddArg("-debug=<category>",
31 "Output debug and trace logging (default: -nodebug, "
32 "supplying <category> is optional). "
33 "If <category> is not supplied or if <category> = 1, output "
34 "all debug and trace logging. <category> can be: " +
35 LogInstance().LogCategoriesString() +
36 ". This option can be specified multiple times to "
37 "output multiple categories.",
39 argsman.AddArg(
40 "-debugexclude=<category>",
42 "Exclude debug and trace logging for a category. Can be used in "
43 "conjunction with -debug=1 to output debug and trace logging for "
44 "all categories except the specified category. This option can be "
45 "specified multiple times to exclude multiple categories."),
47 argsman.AddArg(
48 "-logips",
49 strprintf("Include IP addresses in debug output (default: %u)",
52 argsman.AddArg(
53 "-loglevel=<level>|<category>:<level>",
55 "Set the global or per-category severity level for logging "
56 "categories enabled with the -debug configuration option or the "
57 "logging RPC. Possible values are %s (default=%s); The following "
58 "levels are always logged: error, warning, info. If "
59 "<category>:<level> is supplied, the setting will override the "
60 "global one and may be specified multiple times to set multiple "
61 "category-specific levels. <category> can be: %s.",
62 LogInstance().LogLevelsString(),
64 LogInstance().LogCategoriesString()),
68 argsman.AddArg(
69 "-logtimestamps",
70 strprintf("Prepend debug output with timestamp (default: %u)",
73#ifdef HAVE_THREAD_LOCAL
74 argsman.AddArg(
75 "-logthreadnames",
77 "Prepend debug output with name of the originating thread (only "
78 "available on platforms supporting thread_local) (default: %u)",
81#else
82 argsman.AddHiddenArgs({"-logthreadnames"});
83#endif
84 argsman.AddArg(
85 "-logsourcelocations",
87 "Prepend debug output with name of the originating source location "
88 "(source file, line number and function name) (default: %u)",
91 argsman.AddArg(
92 "-logtimemicros",
93 strprintf("Add microsecond precision to debug timestamps (default: %u)",
97 argsman.AddArg(
98 "-loglevelalways",
99 strprintf("Always prepend a category and level (default: %u)",
102 argsman.AddArg("-logratelimit",
103 strprintf("Apply rate limiting to unconditional logging to "
104 "mitigate disk-filling attacks (default: %u)",
108 argsman.AddArg("-printtoconsole",
109 "Send trace/debug info to console (default: 1 when no "
110 "-daemon. To disable logging to file, set -nodebuglogfile)",
112 argsman.AddArg("-printpriority",
113 strprintf("Log transaction priority and fee per kB when "
114 "mining blocks (default: %d)",
118 argsman.AddArg(
119 "-shrinkdebugfile",
120 "Shrink debug.log file on client startup (default: 1 when no -debug)",
122}
123
125 LogInstance().m_print_to_file = !args.IsArgNegated("-debuglogfile");
127 args, args.GetPathArg("-debuglogfile", DEFAULT_DEBUGLOGFILE));
128
130 args.GetBoolArg("-printtoconsole", !args.GetBoolArg("-daemon", false));
132 args.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
134 args.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
135#ifdef HAVE_THREAD_LOCAL
137 args.GetBoolArg("-logthreadnames", DEFAULT_LOGTHREADNAMES);
138#endif
140 args.GetBoolArg("-logsourcelocations", DEFAULT_LOGSOURCELOCATIONS);
142 args.GetBoolArg("-loglevelalways", DEFAULT_LOGLEVELALWAYS);
143
144 fLogIPs = args.GetBoolArg("-logips", DEFAULT_LOGIPS);
145}
146
147void SetLoggingLevel(const ArgsManager &args) {
148 if (!args.IsArgSet("-loglevel")) {
149 return;
150 }
151 for (const std::string &level_str : args.GetArgs("-loglevel")) {
152 if (level_str.find_first_of(':', 3) == std::string::npos) {
153 // user passed a global log level, i.e. -loglevel=<level>
154 if (!LogInstance().SetLogLevel(level_str)) {
155 InitWarning(strprintf(_("Unsupported global logging level "
156 "-loglevel=%s. Valid values: %s."),
157 level_str,
158 LogInstance().LogLevelsString()));
159 }
160 } else {
161 // user passed a category-specific log level, i.e.
162 // -loglevel=<category>:<level>
163 const auto &toks = SplitString(level_str, ':');
164 if (!(toks.size() == 2 &&
165 LogInstance().SetCategoryLogLevel(toks[0], toks[1]))) {
167 _("Unsupported category-specific logging level "
168 "-loglevel=%s. Expected -loglevel=<category>:<loglevel>. "
169 "Valid categories: %s. Valid loglevels: %s."),
170 level_str, LogInstance().LogCategoriesString(),
171 LogInstance().LogLevelsString()));
172 }
173 }
174 }
175}
176
178 if (args.IsArgSet("-debug")) {
179 // Special-case: if -debug=0/-nodebug is set, turn off debugging
180 // messages
181 const std::vector<std::string> categories = args.GetArgs("-debug");
182
183 if (std::none_of(
184 categories.begin(), categories.end(),
185 [](std::string cat) { return cat == "0" || cat == "none"; })) {
186 for (const auto &cat : categories) {
187 if (!LogInstance().EnableCategory(cat)) {
189 strprintf(_("Unsupported logging category %s=%s."),
190 "-debug", cat));
191 }
192 }
193 }
194 }
195
196 // Now remove the logging categories which were explicitly excluded
197 for (const std::string &cat : args.GetArgs("-debugexclude")) {
198 if (!LogInstance().DisableCategory(cat)) {
199 InitWarning(strprintf(_("Unsupported logging category %s=%s."),
200 "-debugexclude", cat));
201 }
202 }
203}
204
205bool StartLogging(const ArgsManager &args) {
206 BCLog::Logger &logger = LogInstance();
207 if (logger.m_print_to_file) {
208 if (args.GetBoolArg("-shrinkdebugfile",
209 logger.DefaultShrinkDebugFile())) {
210 // Do this first since it both loads a bunch of debug.log into
211 // memory, and because this needs to happen before any other
212 // debug.log printing.
213 logger.ShrinkDebugFile();
214 }
215 }
216
217 if (!logger.StartLogging()) {
218 return InitError(
219 strprintf(Untranslated("Could not open debug log file %s"),
221 }
222
223 if (!logger.m_log_timestamps) {
224 LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
225 }
226 LogPrintf("Default data directory %s\n",
228 LogPrintf("Using data directory %s\n",
230
231 // Only log conf file usage message if conf file actually exists.
232 fs::path config_file_path = args.GetConfigFilePath();
233 if (fs::exists(config_file_path)) {
234 LogPrintf("Config file: %s\n", fs::PathToString(config_file_path));
235 } else if (args.IsArgSet("-conf")) {
236 // Warn if no conf file exists at path provided by user
238 strprintf(_("The specified config file %s does not exist\n"),
239 fs::PathToString(config_file_path)));
240 } else {
241 // Not categorizing as "Warning" because it's the default behavior
242 LogPrintf("Config file: %s (not found, skipping)\n",
243 fs::PathToString(config_file_path));
244 }
245
246 // Log the config arguments to debug.log
247 args.LogArgs();
248
249 return true;
250}
251
253 std::string version_string = FormatFullVersion();
254#ifdef DEBUG
255 version_string += " (debug build)";
256#else
257 version_string += " (release build)";
258#endif
259 LogPrintf("%s version %s\n", CLIENT_NAME, version_string);
260}
261} // namespace init
fs::path GetDefaultDataDir()
Definition: args.cpp:728
ArgsManager gArgs
Definition: args.cpp:40
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:236
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: args.cpp:459
@ 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:362
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:372
fs::path GetConfigFilePath() const
Return config file path (read-only)
Definition: args.cpp:758
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: args.cpp:853
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:525
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: args.cpp:611
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:589
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition: args.cpp:286
bool m_always_print_category_level
Definition: logging.h:263
bool DefaultShrinkDebugFile() const
Default for whether ShrinkDebugFile should be run.
Definition: logging.cpp:630
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:49
bool m_log_timestamps
Definition: logging.h:259
void ShrinkDebugFile()
Definition: logging.cpp:535
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:25
bool fLogIPs
Definition: logging.cpp:21
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:22
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:21
void AddLoggingArgs(ArgsManager &argsman)
Definition: common.cpp:22
void SetLoggingCategories(const ArgsManager &args)
Definition: common.cpp:177
bool StartLogging(const ArgsManager &args)
Definition: common.cpp:205
void SetLoggingLevel(const ArgsManager &args)
Definition: common.cpp:147
void SetLoggingOptions(const ArgsManager &args)
Definition: common.cpp:124
void LogPackageVersion()
Definition: common.cpp:252
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:37
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:22
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:105
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:109
#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.