LCOV - code coverage report
Current view: top level - src - logging.h (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 92.1 % 38 35
Test Date: 2024-08-28 04:44:32 Functions: 47.2 % 233 110
Branches: 35.2 % 54 19

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-2022 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 <threadsafety.h>
      10                 :             : #include <tinyformat.h>
      11                 :             : #include <util/fs.h>
      12                 :             : #include <util/string.h>
      13                 :             : #include <util/time.h>
      14                 :             : 
      15                 :             : #include <atomic>
      16                 :             : #include <cstdint>
      17                 :             : #include <functional>
      18                 :             : #include <list>
      19                 :             : #include <mutex>
      20                 :             : #include <string>
      21                 :             : #include <unordered_map>
      22                 :             : #include <vector>
      23                 :             : 
      24                 :             : static const bool DEFAULT_LOGTIMEMICROS = false;
      25                 :             : static const bool DEFAULT_LOGIPS        = false;
      26                 :             : static const bool DEFAULT_LOGTIMESTAMPS = true;
      27                 :             : static const bool DEFAULT_LOGTHREADNAMES = false;
      28                 :             : static const bool DEFAULT_LOGSOURCELOCATIONS = false;
      29                 :             : static constexpr bool DEFAULT_LOGLEVELALWAYS = false;
      30                 :             : extern const char * const DEFAULT_DEBUGLOGFILE;
      31                 :             : 
      32                 :             : extern bool fLogIPs;
      33                 :             : 
      34                 :      104580 : struct LogCategory {
      35                 :             :     std::string category;
      36                 :             :     bool active;
      37                 :             : };
      38                 :             : 
      39                 :             : namespace BCLog {
      40                 :             :     enum LogFlags : uint32_t {
      41                 :             :         NONE        = 0,
      42                 :             :         NET         = (1 <<  0),
      43                 :             :         TOR         = (1 <<  1),
      44                 :             :         MEMPOOL     = (1 <<  2),
      45                 :             :         HTTP        = (1 <<  3),
      46                 :             :         BENCH       = (1 <<  4),
      47                 :             :         ZMQ         = (1 <<  5),
      48                 :             :         WALLETDB    = (1 <<  6),
      49                 :             :         RPC         = (1 <<  7),
      50                 :             :         ESTIMATEFEE = (1 <<  8),
      51                 :             :         ADDRMAN     = (1 <<  9),
      52                 :             :         SELECTCOINS = (1 << 10),
      53                 :             :         REINDEX     = (1 << 11),
      54                 :             :         CMPCTBLOCK  = (1 << 12),
      55                 :             :         RAND        = (1 << 13),
      56                 :             :         PRUNE       = (1 << 14),
      57                 :             :         PROXY       = (1 << 15),
      58                 :             :         MEMPOOLREJ  = (1 << 16),
      59                 :             :         LIBEVENT    = (1 << 17),
      60                 :             :         COINDB      = (1 << 18),
      61                 :             :         QT          = (1 << 19),
      62                 :             :         LEVELDB     = (1 << 20),
      63                 :             :         VALIDATION  = (1 << 21),
      64                 :             :         I2P         = (1 << 22),
      65                 :             :         IPC         = (1 << 23),
      66                 :             : #ifdef DEBUG_LOCKCONTENTION
      67                 :             :         LOCK        = (1 << 24),
      68                 :             : #endif
      69                 :             :         BLOCKSTORAGE = (1 << 25),
      70                 :             :         TXRECONCILIATION = (1 << 26),
      71                 :             :         SCAN        = (1 << 27),
      72                 :             :         TXPACKAGES  = (1 << 28),
      73                 :             :         ALL         = ~(uint32_t)0,
      74                 :             :     };
      75                 :             :     enum class Level {
      76                 :             :         Trace = 0, // High-volume or detailed logging for development/debugging
      77                 :             :         Debug,     // Reasonably noisy logging, but still usable in production
      78                 :             :         Info,      // Default
      79                 :             :         Warning,
      80                 :             :         Error,
      81                 :             :     };
      82                 :             :     constexpr auto DEFAULT_LOG_LEVEL{Level::Debug};
      83                 :             :     constexpr size_t DEFAULT_MAX_LOG_BUFFER{1'000'000}; // buffer up to 1MB of log data prior to StartLogging
      84                 :             : 
      85                 :             :     class Logger
      86                 :             :     {
      87                 :             :     public:
      88                 :             :         struct BufferedLog {
      89                 :             :             SystemClock::time_point now;
      90                 :             :             std::chrono::seconds mocktime;
      91                 :             :             std::string str, logging_function, source_file, threadname;
      92                 :             :             int source_line;
      93                 :             :             LogFlags category;
      94                 :             :             Level level;
      95                 :             :         };
      96                 :             : 
      97                 :             :     private:
      98                 :             :         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
      99                 :             : 
     100                 :             :         FILE* m_fileout GUARDED_BY(m_cs) = nullptr;
     101                 :             :         std::list<BufferedLog> m_msgs_before_open GUARDED_BY(m_cs);
     102                 :             :         bool m_buffering GUARDED_BY(m_cs) = true; //!< Buffer messages before logging can be started.
     103                 :             :         size_t m_max_buffer_memusage GUARDED_BY(m_cs){DEFAULT_MAX_LOG_BUFFER};
     104                 :             :         size_t m_cur_buffer_memusage GUARDED_BY(m_cs){0};
     105                 :             :         size_t m_buffer_lines_discarded GUARDED_BY(m_cs){0};
     106                 :             : 
     107                 :             :         /**
     108                 :             :          * m_started_new_line is a state variable that will suppress printing of
     109                 :             :          * the timestamp when multiple calls are made that don't end in a
     110                 :             :          * newline.
     111                 :             :          */
     112                 :             :         std::atomic_bool m_started_new_line{true};
     113                 :             : 
     114                 :             :         //! Category-specific log level. Overrides `m_log_level`.
     115                 :             :         std::unordered_map<LogFlags, Level> m_category_log_levels GUARDED_BY(m_cs);
     116                 :             : 
     117                 :             :         //! If there is no category-specific log level, all logs with a severity
     118                 :             :         //! level lower than `m_log_level` will be ignored.
     119                 :             :         std::atomic<Level> m_log_level{DEFAULT_LOG_LEVEL};
     120                 :             : 
     121                 :             :         /** Log categories bitfield. */
     122                 :             :         std::atomic<uint32_t> m_categories{BCLog::NONE};
     123                 :             : 
     124                 :             :         void FormatLogStrInPlace(std::string& str, LogFlags category, Level level, std::string_view source_file, int source_line, std::string_view logging_function, std::string_view threadname, SystemClock::time_point now, std::chrono::seconds mocktime) const;
     125                 :             : 
     126                 :             :         std::string LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const;
     127                 :             : 
     128                 :             :         /** Slots that connect to the print signal */
     129                 :             :         std::list<std::function<void(const std::string&)>> m_print_callbacks GUARDED_BY(m_cs) {};
     130                 :             : 
     131                 :             :         /** Send a string to the log output (internal) */
     132                 :             :         void LogPrintStr_(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
     133                 :             :             EXCLUSIVE_LOCKS_REQUIRED(m_cs);
     134                 :             : 
     135                 :             :         std::string GetLogPrefix(LogFlags category, Level level) const;
     136                 :             : 
     137                 :             :     public:
     138                 :             :         bool m_print_to_console = false;
     139                 :             :         bool m_print_to_file = false;
     140                 :             : 
     141                 :             :         bool m_log_timestamps = DEFAULT_LOGTIMESTAMPS;
     142                 :             :         bool m_log_time_micros = DEFAULT_LOGTIMEMICROS;
     143                 :             :         bool m_log_threadnames = DEFAULT_LOGTHREADNAMES;
     144                 :             :         bool m_log_sourcelocations = DEFAULT_LOGSOURCELOCATIONS;
     145                 :             :         bool m_always_print_category_level = DEFAULT_LOGLEVELALWAYS;
     146                 :             : 
     147                 :             :         fs::path m_file_path;
     148                 :             :         std::atomic<bool> m_reopen_file{false};
     149                 :             : 
     150                 :             :         /** Send a string to the log output */
     151                 :             :         void LogPrintStr(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
     152                 :             :             EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
     153                 :             : 
     154                 :             :         /** Returns whether logs will be written to any output */
     155                 :      298243 :         bool Enabled() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
     156                 :             :         {
     157                 :      298243 :             StdLockGuard scoped_lock(m_cs);
     158   [ +  +  +  -  :      298243 :             return m_buffering || m_print_to_console || m_print_to_file || !m_print_callbacks.empty();
             -  +  -  - ]
     159                 :      298243 :         }
     160                 :             : 
     161                 :             :         /** Connect a slot to the print signal and return the connection */
     162                 :         639 :         std::list<std::function<void(const std::string&)>>::iterator PushBackCallback(std::function<void(const std::string&)> fun) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
     163                 :             :         {
     164                 :         639 :             StdLockGuard scoped_lock(m_cs);
     165         [ +  - ]:         639 :             m_print_callbacks.push_back(std::move(fun));
     166                 :         639 :             return --m_print_callbacks.end();
     167                 :         639 :         }
     168                 :             : 
     169                 :             :         /** Delete a connection */
     170                 :          56 :         void DeleteCallback(std::list<std::function<void(const std::string&)>>::iterator it) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
     171                 :             :         {
     172                 :          56 :             StdLockGuard scoped_lock(m_cs);
     173                 :          56 :             m_print_callbacks.erase(it);
     174                 :          56 :         }
     175                 :             : 
     176                 :             :         /** Start logging (and flush all buffered messages) */
     177                 :             :         bool StartLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
     178                 :             :         /** Only for testing */
     179                 :             :         void DisconnectTestLogger() EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
     180                 :             : 
     181                 :             :         /** Disable logging
     182                 :             :          * This offers a slight speedup and slightly smaller memory usage
     183                 :             :          * compared to leaving the logging system in its default state.
     184                 :             :          * Mostly intended for libbitcoin-kernel apps that don't want any logging.
     185                 :             :          * Should be used instead of StartLogging().
     186                 :             :          */
     187                 :             :         void DisableLogging() EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
     188                 :             : 
     189                 :             :         void ShrinkDebugFile();
     190                 :             : 
     191                 :           8 :         std::unordered_map<LogFlags, Level> CategoryLevels() const EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
     192                 :             :         {
     193                 :           8 :             StdLockGuard scoped_lock(m_cs);
     194         [ +  - ]:           8 :             return m_category_log_levels;
     195                 :           8 :         }
     196                 :          15 :         void SetCategoryLogLevel(const std::unordered_map<LogFlags, Level>& levels) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
     197                 :             :         {
     198                 :          15 :             StdLockGuard scoped_lock(m_cs);
     199         [ +  - ]:          15 :             m_category_log_levels = levels;
     200                 :          15 :         }
     201                 :             :         bool SetCategoryLogLevel(std::string_view category_str, std::string_view level_str) EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
     202                 :             : 
     203   [ +  -  #  #  :      271129 :         Level LogLevel() const { return m_log_level.load(); }
             #  #  #  # ]
           [ +  -  +  -  
             +  -  +  - ]
     204         [ +  - ]:          22 :         void SetLogLevel(Level level) { m_log_level = level; }
     205                 :             :         bool SetLogLevel(std::string_view level);
     206                 :             : 
     207         [ #  # ]:           0 :         uint32_t GetCategoryMask() const { return m_categories.load(); }
     208                 :             : 
     209                 :             :         void EnableCategory(LogFlags flag);
     210                 :             :         bool EnableCategory(std::string_view str);
     211                 :             :         void DisableCategory(LogFlags flag);
     212                 :             :         bool DisableCategory(std::string_view str);
     213                 :             : 
     214                 :             :         bool WillLogCategory(LogFlags category) const;
     215                 :             :         bool WillLogCategoryLevel(LogFlags category, Level level) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs);
     216                 :             : 
     217                 :             :         /** Returns a vector of the log categories in alphabetical order. */
     218                 :             :         std::vector<LogCategory> LogCategoriesList() const;
     219                 :             :         /** Returns a string with the log categories in alphabetical order. */
     220                 :        1245 :         std::string LogCategoriesString() const
     221                 :             :         {
     222   [ +  -  +  - ]:       36105 :             return util::Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
     223                 :             :         };
     224                 :             : 
     225                 :             :         //! Returns a string with all user-selectable log levels.
     226                 :             :         std::string LogLevelsString() const;
     227                 :             : 
     228                 :             :         //! Returns the string representation of a log level.
     229                 :             :         static std::string LogLevelToStr(BCLog::Level level);
     230                 :             : 
     231                 :             :         bool DefaultShrinkDebugFile() const;
     232                 :             :     };
     233                 :             : 
     234                 :             : } // namespace BCLog
     235                 :             : 
     236                 :             : BCLog::Logger& LogInstance();
     237                 :             : 
     238                 :             : /** Return true if log accepts specified category, at the specified level. */
     239                 :      274104 : static inline bool LogAcceptCategory(BCLog::LogFlags category, BCLog::Level level)
     240                 :             : {
     241                 :      274104 :     return LogInstance().WillLogCategoryLevel(category, level);
     242                 :             : }
     243                 :             : 
     244                 :             : /** Return true if str parses as a log category and set the flag */
     245                 :             : bool GetLogCategory(BCLog::LogFlags& flag, std::string_view str);
     246                 :             : 
     247                 :             : // Be conservative when using functions that
     248                 :             : // unconditionally log to debug.log! It should not be the case that an inbound
     249                 :             : // peer can fill up a user's disk with debug.log entries.
     250                 :             : 
     251                 :             : template <typename... Args>
     252                 :      298243 : static inline void LogPrintf_(std::string_view logging_function, std::string_view source_file, const int source_line, const BCLog::LogFlags flag, const BCLog::Level level, const char* fmt, const Args&... args)
     253                 :             : {
     254         [ +  - ]:      298243 :     if (LogInstance().Enabled()) {
     255                 :      298243 :         std::string log_msg;
     256                 :             :         try {
     257         [ +  - ]:      298243 :             log_msg = tfm::format(fmt, args...);
     258         [ -  - ]:           0 :         } catch (tinyformat::format_error& fmterr) {
     259                 :             :             /* Original format string will have newline so don't add one here */
     260   [ -  -  -  -  :           0 :             log_msg = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + fmt;
                   -  - ]
     261                 :             :         }
     262   [ +  -  +  - ]:      298243 :         LogInstance().LogPrintStr(log_msg, logging_function, source_file, source_line, flag, level);
     263                 :      298243 :     }
     264                 :      298243 : }
     265                 :             : 
     266                 :             : #define LogPrintLevel_(category, level, ...) LogPrintf_(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
     267                 :             : 
     268                 :             : // Log unconditionally.
     269                 :             : #define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, __VA_ARGS__)
     270                 :             : #define LogWarning(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Warning, __VA_ARGS__)
     271                 :             : #define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, __VA_ARGS__)
     272                 :             : 
     273                 :             : // Deprecated unconditional logging.
     274                 :             : #define LogPrintf(...) LogInfo(__VA_ARGS__)
     275                 :             : #define LogPrintfCategory(category, ...) LogPrintLevel_(category, BCLog::Level::Info, __VA_ARGS__)
     276                 :             : 
     277                 :             : // Use a macro instead of a function for conditional logging to prevent
     278                 :             : // evaluating arguments when logging for the category is not enabled.
     279                 :             : 
     280                 :             : // Log conditionally, prefixing the output with the passed category name and severity level.
     281                 :             : #define LogPrintLevel(category, level, ...)               \
     282                 :             :     do {                                                  \
     283                 :             :         if (LogAcceptCategory((category), (level))) {     \
     284                 :             :             LogPrintLevel_(category, level, __VA_ARGS__); \
     285                 :             :         }                                                 \
     286                 :             :     } while (0)
     287                 :             : 
     288                 :             : // Log conditionally, prefixing the output with the passed category name.
     289                 :             : #define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
     290                 :             : #define LogTrace(category, ...) LogPrintLevel(category, BCLog::Level::Trace, __VA_ARGS__)
     291                 :             : 
     292                 :             : // Deprecated conditional logging
     293                 :             : #define LogPrint(category, ...)  LogDebug(category, __VA_ARGS__)
     294                 :             : 
     295                 :             : #endif // BITCOIN_LOGGING_H
        

Generated by: LCOV version 2.0-1