Skip to content

Commit

Permalink
Add CMemoryLogger
Browse files Browse the repository at this point in the history
Logger that collects messages in memory. This is useful to collect the log messages for a particular operation and show them in a user interface when the operation failed. Messages can also be forwarded to a parent logger if it's set, regardless of this logger's filter, so the messages also appear in the console normally.
  • Loading branch information
Robyt3 committed Jan 4, 2025
1 parent 8bb8a17 commit 26b669b
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/base/log.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -549,3 +549,38 @@ void CFutureLogger::OnFilterChange()
pLogger->SetFilter(m_Filter);
}
}

void CMemoryLogger::Log(const CLogMessage *pMessage)
{
if(m_pParentLogger)
{
m_pParentLogger->Log(pMessage);
}
if(m_Filter.Filters(pMessage))
{
return;
}
const CLockScope LockScope(m_MessagesMutex);
m_vMessages.push_back(*pMessage);
}

std::vector<CLogMessage> CMemoryLogger::Lines()
{
const CLockScope LockScope(m_MessagesMutex);
return m_vMessages;
}

std::string CMemoryLogger::ConcatenatedLines()
{
const CLockScope LockScope(m_MessagesMutex);
std::string Result;
for(const CLogMessage &Message : m_vMessages)
{
if(!Result.empty())
{
Result += '\n';
}
Result += Message.m_aLine;
}
return Result;
}
25 changes: 25 additions & 0 deletions src/base/logger.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

#include <atomic>
#include <memory>
#include <string>
#include <vector>

typedef void *IOHANDLE;
Expand Down Expand Up @@ -247,6 +248,30 @@ class CFutureLogger : public ILogger
void OnFilterChange() override;
};

/**
* @ingroup Log
*
* Logger that collects messages in memory. This is useful to collect the log
* messages for a particular operation and show them in a user interface when
* the operation failed. Use only temporarily with @link CLogScope @endlink
* or it will result in excessive memory usage.
*
* Messages are also forwarded to the parent logger if it's set, regardless
* of this logger's filter.
*/
class CMemoryLogger : public ILogger
{
ILogger *m_pParentLogger = nullptr;
std::vector<CLogMessage> m_vMessages GUARDED_BY(m_MessagesMutex);
CLock m_MessagesMutex;

public:
void SetParent(ILogger *pParentLogger) { m_pParentLogger = pParentLogger; }
void Log(const CLogMessage *pMessage) override REQUIRES(!m_MessagesMutex);
std::vector<CLogMessage> Lines() REQUIRES(!m_MessagesMutex);
std::string ConcatenatedLines() REQUIRES(!m_MessagesMutex);
};

/**
* @ingroup Log
*
Expand Down

0 comments on commit 26b669b

Please sign in to comment.