Merge pull request #10504 from Icinga/log-optimization

Small code and performance optimizations in `Log` class
This commit is contained in:
Julian Brost 2025-08-04 10:39:22 +02:00 committed by GitHub
commit 370f96bcd5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 22 additions and 23 deletions

View File

@ -27,6 +27,7 @@ template Log& Log::operator<<(const int&);
template Log& Log::operator<<(const unsigned long&);
template Log& Log::operator<<(const long&);
template Log& Log::operator<<(const double&);
template Log& Log::operator<<(const char*&);
REGISTER_TYPE(Logger);
@ -246,21 +247,25 @@ void Logger::UpdateMinLogSeverity()
Log::Log(LogSeverity severity, String facility, const String& message)
: Log(severity, std::move(facility))
{
if (!m_IsNoOp) {
m_Buffer << message;
}
*this << message;
}
Log::Log(LogSeverity severity, String facility)
: m_Severity(severity), m_Facility(std::move(facility)), m_IsNoOp(severity < Logger::GetMinLogSeverity())
{ }
{
// Only fully initialize the object if it's actually going to be logged.
if (severity >= Logger::GetMinLogSeverity()) {
m_Severity = severity;
m_Facility = std::move(facility);
m_Buffer.emplace();
}
}
/**
* Writes the message to the application's log.
*/
Log::~Log()
{
if (m_IsNoOp) {
if (!m_Buffer) {
return;
}
@ -270,7 +275,7 @@ Log::~Log()
entry.Facility = m_Facility;
{
auto msg (m_Buffer.str());
auto msg (m_Buffer->str());
msg.erase(msg.find_last_not_of("\n") + 1u);
entry.Message = std::move(msg);
@ -315,12 +320,3 @@ Log::~Log()
}
#endif /* _WIN32 */
}
Log& Log::operator<<(const char *val)
{
if (!m_IsNoOp) {
m_Buffer << val;
}
return *this;
}

View File

@ -6,6 +6,7 @@
#include "base/atomic.hpp"
#include "base/i2-base.hpp"
#include "base/logger-ti.hpp"
#include <optional>
#include <set>
#include <sstream>
@ -119,22 +120,23 @@ public:
~Log();
template<typename T>
Log& operator<<(const T& val)
Log& operator<<(T&& val)
{
if (!m_IsNoOp) {
m_Buffer << val;
if (m_Buffer) {
*m_Buffer << std::forward<T>(val);
}
return *this;
}
Log& operator<<(const char *val);
private:
LogSeverity m_Severity;
String m_Facility;
std::ostringstream m_Buffer;
bool m_IsNoOp;
/**
* Stream for incrementally generating the log message. If the message will be discarded as it's level currently
* isn't logged, it will be empty as the stream doesn't need to be initialized in this case.
*/
std::optional<std::ostringstream> m_Buffer;
};
extern template Log& Log::operator<<(const Value&);
@ -146,6 +148,7 @@ extern template Log& Log::operator<<(const int&);
extern template Log& Log::operator<<(const unsigned long&);
extern template Log& Log::operator<<(const long&);
extern template Log& Log::operator<<(const double&);
extern template Log& Log::operator<<(const char*&);
}