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