|
| 1 | +// Copyright (c) 2023 Bitcoin 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 | +// Warn about any use of LogPrintf that does not end with a newline. |
| 6 | +#include <string> |
| 7 | + |
| 8 | +enum LogFlags { |
| 9 | + NONE |
| 10 | +}; |
| 11 | + |
| 12 | +enum Level { |
| 13 | + None |
| 14 | +}; |
| 15 | + |
| 16 | +template <typename... Args> |
| 17 | +static inline void LogPrintf_(const std::string& logging_function, const std::string& source_file, const int source_line, const LogFlags flag, const Level level, const char* fmt, const Args&... args) |
| 18 | +{ |
| 19 | +} |
| 20 | + |
| 21 | +#define LogPrintLevel_(category, level, ...) LogPrintf_(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__) |
| 22 | +#define LogPrintf(...) LogPrintLevel_(LogFlags::NONE, Level::None, __VA_ARGS__) |
| 23 | + |
| 24 | +// Use a macro instead of a function for conditional logging to prevent |
| 25 | +// evaluating arguments when logging for the category is not enabled. |
| 26 | +#define LogPrint(category, ...) \ |
| 27 | + do { \ |
| 28 | + LogPrintf(__VA_ARGS__); \ |
| 29 | + } while (0) |
| 30 | + |
| 31 | + |
| 32 | +class CWallet |
| 33 | +{ |
| 34 | + std::string GetDisplayName() const |
| 35 | + { |
| 36 | + return "default wallet"; |
| 37 | + } |
| 38 | + |
| 39 | +public: |
| 40 | + template <typename... Params> |
| 41 | + void WalletLogPrintf(std::string fmt, Params... parameters) const |
| 42 | + { |
| 43 | + LogPrintf(("%s " + fmt).c_str(), GetDisplayName(), parameters...); |
| 44 | + }; |
| 45 | +}; |
| 46 | + |
| 47 | +void good_func() |
| 48 | +{ |
| 49 | + LogPrintf("hello world!\n"); |
| 50 | +} |
| 51 | +void good_func2() |
| 52 | +{ |
| 53 | + CWallet wallet; |
| 54 | + wallet.WalletLogPrintf("hi\n"); |
| 55 | + |
| 56 | + const CWallet& walletref = wallet; |
| 57 | + walletref.WalletLogPrintf("hi\n"); |
| 58 | + |
| 59 | + auto* walletptr = new CWallet(); |
| 60 | + walletptr->WalletLogPrintf("hi\n"); |
| 61 | + delete walletptr; |
| 62 | +} |
| 63 | +void bad_func() |
| 64 | +{ |
| 65 | + LogPrintf("hello world!"); |
| 66 | +} |
| 67 | +void bad_func2() |
| 68 | +{ |
| 69 | + LogPrintf(""); |
| 70 | +} |
| 71 | +void bad_func3() |
| 72 | +{ |
| 73 | + // Ending in "..." has no special meaning. |
| 74 | + LogPrintf("hello world!..."); |
| 75 | +} |
| 76 | +void bad_func4_ignored() |
| 77 | +{ |
| 78 | + LogPrintf("hello world!"); // NOLINT(bitcoin-unterminated-logprintf) |
| 79 | +} |
| 80 | +void bad_func5() |
| 81 | +{ |
| 82 | + CWallet wallet; |
| 83 | + wallet.WalletLogPrintf("hi"); |
| 84 | + |
| 85 | + const CWallet& walletref = wallet; |
| 86 | + walletref.WalletLogPrintf("hi"); |
| 87 | + |
| 88 | + auto* walletptr = new CWallet(); |
| 89 | + walletptr->WalletLogPrintf("hi"); |
| 90 | + delete walletptr; |
| 91 | +} |
0 commit comments