LCOV - code coverage report
Current view: top level - source/ps - CLogger.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 86 147 58.5 %
Date: 2026-12-03 01:19:39 Functions: 10 16 62.5 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "CLogger.h"
      21             : 
      22             : #include "graphics/Canvas2D.h"
      23             : #include "graphics/Color.h"
      24             : #include "graphics/FontMetrics.h"
      25             : #include "graphics/TextRenderer.h"
      26             : #include "lib/debug.h"
      27             : #include "lib/os_path.h"
      28             : #include "lib/path.h"
      29             : #include "lib/secure_crt.h"
      30             : #include "lib/timer.h"
      31             : #include "maths/Vector2D.h"
      32             : #include "ps/CConsole.h"
      33             : #include "ps/CStr.h"
      34             : #include "ps/CStrIntern.h"
      35             : #include "ps/Profile.h"
      36             : #include "ps/Pyrogenesis.h"
      37             : 
      38             : #include <boost/algorithm/string/replace.hpp>
      39             : #include <cstring>
      40             : #include <ctime>
      41             : #include <fstream>
      42             : #include <iostream>
      43             : #include <utility>
      44             : 
      45             : CStrW g_UniqueLogPostfix;
      46             : static const double RENDER_TIMEOUT = 10.0; // seconds before messages are deleted
      47             : static const double RENDER_TIMEOUT_RATE = 10.0; // number of timed-out messages deleted per second
      48             : static const size_t RENDER_LIMIT = 20; // maximum messages on screen at once
      49             : 
      50             : // Set up a default logger that throws everything away, because that's
      51             : // better than crashing. (This is particularly useful for unit tests which
      52             : // don't care about any log output.)
      53             : struct BlackHoleStreamBuf : public std::streambuf
      54             : {
      55             : } blackHoleStreamBuf;
      56             : std::ostream blackHoleStream(&blackHoleStreamBuf);
      57             : CLogger nullLogger{blackHoleStream, blackHoleStream, true};
      58             : 
      59             : CLogger* g_Logger = &nullLogger;
      60             : 
      61             : const char* html_header0 =
      62             :     "<!DOCTYPE html>\n"
      63             :     "<meta charset=\"utf-8\">\n"
      64             :     "<title>Pyrogenesis Log</title>\n"
      65             :     "<style>"
      66             :     "body { background: #eee; color: black; font-family: sans-serif; } "
      67             :     "p { background: white; margin: 3px 0 3px 0; } "
      68             :     ".error { color: red; } "
      69             :     ".warning { color: blue; }"
      70             :     "</style>\n"
      71             :     "<h2>0 A.D. (";
      72             : 
      73             : const char* html_header1 = "</h2>\n";
      74             : 
      75         165 : CLogger::CLogger(std::ostream& mainLog, std::ostream& interestingLog, const bool useDebugPrintf) :
      76         165 :     m_MainLog{mainLog},
      77         165 :     m_InterestingLog{interestingLog},
      78         165 :     m_UseDebugPrintf{useDebugPrintf}
      79             : {
      80         165 :     m_MainLog << html_header0 << PS_VERSION << ") Main log" << html_header1;
      81         165 :     m_InterestingLog << html_header0 << PS_VERSION << ") Main log (warnings and errors only)" << html_header1;
      82         165 : }
      83             : 
      84         165 : CLogger::~CLogger()
      85             : {
      86         165 :     char buffer[128];
      87         165 :     sprintf_s(buffer, ARRAY_SIZE(buffer), " with %d message(s), %d error(s) and %d warning(s).", m_NumberOfMessages,m_NumberOfErrors,m_NumberOfWarnings);
      88             : 
      89         165 :     time_t t = time(NULL);
      90         165 :     struct tm* now = localtime(&t);
      91         165 :     char currentDate[17];
      92         165 :     sprintf_s(currentDate, ARRAY_SIZE(currentDate), "%04d-%02d-%02d", 1900+now->tm_year, 1+now->tm_mon, now->tm_mday);
      93         165 :     char currentTime[10];
      94         165 :     sprintf_s(currentTime, ARRAY_SIZE(currentTime), "%02d:%02d:%02d", now->tm_hour, now->tm_min, now->tm_sec);
      95             : 
      96             :     //Write closing text
      97             : 
      98         165 :     m_MainLog << "<p>Engine exited successfully on " << currentDate;
      99         165 :     m_MainLog << " at " << currentTime << buffer << "</p>\n";
     100             : 
     101         165 :     m_InterestingLog << "<p>Engine exited successfully on " << currentDate;
     102         165 :     m_InterestingLog << " at " << currentTime << buffer << "</p>\n";
     103         165 : }
     104             : 
     105        1657 : static std::string ToHTML(const char* message)
     106             : {
     107        1657 :     std::string cmessage = message;
     108        1657 :     boost::algorithm::replace_all(cmessage, "&", "&amp;");
     109        1657 :     boost::algorithm::replace_all(cmessage, "<", "&lt;");
     110        1657 :     return cmessage;
     111           0 : }
     112             : 
     113        1214 : void CLogger::WriteMessage(const char* message, bool doRender = false)
     114             : {
     115        1214 :     std::string cmessage = ToHTML(message);
     116             : 
     117        1214 :     std::lock_guard<std::mutex> lock(m_Mutex);
     118             : 
     119        1214 :     ++m_NumberOfMessages;
     120             : //  if (m_UseDebugPrintf)
     121             : //      debug_printf("MESSAGE: %s\n", message);
     122             : 
     123        1214 :     m_MainLog << "<p>" << cmessage << "</p>\n";
     124        1214 :     m_MainLog.flush();
     125             : 
     126        1214 :     if (doRender)
     127             :     {
     128           7 :         if (g_Console) g_Console->InsertMessage(std::string("INFO: ") + message);
     129             : 
     130           7 :         PushRenderMessage(Normal, message);
     131             :     }
     132        2418 : }
     133             : 
     134         417 : void CLogger::WriteError(const char* message)
     135             : {
     136         417 :     std::string cmessage = ToHTML(message);
     137             : 
     138         417 :     std::lock_guard<std::mutex> lock(m_Mutex);
     139             : 
     140         417 :     ++m_NumberOfErrors;
     141         417 :     if (m_UseDebugPrintf)
     142           0 :         debug_printf("ERROR: %.16000s\n", message);
     143             : 
     144         417 :     if (g_Console) g_Console->InsertMessage(std::string("ERROR: ") + message);
     145         417 :     m_InterestingLog << "<p class=\"error\">ERROR: " << cmessage << "</p>\n";
     146         417 :     m_InterestingLog.flush();
     147             : 
     148         417 :     m_MainLog << "<p class=\"error\">ERROR: " << cmessage << "</p>\n";
     149         417 :     m_MainLog.flush();
     150             : 
     151         417 :     PushRenderMessage(Error, message);
     152         834 : }
     153             : 
     154          26 : void CLogger::WriteWarning(const char* message)
     155             : {
     156          26 :     std::string cmessage = ToHTML(message);
     157             : 
     158          26 :     std::lock_guard<std::mutex> lock(m_Mutex);
     159             : 
     160          26 :     ++m_NumberOfWarnings;
     161          26 :     if (m_UseDebugPrintf)
     162           0 :         debug_printf("WARNING: %s\n", message);
     163             : 
     164          26 :     if (g_Console) g_Console->InsertMessage(std::string("WARNING: ") + message);
     165          26 :     m_InterestingLog << "<p class=\"warning\">WARNING: " << cmessage << "</p>\n";
     166          26 :     m_InterestingLog.flush();
     167             : 
     168          26 :     m_MainLog << "<p class=\"warning\">WARNING: " << cmessage << "</p>\n";
     169          26 :     m_MainLog.flush();
     170             : 
     171          26 :     PushRenderMessage(Warning, message);
     172          52 : }
     173             : 
     174           0 : void CLogger::Render(CCanvas2D& canvas)
     175             : {
     176           0 :     PROFILE3("logger");
     177             : 
     178           0 :     CleanupRenderQueue();
     179             : 
     180           0 :     CStrIntern font_name{"mono-stroke-10"};
     181           0 :     CFontMetrics font{font_name};
     182           0 :     float height{font.GetHeight()};
     183             : 
     184           0 :     CTextRenderer textRenderer;
     185           0 :     textRenderer.SetCurrentFont(font_name, CStrIntern{});
     186           0 :     textRenderer.SetCurrentColor(CColor(1.0f, 1.0f, 1.0f, 1.0f));
     187             : 
     188             :     // Offset by an extra 35px vertically to avoid the top bar.
     189           0 :     textRenderer.Translate(4.0f, 35.0f + height);
     190             : 
     191             :     // (Lock must come after loading the CFont, since that might log error messages
     192             :     // and attempt to lock the mutex recursively which is forbidden)
     193           0 :     std::lock_guard<std::mutex> lock(m_Mutex);
     194             : 
     195           0 :     for (const RenderedMessage& msg : m_RenderMessages)
     196             :     {
     197           0 :         const char* type;
     198           0 :         if (msg.method == Normal)
     199             :         {
     200           0 :             type = "info";
     201           0 :             textRenderer.SetCurrentColor(CColor(0.0f, 0.8f, 0.0f, 1.0f));
     202             :         }
     203           0 :         else if (msg.method == Warning)
     204             :         {
     205           0 :             type = "warning";
     206           0 :             textRenderer.SetCurrentColor(CColor(1.0f, 1.0f, 0.0f, 1.0f));
     207             :         }
     208             :         else
     209             :         {
     210           0 :             type = "error";
     211           0 :             textRenderer.SetCurrentColor(CColor(1.0f, 0.0f, 0.0f, 1.0f));
     212             :         }
     213             : 
     214           0 :         const CVector2D savedTranslate = textRenderer.GetTranslate();
     215             : 
     216           0 :         textRenderer.PrintfAdvance(L"[%8.3f] %hs: ", msg.time, type);
     217             :         // Display the actual message in white so it's more readable
     218           0 :         textRenderer.SetCurrentColor(CColor(1.0f, 1.0f, 1.0f, 1.0f));
     219           0 :         textRenderer.Put(0.0f, 0.0f, msg.message.c_str());
     220             : 
     221           0 :         textRenderer.ResetTranslate(savedTranslate);
     222             : 
     223           0 :         textRenderer.Translate(0.0f, height);
     224             :     }
     225             : 
     226           0 :     canvas.DrawText(textRenderer);
     227           0 : }
     228             : 
     229         450 : void CLogger::PushRenderMessage(ELogMethod method, const char* message)
     230             : {
     231         450 :     double now = timer_Time();
     232             : 
     233             :     // Add each message line separately
     234         450 :     const char* pos = message;
     235         450 :     const char* eol;
     236         942 :     while ((eol = strchr(pos, '\n')) != NULL)
     237             :     {
     238          42 :         if (eol != pos)
     239             :         {
     240          40 :             RenderedMessage r = { method, now, std::string(pos, eol) };
     241          40 :             m_RenderMessages.push_back(r);
     242          40 :         }
     243          42 :         pos = eol + 1;
     244             :     }
     245             :     // Add the last line, if we didn't end on a \n
     246         450 :     if (*pos != '\0')
     247             :     {
     248         439 :         RenderedMessage r = { method, now, std::string(pos) };
     249         439 :         m_RenderMessages.push_back(r);
     250         439 :     }
     251         450 : }
     252             : 
     253           0 : void CLogger::CleanupRenderQueue()
     254             : {
     255           0 :     std::lock_guard<std::mutex> lock(m_Mutex);
     256             : 
     257           0 :     if (m_RenderMessages.empty())
     258           0 :         return;
     259             : 
     260           0 :     double now = timer_Time();
     261             : 
     262             :     // Initialise the timer on the first call (since we can't do it in the ctor)
     263           0 :     if (m_RenderLastEraseTime == -1.0)
     264           0 :         m_RenderLastEraseTime = now;
     265             : 
     266             :     // Delete old messages, approximately at the given rate limit (and at most one per frame)
     267           0 :     if (now - m_RenderLastEraseTime > 1.0/RENDER_TIMEOUT_RATE)
     268             :     {
     269           0 :         if (m_RenderMessages[0].time + RENDER_TIMEOUT < now)
     270             :         {
     271           0 :             m_RenderMessages.pop_front();
     272           0 :             m_RenderLastEraseTime = now;
     273             :         }
     274             :     }
     275             : 
     276             :     // If there's still too many then delete the oldest
     277           0 :     if (m_RenderMessages.size() > RENDER_LIMIT)
     278           0 :         m_RenderMessages.erase(m_RenderMessages.begin(), m_RenderMessages.end() - RENDER_LIMIT);
     279           0 : }
     280             : 
     281         161 : CLogger::ScopedReplacement::ScopedReplacement(std::ostream& mainLog, std::ostream& interestingLog,
     282         161 :     const bool useDebugPrintf) :
     283           0 :     m_ThisLogger{mainLog, interestingLog, useDebugPrintf},
     284         161 :     m_OldLogger{std::exchange(g_Logger, &m_ThisLogger)}
     285           0 : {}
     286             : 
     287         161 : CLogger::ScopedReplacement::~ScopedReplacement()
     288             : {
     289         161 :     g_Logger = m_OldLogger;
     290         161 : }
     291             : 
     292             : namespace
     293             : {
     294           0 : std::ofstream OpenLogFile(const wchar_t* filePrefix, const char* logName)
     295             : {
     296           0 :     OsPath path{psLogDir() / (filePrefix + g_UniqueLogPostfix + L".html")};
     297           0 :     debug_printf("%s written to '%s'\n", logName, path.string8().c_str());
     298           0 :     return std::ofstream{OsString(path), std::ofstream::trunc};
     299           0 : }
     300             : }
     301             : 
     302           0 : FileLogger::FileLogger() :
     303           0 :     m_MainLog{OpenLogFile(L"mainlog", "Main log")},
     304           0 :     m_InterestingLog{OpenLogFile(L"interestinglog", "Interesting log")},
     305           0 :     m_ScopedReplacement{m_MainLog, m_InterestingLog, true}
     306           0 : {}
     307             : 
     308         161 : TestLogger::TestLogger() :
     309         161 :     m_ScopedReplacement{m_Stream, blackHoleStream, false}
     310         161 : {}
     311             : 
     312          49 : std::string TestLogger::GetOutput()
     313             : {
     314          49 :     return m_Stream.str();
     315             : }
     316             : 
     317           0 : TestStdoutLogger::TestStdoutLogger() :
     318           0 :     m_ScopedReplacement{std::cout, blackHoleStream, false}
     319           0 : {}

Generated by: LCOV version 1.16