LCOV - code coverage report
Current view: top level - src - logging.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 77.1 % 266 205
Test Date: 2024-08-28 04:44:32 Functions: 89.7 % 29 26
Branches: 51.3 % 298 153

             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                 :             : #include <logging.h>
       7                 :             : #include <memusage.h>
       8                 :             : #include <util/fs.h>
       9                 :             : #include <util/string.h>
      10                 :             : #include <util/threadnames.h>
      11                 :             : #include <util/time.h>
      12                 :             : 
      13                 :             : #include <array>
      14                 :             : #include <map>
      15                 :             : #include <optional>
      16                 :             : 
      17                 :             : using util::Join;
      18                 :             : using util::RemovePrefixView;
      19                 :             : 
      20                 :             : const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
      21                 :             : constexpr auto MAX_USER_SETABLE_SEVERITY_LEVEL{BCLog::Level::Info};
      22                 :             : 
      23                 :      882031 : BCLog::Logger& LogInstance()
      24                 :             : {
      25                 :             : /**
      26                 :             :  * NOTE: the logger instances is leaked on exit. This is ugly, but will be
      27                 :             :  * cleaned up by the OS/libc. Defining a logger as a global object doesn't work
      28                 :             :  * since the order of destruction of static/global objects is undefined.
      29                 :             :  * Consider if the logger gets destroyed, and then some later destructor calls
      30                 :             :  * LogPrintf, maybe indirectly, and you get a core dump at shutdown trying to
      31                 :             :  * access the logger. When the shutdown sequence is fully audited and tested,
      32                 :             :  * explicit destruction of these objects can be implemented by changing this
      33                 :             :  * from a raw pointer to a std::unique_ptr.
      34                 :             :  * Since the ~Logger() destructor is never called, the Logger class and all
      35                 :             :  * its subclasses must have implicitly-defined destructors.
      36                 :             :  *
      37                 :             :  * This method of initialization was originally introduced in
      38                 :             :  * ee3374234c60aba2cc4c5cd5cac1c0aefc2d817c.
      39                 :             :  */
      40   [ +  +  +  -  :      882031 :     static BCLog::Logger* g_logger{new BCLog::Logger()};
                   +  - ]
      41                 :      882031 :     return *g_logger;
      42                 :             : }
      43                 :             : 
      44                 :             : bool fLogIPs = DEFAULT_LOGIPS;
      45                 :             : 
      46                 :      298816 : static int FileWriteStr(std::string_view str, FILE *fp)
      47                 :             : {
      48                 :      298816 :     return fwrite(str.data(), 1, str.size(), fp);
      49                 :             : }
      50                 :             : 
      51                 :         583 : bool BCLog::Logger::StartLogging()
      52                 :             : {
      53                 :         583 :     StdLockGuard scoped_lock(m_cs);
      54                 :             : 
      55         [ -  + ]:         583 :     assert(m_buffering);
      56         [ -  + ]:         583 :     assert(m_fileout == nullptr);
      57                 :             : 
      58         [ +  - ]:         583 :     if (m_print_to_file) {
      59         [ -  + ]:         583 :         assert(!m_file_path.empty());
      60         [ +  - ]:         583 :         m_fileout = fsbridge::fopen(m_file_path, "a");
      61         [ +  - ]:         583 :         if (!m_fileout) {
      62                 :             :             return false;
      63                 :             :         }
      64                 :             : 
      65                 :         583 :         setbuf(m_fileout, nullptr); // unbuffered
      66                 :             : 
      67                 :             :         // Add newlines to the logfile to distinguish this execution from the
      68                 :             :         // last one.
      69         [ +  - ]:         583 :         FileWriteStr("\n\n\n\n\n", m_fileout);
      70                 :             :     }
      71                 :             : 
      72                 :             :     // dump buffered messages from before we opened the log
      73                 :         583 :     m_buffering = false;
      74         [ -  + ]:         583 :     if (m_buffer_lines_discarded > 0) {
      75   [ #  #  #  # ]:           0 :         LogPrintStr_(strprintf("Early logging buffer overflowed, %d log lines discarded.\n", m_buffer_lines_discarded), __func__, __FILE__, __LINE__, BCLog::ALL, Level::Info);
      76                 :             :     }
      77         [ +  + ]:        2332 :     while (!m_msgs_before_open.empty()) {
      78         [ +  - ]:        1749 :         const auto& buflog = m_msgs_before_open.front();
      79         [ +  - ]:        1749 :         std::string s{buflog.str};
      80         [ +  - ]:        1749 :         FormatLogStrInPlace(s, buflog.category, buflog.level, buflog.source_file, buflog.source_line, buflog.logging_function, buflog.threadname, buflog.now, buflog.mocktime);
      81                 :        1749 :         m_msgs_before_open.pop_front();
      82                 :             : 
      83   [ +  -  +  - ]:        1749 :         if (m_print_to_file) FileWriteStr(s, m_fileout);
      84   [ -  +  -  - ]:        1749 :         if (m_print_to_console) fwrite(s.data(), 1, s.size(), stdout);
      85         [ +  + ]:        3498 :         for (const auto& cb : m_print_callbacks) {
      86         [ +  - ]:        1749 :             cb(s);
      87                 :             :         }
      88                 :        1749 :     }
      89                 :         583 :     m_cur_buffer_memusage = 0;
      90   [ -  +  -  - ]:         583 :     if (m_print_to_console) fflush(stdout);
      91                 :             : 
      92                 :             :     return true;
      93                 :         583 : }
      94                 :             : 
      95                 :         582 : void BCLog::Logger::DisconnectTestLogger()
      96                 :             : {
      97                 :         582 :     StdLockGuard scoped_lock(m_cs);
      98                 :         582 :     m_buffering = true;
      99   [ +  -  +  - ]:         582 :     if (m_fileout != nullptr) fclose(m_fileout);
     100                 :         582 :     m_fileout = nullptr;
     101                 :         582 :     m_print_callbacks.clear();
     102                 :         582 :     m_max_buffer_memusage = DEFAULT_MAX_LOG_BUFFER;
     103                 :         582 :     m_cur_buffer_memusage = 0;
     104                 :         582 :     m_buffer_lines_discarded = 0;
     105                 :         582 :     m_msgs_before_open.clear();
     106                 :             : 
     107                 :         582 : }
     108                 :             : 
     109                 :           0 : void BCLog::Logger::DisableLogging()
     110                 :             : {
     111                 :           0 :     {
     112                 :           0 :         StdLockGuard scoped_lock(m_cs);
     113         [ #  # ]:           0 :         assert(m_buffering);
     114         [ #  # ]:           0 :         assert(m_print_callbacks.empty());
     115                 :           0 :     }
     116                 :           0 :     m_print_to_file = false;
     117                 :           0 :     m_print_to_console = false;
     118                 :           0 :     StartLogging();
     119                 :           0 : }
     120                 :             : 
     121                 :         585 : void BCLog::Logger::EnableCategory(BCLog::LogFlags flag)
     122                 :             : {
     123                 :         585 :     m_categories |= flag;
     124                 :         585 : }
     125                 :             : 
     126                 :         583 : bool BCLog::Logger::EnableCategory(std::string_view str)
     127                 :             : {
     128                 :         583 :     BCLog::LogFlags flag;
     129         [ +  - ]:         583 :     if (!GetLogCategory(flag, str)) return false;
     130                 :         583 :     EnableCategory(flag);
     131                 :         583 :     return true;
     132                 :             : }
     133                 :             : 
     134                 :        1166 : void BCLog::Logger::DisableCategory(BCLog::LogFlags flag)
     135                 :             : {
     136                 :        1166 :     m_categories &= ~flag;
     137                 :        1166 : }
     138                 :             : 
     139                 :        1166 : bool BCLog::Logger::DisableCategory(std::string_view str)
     140                 :             : {
     141                 :        1166 :     BCLog::LogFlags flag;
     142         [ +  - ]:        1166 :     if (!GetLogCategory(flag, str)) return false;
     143                 :        1166 :     DisableCategory(flag);
     144                 :        1166 :     return true;
     145                 :             : }
     146                 :             : 
     147                 :      308946 : bool BCLog::Logger::WillLogCategory(BCLog::LogFlags category) const
     148                 :             : {
     149                 :      308946 :     return (m_categories.load(std::memory_order_relaxed) & category) != 0;
     150                 :             : }
     151                 :             : 
     152                 :      274104 : bool BCLog::Logger::WillLogCategoryLevel(BCLog::LogFlags category, BCLog::Level level) const
     153                 :             : {
     154                 :             :     // Log messages at Info, Warning and Error level unconditionally, so that
     155                 :             :     // important troubleshooting information doesn't get lost.
     156         [ +  + ]:      274104 :     if (level >= BCLog::Level::Info) return true;
     157                 :             : 
     158         [ +  + ]:      274086 :     if (!WillLogCategory(category)) return false;
     159                 :             : 
     160                 :      271118 :     StdLockGuard scoped_lock(m_cs);
     161                 :      271118 :     const auto it{m_category_log_levels.find(category)};
     162         [ +  + ]:      271118 :     return level >= (it == m_category_log_levels.end() ? LogLevel() : it->second);
     163                 :      271118 : }
     164                 :             : 
     165                 :           0 : bool BCLog::Logger::DefaultShrinkDebugFile() const
     166                 :             : {
     167                 :           0 :     return m_categories == BCLog::NONE;
     168                 :             : }
     169                 :             : 
     170                 :             : static const std::map<std::string, BCLog::LogFlags, std::less<>> LOG_CATEGORIES_BY_STR{
     171                 :             :     {"net", BCLog::NET},
     172                 :             :     {"tor", BCLog::TOR},
     173                 :             :     {"mempool", BCLog::MEMPOOL},
     174                 :             :     {"http", BCLog::HTTP},
     175                 :             :     {"bench", BCLog::BENCH},
     176                 :             :     {"zmq", BCLog::ZMQ},
     177                 :             :     {"walletdb", BCLog::WALLETDB},
     178                 :             :     {"rpc", BCLog::RPC},
     179                 :             :     {"estimatefee", BCLog::ESTIMATEFEE},
     180                 :             :     {"addrman", BCLog::ADDRMAN},
     181                 :             :     {"selectcoins", BCLog::SELECTCOINS},
     182                 :             :     {"reindex", BCLog::REINDEX},
     183                 :             :     {"cmpctblock", BCLog::CMPCTBLOCK},
     184                 :             :     {"rand", BCLog::RAND},
     185                 :             :     {"prune", BCLog::PRUNE},
     186                 :             :     {"proxy", BCLog::PROXY},
     187                 :             :     {"mempoolrej", BCLog::MEMPOOLREJ},
     188                 :             :     {"libevent", BCLog::LIBEVENT},
     189                 :             :     {"coindb", BCLog::COINDB},
     190                 :             :     {"qt", BCLog::QT},
     191                 :             :     {"leveldb", BCLog::LEVELDB},
     192                 :             :     {"validation", BCLog::VALIDATION},
     193                 :             :     {"i2p", BCLog::I2P},
     194                 :             :     {"ipc", BCLog::IPC},
     195                 :             : #ifdef DEBUG_LOCKCONTENTION
     196                 :             :     {"lock", BCLog::LOCK},
     197                 :             : #endif
     198                 :             :     {"blockstorage", BCLog::BLOCKSTORAGE},
     199                 :             :     {"txreconciliation", BCLog::TXRECONCILIATION},
     200                 :             :     {"scan", BCLog::SCAN},
     201                 :             :     {"txpackages", BCLog::TXPACKAGES},
     202                 :             : };
     203                 :             : 
     204                 :             : static const std::unordered_map<BCLog::LogFlags, std::string> LOG_CATEGORIES_BY_FLAG{
     205                 :             :     // Swap keys and values from LOG_CATEGORIES_BY_STR.
     206                 :         231 :     [](const auto& in) {
     207                 :         231 :         std::unordered_map<BCLog::LogFlags, std::string> out;
     208   [ +  -  +  + ]:        6699 :         for (const auto& [k, v] : in) {
     209                 :        6468 :             const bool inserted{out.emplace(v, k).second};
     210         [ -  + ]:        6468 :             assert(inserted);
     211                 :             :         }
     212                 :         231 :         return out;
     213                 :           0 :     }(LOG_CATEGORIES_BY_STR)
     214                 :             : };
     215                 :             : 
     216                 :        1781 : bool GetLogCategory(BCLog::LogFlags& flag, std::string_view str)
     217                 :             : {
     218   [ +  +  +  -  :        1781 :     if (str.empty() || str == "1" || str == "all") {
                   -  + ]
     219                 :         583 :         flag = BCLog::ALL;
     220                 :         583 :         return true;
     221                 :             :     }
     222                 :        1198 :     auto it = LOG_CATEGORIES_BY_STR.find(str);
     223         [ +  - ]:        1198 :     if (it != LOG_CATEGORIES_BY_STR.end()) {
     224                 :        1198 :         flag = it->second;
     225                 :        1198 :         return true;
     226                 :             :     }
     227                 :             :     return false;
     228                 :             : }
     229                 :             : 
     230                 :        2992 : std::string BCLog::Logger::LogLevelToStr(BCLog::Level level)
     231                 :             : {
     232   [ +  +  +  +  :        2992 :     switch (level) {
                   +  - ]
     233                 :         916 :     case BCLog::Level::Trace:
     234                 :         916 :         return "trace";
     235                 :        1168 :     case BCLog::Level::Debug:
     236                 :        1168 :         return "debug";
     237                 :         597 :     case BCLog::Level::Info:
     238                 :         597 :         return "info";
     239                 :           6 :     case BCLog::Level::Warning:
     240                 :           6 :         return "warning";
     241                 :         305 :     case BCLog::Level::Error:
     242                 :         305 :         return "error";
     243                 :             :     }
     244                 :           0 :     assert(false);
     245                 :             : }
     246                 :             : 
     247                 :      269414 : static std::string LogCategoryToStr(BCLog::LogFlags category)
     248                 :             : {
     249         [ -  + ]:      269414 :     if (category == BCLog::ALL) {
     250                 :           0 :         return "all";
     251                 :             :     }
     252                 :      269414 :     auto it = LOG_CATEGORIES_BY_FLAG.find(category);
     253         [ -  + ]:      269414 :     assert(it != LOG_CATEGORIES_BY_FLAG.end());
     254                 :      269414 :     return it->second;
     255                 :             : }
     256                 :             : 
     257                 :         589 : static std::optional<BCLog::Level> GetLogLevel(std::string_view level_str)
     258                 :             : {
     259         [ +  + ]:         589 :     if (level_str == "trace") {
     260                 :         585 :         return BCLog::Level::Trace;
     261         [ +  + ]:           4 :     } else if (level_str == "debug") {
     262                 :           2 :         return BCLog::Level::Debug;
     263         [ +  - ]:           2 :     } else if (level_str == "info") {
     264                 :           2 :         return BCLog::Level::Info;
     265         [ #  # ]:           0 :     } else if (level_str == "warning") {
     266                 :           0 :         return BCLog::Level::Warning;
     267         [ #  # ]:           0 :     } else if (level_str == "error") {
     268                 :           0 :         return BCLog::Level::Error;
     269                 :             :     } else {
     270                 :           0 :         return std::nullopt;
     271                 :             :     }
     272                 :             : }
     273                 :             : 
     274                 :        1245 : std::vector<LogCategory> BCLog::Logger::LogCategoriesList() const
     275                 :             : {
     276                 :        1245 :     std::vector<LogCategory> ret;
     277         [ +  - ]:        1245 :     ret.reserve(LOG_CATEGORIES_BY_STR.size());
     278   [ +  -  +  + ]:       36105 :     for (const auto& [category, flag] : LOG_CATEGORIES_BY_STR) {
     279   [ +  -  +  - ]:       34860 :         ret.push_back(LogCategory{.category = category, .active = WillLogCategory(flag)});
     280                 :             :     }
     281                 :        1245 :     return ret;
     282                 :           0 : }
     283                 :             : 
     284                 :             : /** Log severity levels that can be selected by the user. */
     285                 :             : static constexpr std::array<BCLog::Level, 3> LogLevelsList()
     286                 :             : {
     287                 :             :     return {BCLog::Level::Info, BCLog::Level::Debug, BCLog::Level::Trace};
     288                 :             : }
     289                 :             : 
     290                 :         583 : std::string BCLog::Logger::LogLevelsString() const
     291                 :             : {
     292                 :         583 :     const auto& levels = LogLevelsList();
     293   [ +  -  +  - ]:        2915 :     return Join(std::vector<BCLog::Level>{levels.begin(), levels.end()}, ", ", [](BCLog::Level level) { return LogLevelToStr(level); });
     294                 :             : }
     295                 :             : 
     296                 :      298233 : std::string BCLog::Logger::LogTimestampStr(SystemClock::time_point now, std::chrono::seconds mocktime) const
     297                 :             : {
     298         [ +  + ]:      298233 :     std::string strStamped;
     299                 :             : 
     300         [ +  + ]:      298233 :     if (!m_log_timestamps)
     301                 :             :         return strStamped;
     302                 :             : 
     303                 :      298177 :     const auto now_seconds{std::chrono::time_point_cast<std::chrono::seconds>(now)};
     304         [ +  - ]:      298177 :     strStamped = FormatISO8601DateTime(TicksSinceEpoch<std::chrono::seconds>(now_seconds));
     305   [ +  -  +  - ]:      298177 :     if (m_log_time_micros && !strStamped.empty()) {
     306                 :      298177 :         strStamped.pop_back();
     307         [ +  - ]:      596354 :         strStamped += strprintf(".%06dZ", Ticks<std::chrono::microseconds>(now - now_seconds));
     308                 :             :     }
     309         [ +  + ]:      298177 :     if (mocktime > 0s) {
     310   [ +  -  +  -  :      572793 :         strStamped += " (mocktime: " + FormatISO8601DateTime(count_seconds(mocktime)) + ")";
                   +  - ]
     311                 :             :     }
     312         [ +  - ]:      596410 :     strStamped += ' ';
     313                 :             : 
     314                 :             :     return strStamped;
     315                 :           0 : }
     316                 :             : 
     317                 :             : namespace BCLog {
     318                 :             :     /** Belts and suspenders: make sure outgoing log messages don't contain
     319                 :             :      * potentially suspicious characters, such as terminal control codes.
     320                 :             :      *
     321                 :             :      * This escapes control characters except newline ('\n') in C syntax.
     322                 :             :      * It escapes instead of removes them to still allow for troubleshooting
     323                 :             :      * issues where they accidentally end up in strings.
     324                 :             :      */
     325                 :      298247 :     std::string LogEscapeMessage(std::string_view str) {
     326                 :      298247 :         std::string ret;
     327         [ +  + ]:    29974117 :         for (char ch_in : str) {
     328                 :    29675870 :             uint8_t ch = (uint8_t)ch_in;
     329   [ +  +  +  + ]:    29675870 :             if ((ch >= 32 || ch == '\n') && ch != '\x7f') {
     330         [ +  - ]:    59351736 :                 ret += ch_in;
     331                 :             :             } else {
     332         [ +  - ]:           8 :                 ret += strprintf("\\x%02x", ch);
     333                 :             :             }
     334                 :             :         }
     335                 :      298247 :         return ret;
     336                 :           0 :     }
     337                 :             : } // namespace BCLog
     338                 :             : 
     339                 :      298233 : std::string BCLog::Logger::GetLogPrefix(BCLog::LogFlags category, BCLog::Level level) const
     340                 :             : {
     341         [ +  + ]:      298233 :     if (category == LogFlags::NONE) category = LogFlags::ALL;
     342                 :             : 
     343   [ +  -  +  + ]:      298233 :     const bool has_category{m_always_print_category_level || category != LogFlags::ALL};
     344                 :             : 
     345                 :             :     // If there is no category, Info is implied
     346         [ +  + ]:      298233 :     if (!has_category && level == Level::Info) return {};
     347                 :             : 
     348                 :      269721 :     std::string s{"["};
     349         [ +  + ]:      269721 :     if (has_category) {
     350         [ +  - ]:      538828 :         s += LogCategoryToStr(category);
     351                 :             :     }
     352                 :             : 
     353   [ +  -  +  + ]:      269721 :     if (m_always_print_category_level || !has_category || level != Level::Debug) {
     354                 :             :         // If there is a category, Debug is implied, so don't add the level
     355                 :             : 
     356                 :             :         // Only add separator if we have a category
     357   [ +  +  +  - ]:         660 :         if (has_category) s += ":";
     358         [ +  - ]:        1320 :         s += Logger::LogLevelToStr(level);
     359                 :             :     }
     360                 :             : 
     361         [ +  - ]:      269721 :     s += "] ";
     362                 :      269721 :     return s;
     363                 :      269721 : }
     364                 :             : 
     365                 :        1759 : static size_t MemUsage(const BCLog::Logger::BufferedLog& buflog)
     366                 :             : {
     367                 :        1759 :     return buflog.str.size() + buflog.logging_function.size() + buflog.source_file.size() + buflog.threadname.size() + memusage::MallocUsage(sizeof(memusage::list_node<BCLog::Logger::BufferedLog>));
     368                 :             : }
     369                 :             : 
     370                 :      298233 : void BCLog::Logger::FormatLogStrInPlace(std::string& str, BCLog::LogFlags category, BCLog::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
     371                 :             : {
     372         [ +  - ]:      298233 :     str.insert(0, GetLogPrefix(category, level));
     373                 :             : 
     374         [ +  + ]:      298233 :     if (m_log_sourcelocations) {
     375         [ +  - ]:      596368 :         str.insert(0, strprintf("[%s:%d] [%s] ", RemovePrefixView(source_file, "./"), source_line, logging_function));
     376                 :             :     }
     377                 :             : 
     378         [ +  + ]:      298233 :     if (m_log_threadnames) {
     379   [ +  +  +  - ]:      596354 :         str.insert(0, strprintf("[%s] ", (threadname.empty() ? "unknown" : threadname)));
     380                 :             :     }
     381                 :             : 
     382         [ +  - ]:      298233 :     str.insert(0, LogTimestampStr(now, mocktime));
     383                 :      298233 : }
     384                 :             : 
     385                 :      298243 : void BCLog::Logger::LogPrintStr(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
     386                 :             : {
     387                 :      298243 :     StdLockGuard scoped_lock(m_cs);
     388         [ +  - ]:      298243 :     return LogPrintStr_(str, logging_function, source_file, source_line, category, level);
     389                 :      298243 : }
     390                 :             : 
     391                 :      298243 : void BCLog::Logger::LogPrintStr_(std::string_view str, std::string_view logging_function, std::string_view source_file, int source_line, BCLog::LogFlags category, BCLog::Level level)
     392                 :             : {
     393                 :      298243 :     std::string str_prefixed = LogEscapeMessage(str);
     394                 :             : 
     395         [ +  - ]:      298243 :     const bool starts_new_line = m_started_new_line;
     396   [ +  -  -  +  :      298243 :     m_started_new_line = !str.empty() && str[str.size()-1] == '\n';
                   +  + ]
     397                 :             : 
     398         [ +  + ]:      298243 :     if (m_buffering) {
     399         [ -  + ]:        1759 :         if (!starts_new_line) {
     400         [ #  # ]:           0 :             if (!m_msgs_before_open.empty()) {
     401         [ #  # ]:           0 :                 m_msgs_before_open.back().str += str_prefixed;
     402                 :           0 :                 m_cur_buffer_memusage += str_prefixed.size();
     403                 :           0 :                 return;
     404                 :             :             } else {
     405                 :             :                 // unlikely edge case; add a marker that something was trimmed
     406         [ #  # ]:           0 :                 str_prefixed.insert(0, "[...] ");
     407                 :             :             }
     408                 :             :         }
     409                 :             : 
     410                 :        1759 :         {
     411                 :        1759 :             BufferedLog buf{
     412                 :        1759 :                 .now=SystemClock::now(),
     413         [ +  - ]:        1759 :                 .mocktime=GetMockTime(),
     414                 :             :                 .str=str_prefixed,
     415                 :             :                 .logging_function=std::string(logging_function),
     416                 :        1759 :                 .source_file=std::string(source_file),
     417                 :             :                 .threadname=util::ThreadGetInternalName(),
     418                 :             :                 .source_line=source_line,
     419                 :             :                 .category=category,
     420                 :             :                 .level=level,
     421   [ +  -  +  -  :        1759 :             };
          +  -  +  -  +  
                      - ]
     422                 :        1759 :             m_cur_buffer_memusage += MemUsage(buf);
     423         [ +  - ]:        1759 :             m_msgs_before_open.push_back(std::move(buf));
     424                 :           0 :         }
     425                 :             : 
     426         [ -  + ]:        3518 :         while (m_cur_buffer_memusage > m_max_buffer_memusage) {
     427         [ #  # ]:           0 :             if (m_msgs_before_open.empty()) {
     428                 :           0 :                 m_cur_buffer_memusage = 0;
     429                 :           0 :                 break;
     430                 :             :             }
     431                 :           0 :             m_cur_buffer_memusage -= MemUsage(m_msgs_before_open.front());
     432                 :           0 :             m_msgs_before_open.pop_front();
     433                 :           0 :             ++m_buffer_lines_discarded;
     434                 :             :         }
     435                 :             : 
     436                 :        1759 :         return;
     437                 :             :     }
     438                 :             : 
     439         [ +  - ]:      296484 :     if (starts_new_line) {
     440   [ +  -  +  -  :      592968 :         FormatLogStrInPlace(str_prefixed, category, level, source_file, source_line, logging_function, util::ThreadGetInternalName(), SystemClock::now(), GetMockTime());
                   +  - ]
     441                 :             :     }
     442                 :             : 
     443         [ -  + ]:      296484 :     if (m_print_to_console) {
     444                 :             :         // print to console
     445         [ #  # ]:           0 :         fwrite(str_prefixed.data(), 1, str_prefixed.size(), stdout);
     446         [ #  # ]:           0 :         fflush(stdout);
     447                 :             :     }
     448         [ +  + ]:      593526 :     for (const auto& cb : m_print_callbacks) {
     449         [ +  - ]:      297042 :         cb(str_prefixed);
     450                 :             :     }
     451         [ +  - ]:      296484 :     if (m_print_to_file) {
     452         [ -  + ]:      296484 :         assert(m_fileout != nullptr);
     453                 :             : 
     454                 :             :         // reopen the log file, if requested
     455         [ +  + ]:      296484 :         if (m_reopen_file) {
     456         [ +  - ]:           6 :             m_reopen_file = false;
     457         [ +  - ]:           6 :             FILE* new_fileout = fsbridge::fopen(m_file_path, "a");
     458         [ +  - ]:           6 :             if (new_fileout) {
     459                 :           6 :                 setbuf(new_fileout, nullptr); // unbuffered
     460         [ +  - ]:           6 :                 fclose(m_fileout);
     461                 :           6 :                 m_fileout = new_fileout;
     462                 :             :             }
     463                 :             :         }
     464         [ +  - ]:      296484 :         FileWriteStr(str_prefixed, m_fileout);
     465                 :             :     }
     466                 :      298243 : }
     467                 :             : 
     468                 :           0 : void BCLog::Logger::ShrinkDebugFile()
     469                 :             : {
     470                 :             :     // Amount of debug.log to save at end when shrinking (must fit in memory)
     471                 :           0 :     constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
     472                 :             : 
     473         [ #  # ]:           0 :     assert(!m_file_path.empty());
     474                 :             : 
     475                 :             :     // Scroll debug.log if it's getting too big
     476                 :           0 :     FILE* file = fsbridge::fopen(m_file_path, "r");
     477                 :             : 
     478                 :             :     // Special files (e.g. device nodes) may not have a size.
     479                 :           0 :     size_t log_size = 0;
     480                 :           0 :     try {
     481         [ #  # ]:           0 :         log_size = fs::file_size(m_file_path);
     482         [ -  - ]:           0 :     } catch (const fs::filesystem_error&) {}
     483                 :             : 
     484                 :             :     // If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
     485                 :             :     // trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
     486         [ #  # ]:           0 :     if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
     487                 :             :     {
     488                 :             :         // Restart the file with some of the end
     489                 :           0 :         std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
     490         [ #  # ]:           0 :         if (fseek(file, -((long)vch.size()), SEEK_END)) {
     491         [ #  # ]:           0 :             LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
     492         [ #  # ]:           0 :             fclose(file);
     493                 :           0 :             return;
     494                 :             :         }
     495         [ #  # ]:           0 :         int nBytes = fread(vch.data(), 1, vch.size(), file);
     496         [ #  # ]:           0 :         fclose(file);
     497                 :             : 
     498         [ #  # ]:           0 :         file = fsbridge::fopen(m_file_path, "w");
     499         [ #  # ]:           0 :         if (file)
     500                 :             :         {
     501         [ #  # ]:           0 :             fwrite(vch.data(), 1, nBytes, file);
     502         [ #  # ]:           0 :             fclose(file);
     503                 :             :         }
     504                 :           0 :     }
     505         [ #  # ]:           0 :     else if (file != nullptr)
     506                 :           0 :         fclose(file);
     507                 :             : }
     508                 :             : 
     509                 :         585 : bool BCLog::Logger::SetLogLevel(std::string_view level_str)
     510                 :             : {
     511                 :         585 :     const auto level = GetLogLevel(level_str);
     512   [ +  -  +  - ]:         585 :     if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
     513                 :         585 :     m_log_level = level.value();
     514                 :         585 :     return true;
     515                 :             : }
     516                 :             : 
     517                 :           4 : bool BCLog::Logger::SetCategoryLogLevel(std::string_view category_str, std::string_view level_str)
     518                 :             : {
     519                 :           4 :     BCLog::LogFlags flag;
     520         [ +  - ]:           4 :     if (!GetLogCategory(flag, category_str)) return false;
     521                 :             : 
     522                 :           4 :     const auto level = GetLogLevel(level_str);
     523   [ +  -  +  - ]:           4 :     if (!level.has_value() || level.value() > MAX_USER_SETABLE_SEVERITY_LEVEL) return false;
     524                 :             : 
     525                 :           4 :     StdLockGuard scoped_lock(m_cs);
     526         [ +  - ]:           4 :     m_category_log_levels[flag] = level.value();
     527                 :           4 :     return true;
     528                 :           4 : }
        

Generated by: LCOV version 2.0-1