diff --git a/icinga-app/icinga.cpp b/icinga-app/icinga.cpp index acae5d544..0c6d058b0 100644 --- a/icinga-app/icinga.cpp +++ b/icinga-app/icinga.cpp @@ -192,9 +192,8 @@ int Main(void) CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc, vm, cmdname, command, autocomplete); } catch (const std::exception& ex) { - std::ostringstream msgbuf; - msgbuf << "Error while parsing command-line options: " << ex.what(); - Log(LogCritical, "icinga-app", msgbuf.str()); + Log(LogCritical, "icinga-app") + << "Error while parsing command-line options: " << ex.what(); return EXIT_FAILURE; } @@ -337,30 +336,26 @@ int Main(void) if (!gr) { if (errno == 0) { - std::ostringstream msgbuf; - msgbuf << "Invalid group specified: " + group; - Log(LogCritical, "cli", msgbuf.str()); + Log(LogCritical, "cli") + << "Invalid group specified: " << group; return EXIT_FAILURE; } else { - std::ostringstream msgbuf; - msgbuf << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "cli", msgbuf.str()); + Log(LogCritical, "cli") + << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; return EXIT_FAILURE; } } if (getgid() != gr->gr_gid) { if (!vm.count("reload-internal") && setgroups(0, NULL) < 0) { - std::ostringstream msgbuf; - msgbuf << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "cli", msgbuf.str()); + Log(LogCritical, "cli") + << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; return EXIT_FAILURE; } if (setgid(gr->gr_gid) < 0) { - std::ostringstream msgbuf; - msgbuf << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "cli", msgbuf.str()); + Log(LogCritical, "cli") + << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; return EXIT_FAILURE; } } @@ -372,14 +367,12 @@ int Main(void) if (!pw) { if (errno == 0) { - std::ostringstream msgbuf; - msgbuf << "Invalid user specified: " + user; - Log(LogCritical, "cli", msgbuf.str()); + Log(LogCritical, "cli") + << "Invalid user specified: " << user; return EXIT_FAILURE; } else { - std::ostringstream msgbuf; - msgbuf << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "cli", msgbuf.str()); + Log(LogCritical, "cli") + << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; return EXIT_FAILURE; } } @@ -387,16 +380,14 @@ int Main(void) // also activate the additional groups the configured user is member of if (getuid() != pw->pw_uid) { if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) { - std::ostringstream msgbuf; - msgbuf << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "cli", msgbuf.str()); + Log(LogCritical, "cli") + << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; return EXIT_FAILURE; } if (setuid(pw->pw_uid) < 0) { - std::ostringstream msgbuf; - msgbuf << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "cli", msgbuf.str()); + Log(LogCritical, "cli") + << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; return EXIT_FAILURE; } } diff --git a/lib/base/application.cpp b/lib/base/application.cpp index acb6d751a..772a71e40 100644 --- a/lib/base/application.cpp +++ b/lib/base/application.cpp @@ -286,11 +286,10 @@ mainloop: if (abs(timeDiff) > 15) { /* We made a significant jump in time. */ - std::ostringstream msgbuf; - msgbuf << "We jumped " - << (timeDiff < 0 ? "forward" : "backward") - << " in time: " << abs(timeDiff) << " seconds"; - Log(LogInformation, "Application", msgbuf.str()); + Log(LogInformation, "Application") + << "We jumped " + << (timeDiff < 0 ? "forward" : "backward") + << " in time: " << abs(timeDiff) << " seconds"; Timer::AdjustTimers(-timeDiff); } @@ -682,7 +681,8 @@ int Application::Run(void) try { UpdatePidFile(GetPidPath()); } catch (const std::exception&) { - Log(LogCritical, "Application", "Cannot update PID file '" + GetPidPath() + "'. Aborting."); + Log(LogCritical, "Application") + << "Cannot update PID file '" << GetPidPath() << "'. Aborting."; return false; } @@ -714,7 +714,8 @@ void Application::UpdatePidFile(const String& filename, pid_t pid) m_PidFile = fopen(filename.CStr(), "w"); if (m_PidFile == NULL) { - Log(LogCritical, "Application", "Could not open PID file '" + filename + "'."); + Log(LogCritical, "Application") + << "Could not open PID file '" << filename << "'."; BOOST_THROW_EXCEPTION(std::runtime_error("Could not open PID file '" + filename + "'")); } @@ -737,9 +738,8 @@ void Application::UpdatePidFile(const String& filename, pid_t pid) } if (ftruncate(fd, 0) < 0) { - std::ostringstream msgbuf; - msgbuf << "ftruncate() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "Application", msgbuf.str()); + Log(LogCritical, "Application") + << "ftruncate() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; BOOST_THROW_EXCEPTION(posix_error() << boost::errinfo_api_function("ftruncate") diff --git a/lib/base/dynamicobject.cpp b/lib/base/dynamicobject.cpp index 7a41cdfde..919ee0599 100644 --- a/lib/base/dynamicobject.cpp +++ b/lib/base/dynamicobject.cpp @@ -239,7 +239,8 @@ Value DynamicObject::InvokeMethod(const String& method, void DynamicObject::DumpObjects(const String& filename, int attributeTypes) { - Log(LogInformation, "DynamicObject", "Dumping program state to file '" + filename + "'"); + Log(LogInformation, "DynamicObject") + << "Dumping program state to file '" << filename << "'"; String tempFilename = filename + ".tmp"; @@ -307,7 +308,8 @@ void DynamicObject::RestoreObject(const String& message, int attributeTypes) ASSERT(!object->IsActive()); #ifdef _DEBUG - Log(LogDebug, "DynamicObject", "Restoring object '" + name + "' of type '" + type + "'."); + Log(LogDebug, "DynamicObject") + << "Restoring object '" << name << "' of type '" << type << "'."; #endif /* _DEBUG */ Dictionary::Ptr update = persistentObject->Get("update"); Deserialize(object, update, false, attributeTypes); @@ -316,7 +318,8 @@ void DynamicObject::RestoreObject(const String& message, int attributeTypes) void DynamicObject::RestoreObjects(const String& filename, int attributeTypes) { - Log(LogInformation, "DynamicObject", "Restoring program state from file '" + filename + "'"); + Log(LogInformation, "DynamicObject") + << "Restoring program state from file '" << filename << "'"; std::fstream fp; fp.open(filename.CStr(), std::ios_base::in); @@ -337,9 +340,8 @@ void DynamicObject::RestoreObjects(const String& filename, int attributeTypes) upq.Join(); - std::ostringstream msgbuf; - msgbuf << "Restored " << restored << " objects"; - Log(LogInformation, "DynamicObject", msgbuf.str()); + Log(LogInformation, "DynamicObject") + << "Restored " << restored << " objects"; } void DynamicObject::StopObjects(void) diff --git a/lib/base/logger.cpp b/lib/base/logger.cpp index 205103199..2cee05d8b 100644 --- a/lib/base/logger.cpp +++ b/lib/base/logger.cpp @@ -77,7 +77,7 @@ std::set Logger::GetLoggers(void) * @param facility The log facility. * @param message The message. */ -void icinga::Log(LogSeverity severity, const String& facility, +void icinga::IcingaLog(LogSeverity severity, const String& facility, const String& message) { LogEntry entry; diff --git a/lib/base/logger.hpp b/lib/base/logger.hpp index d8b0bc162..61ecc5050 100644 --- a/lib/base/logger.hpp +++ b/lib/base/logger.hpp @@ -23,6 +23,7 @@ #include "base/i2-base.hpp" #include "base/logger.thpp" #include +#include namespace icinga { @@ -102,6 +103,39 @@ private: const String& message); }; +I2_BASE_API void IcingaLog(LogSeverity severity, const String& facility, const String& message); + +class Log +{ +public: + inline Log(LogSeverity severity, const String& facility, const String& message) + : m_Severity(severity), m_Facility(facility) + { + m_Buffer << message; + } + + inline Log(LogSeverity severity, const String& facility) + : m_Severity(severity), m_Facility(facility) + { } + + inline ~Log(void) + { + IcingaLog(m_Severity, m_Facility, m_Buffer.str()); + } + + template + Log& operator<<(const T& val) + { + m_Buffer << val; + return *this; + } + +private: + LogSeverity m_Severity; + String m_Facility; + std::ostringstream m_Buffer; +}; + } #endif /* LOGGER_H */ diff --git a/lib/base/process.cpp b/lib/base/process.cpp index 39630e824..5d368f4a7 100644 --- a/lib/base/process.cpp +++ b/lib/base/process.cpp @@ -437,8 +437,8 @@ void Process::Run(const boost::function& callback) m_FD = outReadPipe; m_PID = pi.dwProcessId; - Log(LogNotice, "Process", "Running command " + PrettyPrintArguments(m_Arguments) + - ": PID " + Convert::ToString(m_PID)); + Log(LogNotice, "Process") + << "Running command " << PrettyPrintArguments(m_Arguments) << ": PID " << m_PID; #else /* _WIN32 */ int fds[2]; @@ -549,8 +549,8 @@ void Process::Run(const boost::function& callback) m_PID = m_Process; - Log(LogNotice, "Process", "Running command " + PrettyPrintArguments(m_Arguments) + - ": PID " + Convert::ToString(m_PID)); + Log(LogNotice, "Process") + << "Running command " << PrettyPrintArguments(m_Arguments) <<": PID " << m_PID; // free arguments for (int i = 0; argv[i] != NULL; i++) @@ -599,9 +599,9 @@ bool Process::DoEvents(void) double timeout = m_Result.ExecutionStart + m_Timeout; if (timeout < Utility::GetTime()) { - Log(LogWarning, "Process", "Killing process " + Convert::ToString(m_PID) + - " (" + PrettyPrintArguments(m_Arguments) + ") after timeout of " + - Convert::ToString(m_Timeout) + " seconds"); + Log(LogWarning, "Process") + << "Killing process " << m_PID << " (" << PrettyPrintArguments(m_Arguments) + << ") after timeout of " << m_Timeout << " seconds"; m_OutputStream << ""; #ifdef _WIN32 @@ -649,9 +649,8 @@ bool Process::DoEvents(void) DWORD exitcode; GetExitCodeProcess(m_Process, &exitcode); - Log(LogNotice, "Process", "PID " + Convert::ToString(m_PID) + - " (" + PrettyPrintArguments(m_Arguments) + ") terminated with exit code " + - Convert::ToString(exitcode)); + Log(LogNotice, "Process") + << "PID " << m_PID << " (" << PrettyPrintArguments(m_Arguments) << ") terminated with exit code " << exitcode; #else /* _WIN32 */ int status, exitcode; if (waitpid(m_Process, &status, 0) != m_Process) { @@ -663,12 +662,11 @@ bool Process::DoEvents(void) if (WIFEXITED(status)) { exitcode = WEXITSTATUS(status); - Log(LogNotice, "Process", "PID " + Convert::ToString(m_PID) + - " (" + PrettyPrintArguments(m_Arguments) + ") terminated with exit code " + - Convert::ToString(exitcode)); + Log(LogNotice, "Process") + << "PID " << m_PID << " (" << PrettyPrintArguments(m_Arguments) << ") terminated with exit code " << exitcode; } else if (WIFSIGNALED(status)) { - Log(LogWarning, "Process", "PID " + Convert::ToString(m_PID) + " was terminated by signal " + - Convert::ToString(WTERMSIG(status))); + Log(LogWarning, "Process") + << "PID " << m_PID << " was terminated by signal " << WTERMSIG(status); std::ostringstream outputbuf; outputbuf << ""; diff --git a/lib/base/socket.cpp b/lib/base/socket.cpp index 562ddd9bf..a82a028bb 100644 --- a/lib/base/socket.cpp +++ b/lib/base/socket.cpp @@ -131,17 +131,15 @@ String Socket::GetAddressFromSockaddr(sockaddr *address, socklen_t len) if (getnameinfo(address, len, host, sizeof(host), service, sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV) < 0) { #ifndef _WIN32 - std::ostringstream msgbuf; - msgbuf << "getnameinfo() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "getnameinfo() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("getnameinfo") << boost::errinfo_errno(errno)); #else /* _WIN32 */ - std::ostringstream msgbuf; - msgbuf << "getnameinfo() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "getnameinfo() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("getnameinfo") @@ -168,17 +166,15 @@ String Socket::GetClientAddress(void) if (getsockname(GetFD(), (sockaddr *)&sin, &len) < 0) { #ifndef _WIN32 - std::ostringstream msgbuf; - msgbuf << "getsockname() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "getsockname() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("getsockname") << boost::errinfo_errno(errno)); #else /* _WIN32 */ - std::ostringstream msgbuf; - msgbuf << "getsockname() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "getsockname() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("getsockname") @@ -210,17 +206,15 @@ String Socket::GetPeerAddress(void) if (getpeername(GetFD(), (sockaddr *)&sin, &len) < 0) { #ifndef _WIN32 - std::ostringstream msgbuf; - msgbuf << "getpeername() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "getpeername() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("getpeername") << boost::errinfo_errno(errno)); #else /* _WIN32 */ - std::ostringstream msgbuf; - msgbuf << "getpeername() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "getpeername() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("getpeername") @@ -245,17 +239,15 @@ void Socket::Listen(void) { if (listen(GetFD(), SOMAXCONN) < 0) { #ifndef _WIN32 - std::ostringstream msgbuf; - msgbuf << "listen() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "listen() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("listen") << boost::errinfo_errno(errno)); #else /* _WIN32 */ - std::ostringstream msgbuf; - msgbuf << "listen() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "listen() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("listen") @@ -273,17 +265,15 @@ size_t Socket::Write(const void *buffer, size_t count) if (rc < 0) { #ifndef _WIN32 - std::ostringstream msgbuf; - msgbuf << "send() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "send() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("send") << boost::errinfo_errno(errno)); #else /* _WIN32 */ - std::ostringstream msgbuf; - msgbuf << "send() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "send() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("send") @@ -303,17 +293,15 @@ size_t Socket::Read(void *buffer, size_t count) if (rc < 0) { #ifndef _WIN32 - std::ostringstream msgbuf; - msgbuf << "recv() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "recv() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("recv") << boost::errinfo_errno(errno)); #else /* _WIN32 */ - std::ostringstream msgbuf; - msgbuf << "recv() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "recv() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("recv") @@ -337,17 +325,15 @@ Socket::Ptr Socket::Accept(void) if (fd < 0) { #ifndef _WIN32 - std::ostringstream msgbuf; - msgbuf << "accept() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "accept() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("accept") << boost::errinfo_errno(errno)); #else /* _WIN32 */ - std::ostringstream msgbuf; - msgbuf << "accept() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "accept() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("accept") @@ -379,9 +365,8 @@ bool Socket::Poll(bool read, bool write) rc = select(GetFD() + 1, &readfds, &writefds, &exceptfds, NULL); if (rc < 0) { - std::ostringstream msgbuf; - msgbuf << "select() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "select() failed with error code " << WSAGetLastError() << ", \"" << Utility::FormatErrorNumber(WSAGetLastError()) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("select") @@ -396,9 +381,8 @@ bool Socket::Poll(bool read, bool write) rc = poll(&pfd, 1, -1); if (rc < 0) { - std::ostringstream msgbuf; - msgbuf << "poll() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "Socket", msgbuf.str()); + Log(LogCritical, "Socket") + << "poll() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("poll") diff --git a/lib/base/tcpsocket.cpp b/lib/base/tcpsocket.cpp index 5bdcd991b..b3bfbe52a 100644 --- a/lib/base/tcpsocket.cpp +++ b/lib/base/tcpsocket.cpp @@ -62,9 +62,8 @@ void TcpSocket::Bind(const String& node, const String& service, int family) service.CStr(), &hints, &result); if (rc != 0) { - std::ostringstream msgbuf; - msgbuf << "getaddrinfo() failed with error code " << rc << ", \"" << gai_strerror(rc) << "\""; - Log(LogCritical, "TcpSocket", msgbuf.str()); + Log(LogCritical, "TcpSocket") + << "getaddrinfo() failed with error code " << rc << ", \"" << gai_strerror(rc) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("getaddrinfo") @@ -118,9 +117,8 @@ void TcpSocket::Bind(const String& node, const String& service, int family) freeaddrinfo(result); if (GetFD() == INVALID_SOCKET) { - std::ostringstream msgbuf; - msgbuf << "Invalid socket: " << Utility::FormatErrorNumber(error); - Log(LogCritical, "TcpSocket", msgbuf.str()); + Log(LogCritical, "TcpSocket") + << "Invalid socket: " << Utility::FormatErrorNumber(error); #ifndef _WIN32 BOOST_THROW_EXCEPTION(socket_error() @@ -155,9 +153,8 @@ void TcpSocket::Connect(const String& node, const String& service) int rc = getaddrinfo(node.CStr(), service.CStr(), &hints, &result); if (rc != 0) { - std::ostringstream msgbuf; - msgbuf << "getaddrinfo() failed with error code " << rc << ", \"" << gai_strerror(rc) << "\""; - Log(LogCritical, "TcpSocket", msgbuf.str()); + Log(LogCritical, "TcpSocket") + << "getaddrinfo() failed with error code " << rc << ", \"" << gai_strerror(rc) << "\""; BOOST_THROW_EXCEPTION(socket_error() << boost::errinfo_api_function("getaddrinfo") @@ -203,9 +200,8 @@ void TcpSocket::Connect(const String& node, const String& service) freeaddrinfo(result); if (GetFD() == INVALID_SOCKET) { - std::ostringstream msgbuf; - msgbuf << "Invalid socket: " << Utility::FormatErrorNumber(error); - Log(LogCritical, "TcpSocket", msgbuf.str()); + Log(LogCritical, "TcpSocket") + << "Invalid socket: " << Utility::FormatErrorNumber(error); #ifndef _WIN32 BOOST_THROW_EXCEPTION(socket_error() diff --git a/lib/base/threadpool.cpp b/lib/base/threadpool.cpp index 77fb7d35c..d35bf69f4 100644 --- a/lib/base/threadpool.cpp +++ b/lib/base/threadpool.cpp @@ -133,11 +133,9 @@ void ThreadPool::WorkerThread::ThreadProc(Queue& queue) if (wi.Callback) wi.Callback(); } catch (const std::exception& ex) { - std::ostringstream msgbuf; - msgbuf << "Exception thrown in event handler: " << std::endl - << DiagnosticInformation(ex); - - Log(LogCritical, "ThreadPool", msgbuf.str()); + Log(LogCritical, "ThreadPool") + << "Exception thrown in event handler:\n" + << DiagnosticInformation(ex); } catch (...) { Log(LogCritical, "ThreadPool", "Exception of unknown type thrown in event handler."); } @@ -172,14 +170,12 @@ void ThreadPool::WorkerThread::ThreadProc(Queue& queue) int divctx = usage_end.ru_nivcsw - usage_start.ru_nivcsw; # endif /* RUSAGE_THREAD */ if (et - st > 0.5) { - std::ostringstream msgbuf; + Log(LogWarning, "ThreadPool") # ifdef RUSAGE_THREAD - msgbuf << "Event call took user:" << duser << "s, system:" << dsys << "s, wait:" << dwait << "s, minor_faults:" << dminfaults << ", major_faults:" << dmajfaults << ", voluntary_csw:" << dvctx << ", involuntary_csw:" << divctx; + << "Event call took user:" << duser << "s, system:" << dsys << "s, wait:" << dwait << "s, minor_faults:" << dminfaults << ", major_faults:" << dmajfaults << ", voluntary_csw:" << dvctx << ", involuntary_csw:" << divctx; # else - msgbuf << "Event call took " << (et - st) << "s"; + << "Event call took " << (et - st) << "s"; # endif /* RUSAGE_THREAD */ - - Log(LogWarning, "ThreadPool", msgbuf.str()); } #endif /* _DEBUG */ } @@ -293,9 +289,8 @@ void ThreadPool::ManagerThreadProc(void) tthreads = m_MaxThreads / (sizeof(m_Queues) / sizeof(m_Queues[0])) - alive; if (tthreads != 0) { - std::ostringstream msgbuf; - msgbuf << "Thread pool; current: " << alive << "; adjustment: " << tthreads; - Log(LogNotice, "ThreadPool", msgbuf.str()); + Log(LogNotice, "ThreadPool") + << "Thread pool; current: " << alive << "; adjustment: " << tthreads; } for (int i = 0; i < -tthreads; i++) @@ -320,12 +315,11 @@ void ThreadPool::ManagerThreadProc(void) if (lastStats < now - 15) { lastStats = now; - std::ostringstream msgbuf; - msgbuf << "Pool #" << m_ID << ": Pending tasks: " << total_pending << "; Average latency: " - << (long)(total_avg_latency * 1000 / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "ms" - << "; Threads: " << total_alive - << "; Pool utilization: " << (total_utilization / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "%"; - Log(LogNotice, "ThreadPool", msgbuf.str()); + Log(LogNotice, "ThreadPool") + << "Pool #" << m_ID << ": Pending tasks: " << total_pending << "; Average latency: " + << (long)(total_avg_latency * 1000 / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "ms" + << "; Threads: " << total_alive + << "; Pool utilization: " << (total_utilization / (sizeof(m_Queues) / sizeof(m_Queues[0]))) << "%"; } } } diff --git a/lib/base/tlsutility.cpp b/lib/base/tlsutility.cpp index 963de5536..582383704 100644 --- a/lib/base/tlsutility.cpp +++ b/lib/base/tlsutility.cpp @@ -86,8 +86,8 @@ shared_ptr MakeSSLContext(const String& pubkey, const String& privkey, SSL_CTX_set_mode(sslContext.get(), SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); if (!SSL_CTX_use_certificate_chain_file(sslContext.get(), pubkey.CStr())) { - msgbuf << "Error with public key file '" << pubkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error with public key file '" << pubkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() << boost::errinfo_api_function("SSL_CTX_use_certificate_chain_file") << errinfo_openssl_error(ERR_peek_error()) @@ -95,8 +95,8 @@ shared_ptr MakeSSLContext(const String& pubkey, const String& privkey, } if (!SSL_CTX_use_PrivateKey_file(sslContext.get(), privkey.CStr(), SSL_FILETYPE_PEM)) { - msgbuf << "Error with private key file '" << privkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error with private key file '" << privkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() << boost::errinfo_api_function("SSL_CTX_use_PrivateKey_file") << errinfo_openssl_error(ERR_peek_error()) @@ -104,8 +104,8 @@ shared_ptr MakeSSLContext(const String& pubkey, const String& privkey, } if (!SSL_CTX_check_private_key(sslContext.get())) { - msgbuf << "Error checking private key '" << privkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error checking private key '" << privkey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() << boost::errinfo_api_function("SSL_CTX_check_private_key") << errinfo_openssl_error(ERR_peek_error())); @@ -113,8 +113,8 @@ shared_ptr MakeSSLContext(const String& pubkey, const String& privkey, if (!cakey.IsEmpty()) { if (!SSL_CTX_load_verify_locations(sslContext.get(), cakey.CStr(), NULL)) { - msgbuf << "Error loading and verifying locations in ca key file '" << cakey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error loading and verifying locations in ca key file '" << cakey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() << boost::errinfo_api_function("SSL_CTX_load_verify_locations") << errinfo_openssl_error(ERR_peek_error()) @@ -125,8 +125,8 @@ shared_ptr MakeSSLContext(const String& pubkey, const String& privkey, cert_names = SSL_load_client_CA_file(cakey.CStr()); if (cert_names == NULL) { - msgbuf << "Error loading client ca key file '" << cakey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error loading client ca key file '" << cakey << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() << boost::errinfo_api_function("SSL_load_client_CA_file") << errinfo_openssl_error(ERR_peek_error()) @@ -147,7 +147,6 @@ shared_ptr MakeSSLContext(const String& pubkey, const String& privkey, */ void AddCRLToSSLContext(const shared_ptr& context, const String& crlPath) { - std::ostringstream msgbuf; char errbuf[120]; X509_STORE *x509_store = SSL_CTX_get_cert_store(context.get()); @@ -155,20 +154,20 @@ void AddCRLToSSLContext(const shared_ptr& context, const String& crlPat lookup = X509_STORE_add_lookup(x509_store, X509_LOOKUP_file()); if (!lookup) { - msgbuf << "Error adding X509 store lookup: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error adding X509 store lookup: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() - << boost::errinfo_api_function("X509_STORE_add_lookup") - << errinfo_openssl_error(ERR_peek_error())); + << boost::errinfo_api_function("X509_STORE_add_lookup") + << errinfo_openssl_error(ERR_peek_error())); } if (X509_LOOKUP_load_file(lookup, crlPath.CStr(), X509_FILETYPE_PEM) != 0) { - msgbuf << "Error loading crl file '" << crlPath << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error loading crl file '" << crlPath << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() - << boost::errinfo_api_function("X509_LOOKUP_load_file") - << errinfo_openssl_error(ERR_peek_error()) - << boost::errinfo_file_name(crlPath)); + << boost::errinfo_api_function("X509_LOOKUP_load_file") + << errinfo_openssl_error(ERR_peek_error()) + << boost::errinfo_file_name(crlPath)); } X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new(); @@ -185,7 +184,6 @@ void AddCRLToSSLContext(const shared_ptr& context, const String& crlPat */ String GetCertificateCN(const shared_ptr& certificate) { - std::ostringstream msgbuf; char errbuf[120]; char buffer[256]; @@ -193,8 +191,8 @@ String GetCertificateCN(const shared_ptr& certificate) NID_commonName, buffer, sizeof(buffer)); if (rc == -1) { - msgbuf << "Error with x509 NAME getting text by NID: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error with x509 NAME getting text by NID: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() << boost::errinfo_api_function("X509_NAME_get_text_by_NID") << errinfo_openssl_error(ERR_peek_error())); @@ -211,22 +209,21 @@ String GetCertificateCN(const shared_ptr& certificate) */ shared_ptr GetX509Certificate(const String& pemfile) { - std::ostringstream msgbuf; char errbuf[120]; X509 *cert; BIO *fpcert = BIO_new(BIO_s_file()); if (fpcert == NULL) { - msgbuf << "Error creating new BIO: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error creating new BIO: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() << boost::errinfo_api_function("BIO_new") << errinfo_openssl_error(ERR_peek_error())); } if (BIO_read_filename(fpcert, pemfile.CStr()) < 0) { - msgbuf << "Error reading pem file '" << pemfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error reading pem file '" << pemfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() << boost::errinfo_api_function("BIO_read_filename") << errinfo_openssl_error(ERR_peek_error()) @@ -235,8 +232,8 @@ shared_ptr GetX509Certificate(const String& pemfile) cert = PEM_read_bio_X509_AUX(fpcert, NULL, NULL, NULL); if (cert == NULL) { - msgbuf << "Error on bio X509 AUX reading pem file '" << pemfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error on bio X509 AUX reading pem file '" << pemfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() << boost::errinfo_api_function("PEM_read_bio_X509_AUX") << errinfo_openssl_error(ERR_peek_error()) @@ -254,7 +251,8 @@ int MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile, RSA *rsa = RSA_generate_key(4096, RSA_F4, NULL, NULL); - Log(LogInformation, "base", "Writing private key to '" + keyfile + "'."); + Log(LogInformation, "base") + << "Writing private key to '" << keyfile << "'."; BIO *bio = BIO_new_file(const_cast(keyfile.CStr()), "w"); PEM_write_bio_RSAPrivateKey(bio, rsa, NULL, NULL, 0, NULL, NULL); @@ -275,7 +273,8 @@ int MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile, X509_NAME_free(subject); - Log(LogInformation, "base", "Writing X509 certificate to '" + certfile + "'."); + Log(LogInformation, "base") + << "Writing X509 certificate to '" << certfile << "'."; bio = BIO_new(BIO_s_file()); BIO_write_filename(bio, const_cast(certfile.CStr())); @@ -297,7 +296,8 @@ int MakeX509CSR(const String& cn, const String& keyfile, const String& csrfile, X509_REQ_sign(req, key, EVP_sha1()); - Log(LogInformation, "base", "Writing certificate signing request to '" + csrfile + "'."); + Log(LogInformation, "base") + << "Writing certificate signing request to '" << csrfile << "'."; bio = BIO_new(BIO_s_file()); BIO_write_filename(bio, const_cast(csrfile.CStr())); @@ -348,7 +348,6 @@ String GetIcingaCADir(void) shared_ptr CreateCertIcingaCA(EVP_PKEY *pubkey, X509_NAME *subject) { - std::stringstream msgbuf; char errbuf[120]; String cadir = GetIcingaCADir(); @@ -360,16 +359,16 @@ shared_ptr CreateCertIcingaCA(EVP_PKEY *pubkey, X509_NAME *subject) BIO *cakeybio = BIO_new_file(const_cast(cakeyfile.CStr()), "r"); if (!cakeybio) { - msgbuf << "Could not open CA key file '" << cakeyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Could not open CA key file '" << cakeyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; return shared_ptr(); } rsa = PEM_read_bio_RSAPrivateKey(cakeybio, NULL, NULL, NULL); if (!rsa) { - msgbuf << "Could not read RSA key from CA key file '" << cakeyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Could not read RSA key from CA key file '" << cakeyfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; return shared_ptr(); } @@ -415,33 +414,32 @@ String PBKDF2_SHA1(const String& password, const String& salt, int iterations) String SHA256(const String& s) { - std::ostringstream msgbuf; char errbuf[120]; SHA256_CTX context; unsigned char digest[SHA256_DIGEST_LENGTH]; if (!SHA256_Init(&context)) { - msgbuf << "Error on SHA256 Init: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error on SHA256 Init: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() - << boost::errinfo_api_function("SHA256_Init") - << errinfo_openssl_error(ERR_peek_error())); + << boost::errinfo_api_function("SHA256_Init") + << errinfo_openssl_error(ERR_peek_error())); } if (!SHA256_Update(&context, (unsigned char*)s.CStr(), s.GetLength())) { - msgbuf << "Error on SHA256 Update: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error on SHA256 Update: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() - << boost::errinfo_api_function("SHA256_Update") - << errinfo_openssl_error(ERR_peek_error())); + << boost::errinfo_api_function("SHA256_Update") + << errinfo_openssl_error(ERR_peek_error())); } if (!SHA256_Final(digest, &context)) { - msgbuf << "Error on SHA256 Final: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Error on SHA256 Final: " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; BOOST_THROW_EXCEPTION(openssl_error() - << boost::errinfo_api_function("SHA256_Final") - << errinfo_openssl_error(ERR_peek_error())); + << boost::errinfo_api_function("SHA256_Final") + << errinfo_openssl_error(ERR_peek_error())); } char output[SHA256_DIGEST_LENGTH*2+1]; diff --git a/lib/base/utility.cpp b/lib/base/utility.cpp index b6b86ad37..a7ebcb8bc 100644 --- a/lib/base/utility.cpp +++ b/lib/base/utility.cpp @@ -304,7 +304,8 @@ Utility::LoadExtensionLibrary(const String& library) path = "lib" + library + ".so"; #endif /* _WIN32 */ - Log(LogInformation, "Utility", "Loading library '" + path + "'"); + Log(LogInformation, "Utility") + << "Loading library '" << path << "'"; #ifdef _WIN32 HMODULE hModule = LoadLibrary(path.CStr()); diff --git a/lib/base/workqueue.cpp b/lib/base/workqueue.cpp index 17f05811e..39ca0cdbc 100644 --- a/lib/base/workqueue.cpp +++ b/lib/base/workqueue.cpp @@ -124,7 +124,8 @@ void WorkQueue::StatusTimerHandler(void) { boost::mutex::scoped_lock lock(m_Mutex); - Log(LogNotice, "WorkQueue", "#" + Convert::ToString(m_ID) + " items: " + Convert::ToString(m_Items.size())); + Log(LogNotice, "WorkQueue") + << "#" << m_ID << " items: " << m_Items.size(); } void WorkQueue::WorkerThreadProc(void) diff --git a/lib/cli/agentlistcommand.cpp b/lib/cli/agentlistcommand.cpp index 132472aa4..e9647e6e0 100644 --- a/lib/cli/agentlistcommand.cpp +++ b/lib/cli/agentlistcommand.cpp @@ -50,7 +50,8 @@ String AgentListCommand::GetShortDescription(void) const int AgentListCommand::Run(const boost::program_options::variables_map& vm, const std::vector& ap) const { if (!ap.empty()) { - Log(LogWarning, "cli", "Ignoring parameters: " + boost::algorithm::join(ap, " ")); + Log(LogWarning, "cli") + << "Ignoring parameters: " << boost::algorithm::join(ap, " "); } return 0; diff --git a/lib/cli/agentsetupcommand.cpp b/lib/cli/agentsetupcommand.cpp index d86f7a02a..035e0698d 100644 --- a/lib/cli/agentsetupcommand.cpp +++ b/lib/cli/agentsetupcommand.cpp @@ -59,7 +59,8 @@ void AgentSetupCommand::InitParameters(boost::program_options::options_descripti int AgentSetupCommand::Run(const boost::program_options::variables_map& vm, const std::vector& ap) const { if (!ap.empty()) { - Log(LogWarning, "cli", "Ignoring parameters: " + boost::algorithm::join(ap, " ")); + Log(LogWarning, "cli") + << "Ignoring parameters: " << boost::algorithm::join(ap, " "); } return 0; diff --git a/lib/cli/agentupdateconfigcommand.cpp b/lib/cli/agentupdateconfigcommand.cpp index df2828cf9..829b74eb4 100644 --- a/lib/cli/agentupdateconfigcommand.cpp +++ b/lib/cli/agentupdateconfigcommand.cpp @@ -50,7 +50,8 @@ String AgentUpdateConfigCommand::GetShortDescription(void) const int AgentUpdateConfigCommand::Run(const boost::program_options::variables_map& vm, const std::vector& ap) const { if (!ap.empty()) { - Log(LogWarning, "cli", "Ignoring parameters: " + boost::algorithm::join(ap, " ")); + Log(LogWarning, "cli") + << "Ignoring parameters: " << boost::algorithm::join(ap, " "); } return 0; diff --git a/lib/cli/agentwizardcommand.cpp b/lib/cli/agentwizardcommand.cpp index 3e42ddcc1..3f900bff0 100644 --- a/lib/cli/agentwizardcommand.cpp +++ b/lib/cli/agentwizardcommand.cpp @@ -50,7 +50,8 @@ String AgentWizardCommand::GetShortDescription(void) const int AgentWizardCommand::Run(const boost::program_options::variables_map& vm, const std::vector& ap) const { if (!ap.empty()) { - Log(LogWarning, "cli", "Ignoring parameters: " + boost::algorithm::join(ap, " ")); + Log(LogWarning, "cli") + << "Ignoring parameters: " << boost::algorithm::join(ap, " "); } return 0; diff --git a/lib/cli/daemoncommand.cpp b/lib/cli/daemoncommand.cpp index 09841a860..df9bfe817 100644 --- a/lib/cli/daemoncommand.cpp +++ b/lib/cli/daemoncommand.cpp @@ -46,7 +46,8 @@ REGISTER_CLICOMMAND("daemon", DaemonCommand); static String LoadAppType(const String& typeSpec) { - Log(LogInformation, "cli", "Loading application type: " + typeSpec); + Log(LogInformation, "cli") + << "Loading application type: " << typeSpec; String::SizeType index = typeSpec.FindFirstOf('/'); @@ -141,7 +142,8 @@ static bool LoadConfigFiles(const boost::program_options::variables_map& vm, con else severity = LogCritical; - Log(severity, "config", Convert::ToString(errors) + " errors, " + Convert::ToString(warnings) + " warnings."); + Log(severity, "config") + << errors << " errors, " << warnings << " warnings."; } if (!result) @@ -183,9 +185,8 @@ static bool Daemonize(void) Log(LogCritical, "cli", "The daemon could not be started. See log output for details."); exit(EXIT_FAILURE); } else if (ret == -1) { - std::ostringstream msgbuf; - msgbuf << "waitpid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "cli", msgbuf.str()); + Log(LogCritical, "cli") + << "waitpid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; exit(EXIT_FAILURE); } @@ -313,14 +314,16 @@ int DaemonCommand::Run(const po::variables_map& vm, const std::vector 0) { - Log(LogCritical, "cli", "Another instance of Icinga already running with PID " + Convert::ToString(runningpid)); + Log(LogCritical, "cli") + << "Another instance of Icinga already running with PID " << runningpid; return EXIT_FAILURE; } } @@ -335,7 +338,8 @@ int DaemonCommand::Run(const po::variables_map& vm, const std::vector(); - Log(LogInformation, "cli", "Terminating previous instance of Icinga (PID " + Convert::ToString(parentpid) + ")"); + Log(LogInformation, "cli") + << "Terminating previous instance of Icinga (PID " << parentpid << ")"; TerminateAndWaitForEnd(parentpid); Log(LogInformation, "cli", "Previous instance has ended, taking over now."); } diff --git a/lib/cli/featuredisablecommand.cpp b/lib/cli/featuredisablecommand.cpp index ceb99bbd7..6dbf231b8 100644 --- a/lib/cli/featuredisablecommand.cpp +++ b/lib/cli/featuredisablecommand.cpp @@ -69,7 +69,8 @@ int FeatureDisableCommand::Run(const boost::program_options::variables_map& vm, } if (!Utility::PathExists(features_enabled_dir) ) { - Log(LogCritical, "cli", "Cannot disable features. Path '" + features_enabled_dir + "' does not exist."); + Log(LogCritical, "cli") + << "Cannot disable features. Path '" << features_enabled_dir << "' does not exist."; return 0; } @@ -79,14 +80,16 @@ int FeatureDisableCommand::Run(const boost::program_options::variables_map& vm, String target = features_enabled_dir + "/" + feature + ".conf"; if (!Utility::PathExists(target) ) { - Log(LogCritical, "cli", "Cannot disable feature '" + feature + "'. Target file '" + target + "' does not exist."); + Log(LogCritical, "cli") + << "Cannot disable feature '" << feature << "'. Target file '" << target << "' does not exist."; errors.push_back(feature); continue; } if (unlink(target.CStr()) < 0) { - Log(LogCritical, "cli", "Cannot disable feature '" + feature + "'. Unlinking target file '" + target + - "' failed with error code " + Convert::ToString(errno) + ", \"" + Utility::FormatErrorNumber(errno) + "\"."); + Log(LogCritical, "cli") + << "Cannot disable feature '" << feature << "'. Unlinking target file '" << target + << "' failed with error code " << errno << ", \"" + Utility::FormatErrorNumber(errno) << "\"."; errors.push_back(feature); continue; } @@ -96,7 +99,8 @@ int FeatureDisableCommand::Run(const boost::program_options::variables_map& vm, } if (!errors.empty()) { - Log(LogCritical, "cli", "Cannot disable feature(s): " + boost::algorithm::join(errors, " ")); + Log(LogCritical, "cli") + << "Cannot disable feature(s): " << boost::algorithm::join(errors, " "); errors.clear(); return 1; } diff --git a/lib/cli/featureenablecommand.cpp b/lib/cli/featureenablecommand.cpp index fdaa3f54f..ab790d960 100644 --- a/lib/cli/featureenablecommand.cpp +++ b/lib/cli/featureenablecommand.cpp @@ -65,12 +65,14 @@ int FeatureEnableCommand::Run(const boost::program_options::variables_map& vm, c } if (!Utility::PathExists(features_available_dir) ) { - Log(LogCritical, "cli", "Cannot parse available features. Path '" + features_available_dir + "' does not exist."); + Log(LogCritical, "cli") + << "Cannot parse available features. Path '" << features_available_dir << "' does not exist."; return 0; } if (!Utility::PathExists(features_enabled_dir) ) { - Log(LogCritical, "cli", "Cannot enable features. Path '" + features_enabled_dir + "' does not exist."); + Log(LogCritical, "cli") + << "Cannot enable features. Path '" << features_enabled_dir << "' does not exist."; return 0; } @@ -80,7 +82,8 @@ int FeatureEnableCommand::Run(const boost::program_options::variables_map& vm, c String source = features_available_dir + "/" + feature + ".conf"; if (!Utility::PathExists(source) ) { - Log(LogCritical, "cli", "Cannot enable feature '" + feature + "'. Source file '" + source + "' does not exist."); + Log(LogCritical, "cli") + << "Cannot enable feature '" << feature << "'. Source file '" << source + "' does not exist."; errors.push_back(feature); continue; } @@ -88,14 +91,16 @@ int FeatureEnableCommand::Run(const boost::program_options::variables_map& vm, c String target = features_enabled_dir + "/" + feature + ".conf"; if (Utility::PathExists(target) ) { - Log(LogWarning, "cli", "Feature '" + feature + "' already enabled."); + Log(LogWarning, "cli") + << "Feature '" << feature << "' already enabled."; continue; } #ifndef _WIN32 if (symlink(source.CStr(), target.CStr()) < 0) { - Log(LogCritical, "cli", "Cannot enable feature '" + feature + "'. Linking source '" + source + "' to target file '" + target + - "' failed with error code " + Convert::ToString(errno) + ", \"" + Utility::FormatErrorNumber(errno) + "\"."); + Log(LogCritical, "cli") + << "Cannot enable feature '" << feature << "'. Linking source '" << source << "' to target file '" << target + << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"."; errors.push_back(feature); continue; } @@ -103,7 +108,8 @@ int FeatureEnableCommand::Run(const boost::program_options::variables_map& vm, c std::ofstream fp; fp.open(target.CStr()); if (!fp) { - Log(LogCritical, "cli", "Cannot enable feature '" + feature + "'. Failed to open file '" + target + "'."); + Log(LogCritical, "cli") + << "Cannot enable feature '" << feature << "'. Failed to open file '" << target << "'."; errors.push_back(feature); continue; } @@ -116,7 +122,8 @@ int FeatureEnableCommand::Run(const boost::program_options::variables_map& vm, c } if (!errors.empty()) { - Log(LogCritical, "cli", "Cannot enable feature(s): " + boost::algorithm::join(errors, " ")); + Log(LogCritical, "cli") + << "Cannot enable feature(s): " << boost::algorithm::join(errors, " "); errors.clear(); return 1; } diff --git a/lib/cli/featurelistcommand.cpp b/lib/cli/featurelistcommand.cpp index 58e651eab..03708a9ae 100644 --- a/lib/cli/featurelistcommand.cpp +++ b/lib/cli/featurelistcommand.cpp @@ -50,7 +50,8 @@ String FeatureListCommand::GetShortDescription(void) const int FeatureListCommand::Run(const boost::program_options::variables_map& vm, const std::vector& ap) const { if (!ap.empty()) { - Log(LogWarning, "cli", "Ignoring parameters: " + boost::algorithm::join(ap, " ")); + Log(LogWarning, "cli") + << "Ignoring parameters: " << boost::algorithm::join(ap, " "); } std::vector available_features; diff --git a/lib/cli/featureutility.cpp b/lib/cli/featureutility.cpp index dcb689b4c..10bd89110 100644 --- a/lib/cli/featureutility.cpp +++ b/lib/cli/featureutility.cpp @@ -81,7 +81,8 @@ bool FeatureUtility::GetFeatures(FeatureType ftype, std::vector& feature if (!Utility::Glob(path + "/*.conf", boost::bind(&FeatureUtility::CollectFeatures, _1, boost::ref(features)), GlobFile)) { - Log(LogCritical, "cli", "Cannot access path '" + path + "'."); + Log(LogCritical, "cli") + << "Cannot access path '" << path << "'."; return false; } } @@ -94,6 +95,7 @@ void FeatureUtility::CollectFeatures(const String& feature_file, std::vector& ap) const { if (!ap.empty()) { - Log(LogWarning, "cli", "Ignoring parameters: " + boost::algorithm::join(ap, " ")); + Log(LogWarning, "cli") + << "Ignoring parameters: " << boost::algorithm::join(ap, " "); } String objectfile = Application::GetObjectsPath(); if (!Utility::PathExists(objectfile)) { - Log(LogCritical, "cli", "Cannot parse objects file '" + Application::GetObjectsPath() + "'."); + Log(LogCritical, "cli") + << "Cannot open objects file '" << Application::GetObjectsPath() << "'."; Log(LogCritical, "cli", "Run 'icinga2 daemon -C' to validate config and generate the cache file."); return 1; } @@ -112,7 +114,8 @@ int ObjectListCommand::Run(const boost::program_options::variables_map& vm, cons std::cout << "\n"; } - Log(LogNotice, "cli", "Parsed " + Convert::ToString(objects_count) + " objects."); + Log(LogNotice, "cli") + << "Parsed " << objects_count << " objects."; return 0; } diff --git a/lib/cli/pkinewcacommand.cpp b/lib/cli/pkinewcacommand.cpp index c7a106046..4277d6c92 100644 --- a/lib/cli/pkinewcacommand.cpp +++ b/lib/cli/pkinewcacommand.cpp @@ -48,12 +48,14 @@ int PKINewCACommand::Run(const boost::program_options::variables_map& vm, const String cadir = Application::GetLocalStateDir() + "/lib/icinga2/ca"; if (Utility::PathExists(cadir)) { - Log(LogCritical, "base", "CA directory '" + cadir + "' already exists."); + Log(LogCritical, "base") + << "CA directory '" << cadir << "' already exists."; return 1; } if (!Utility::MkDirP(cadir, 0700)) { - Log(LogCritical, "base", "Could not create CA directory '" + cadir + "'."); + Log(LogCritical, "base") + << "Could not create CA directory '" << cadir << "'."; return 1; } @@ -61,7 +63,8 @@ int PKINewCACommand::Run(const boost::program_options::variables_map& vm, const String serialpath = cadir + "/serial.txt"; - Log(LogInformation, "cli", "Initializing serial file in '" + serialpath + "'."); + Log(LogInformation, "cli") + << "Initializing serial file in '" << serialpath << "'."; std::ofstream fp; fp.open(serialpath.CStr()); diff --git a/lib/cli/pkirequestcommand.cpp b/lib/cli/pkirequestcommand.cpp index 2ed8baeb1..c8aa02e9e 100644 --- a/lib/cli/pkirequestcommand.cpp +++ b/lib/cli/pkirequestcommand.cpp @@ -155,7 +155,8 @@ int PKIRequestCommand::Run(const boost::program_options::variables_map& vm, cons fpcert.open(certfile.CStr()); if (!fpcert) { - Log(LogCritical, "cli", "Could not open certificate file '" + certfile + "' for writing."); + Log(LogCritical, "cli") + << "Could not open certificate file '" << certfile << "' for writing."; return 1; } @@ -166,7 +167,8 @@ int PKIRequestCommand::Run(const boost::program_options::variables_map& vm, cons fpca.open(cafile.CStr()); if (!fpcert) { - Log(LogCritical, "cli", "Could not open CA certificate file '" + cafile + "' for writing."); + Log(LogCritical, "cli") + << "Could not open CA certificate file '" << cafile << "' for writing."; return 1; } diff --git a/lib/cli/pkisigncsrcommand.cpp b/lib/cli/pkisigncsrcommand.cpp index 5b7ce8488..41ff0ed33 100644 --- a/lib/cli/pkisigncsrcommand.cpp +++ b/lib/cli/pkisigncsrcommand.cpp @@ -83,8 +83,8 @@ int PKISignCSRCommand::Run(const boost::program_options::variables_map& vm, cons X509_REQ *req = PEM_read_bio_X509_REQ(csrbio, NULL, NULL, NULL); if (!req) { - msgbuf << "Could not read X509 certificate request from '" + csrfile + "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; - Log(LogCritical, "SSL", msgbuf.str()); + Log(LogCritical, "SSL") + << "Could not read X509 certificate request from '" << csrfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\""; return 1; } @@ -100,7 +100,8 @@ int PKISignCSRCommand::Run(const boost::program_options::variables_map& vm, cons fpcert.open(certfile.CStr()); if (!fpcert) { - Log(LogCritical, "cli", "Failed to open certificate file '" + certfile + "' for output"); + Log(LogCritical, "cli") + << "Failed to open certificate file '" << certfile << "' for output"; return 1; } diff --git a/lib/compat/checkresultreader.cpp b/lib/compat/checkresultreader.cpp index d925300ca..4e9c68810 100644 --- a/lib/compat/checkresultreader.cpp +++ b/lib/compat/checkresultreader.cpp @@ -118,8 +118,8 @@ void CheckResultReader::ProcessCheckResultFile(const String& path) const Host::Ptr host = Host::GetByName(attrs["host_name"]); if (!host) { - Log(LogWarning, "CheckResultReader", "Ignoring checkresult file for host '" + attrs["host_name"] + - "': Host does not exist."); + Log(LogWarning, "CheckResultReader") + << "Ignoring checkresult file for host '" << attrs["host_name"] << "': Host does not exist."; return; } @@ -127,8 +127,9 @@ void CheckResultReader::ProcessCheckResultFile(const String& path) const Service::Ptr service = host->GetServiceByShortName(attrs["service_description"]); if (!service) { - Log(LogWarning, "CheckResultReader", "Ignoring checkresult file for host '" + attrs["host_name"] + - "', service '" + attrs["service_description"] + "': Service does not exist."); + Log(LogWarning, "CheckResultReader") + << "Ignoring checkresult file for host '" << attrs["host_name"] + << "', service '" << attrs["service_description"] << "': Service does not exist."; return; } @@ -143,8 +144,9 @@ void CheckResultReader::ProcessCheckResultFile(const String& path) const service->ProcessCheckResult(result); - Log(LogDebug, "CheckResultReader", "Processed checkresult file for host '" + attrs["host_name"] + - "', service '" + attrs["service_description"] + "'"); + Log(LogDebug, "CheckResultReader") + << "Processed checkresult file for host '" << attrs["host_name"] + << "', service '" << attrs["service_description"] << "'"; { ObjectLock olock(service); diff --git a/lib/compat/compatlogger.cpp b/lib/compat/compatlogger.cpp index 108f5ef17..40dc58f60 100644 --- a/lib/compat/compatlogger.cpp +++ b/lib/compat/compatlogger.cpp @@ -321,7 +321,8 @@ void CompatLogger::FlappingHandler(const Checkable::Ptr& checkable, FlappingStat flapping_state_str = "DISABLED"; break; default: - Log(LogCritical, "CompatLogger", "Unknown flapping state: " + Convert::ToString(flapping_state)); + Log(LogCritical, "CompatLogger") + << "Unknown flapping state: " << flapping_state; return; } @@ -434,15 +435,18 @@ void CompatLogger::ReopenFile(bool rotate) if (rotate) { String archiveFile = GetLogDir() + "/archives/icinga-" + Utility::FormatDateTime("%m-%d-%Y-%H", Utility::GetTime()) + ".log"; - Log(LogNotice, "CompatLogger", "Rotating compat log file '" + tempFile + "' -> '" + archiveFile + "'"); + Log(LogNotice, "CompatLogger") + << "Rotating compat log file '" << tempFile << "' -> '" << archiveFile << "'"; + (void) rename(tempFile.CStr(), archiveFile.CStr()); } } m_OutputFile.open(tempFile.CStr(), std::ofstream::app); - if (!m_OutputFile.good()) { - Log(LogWarning, "CompatLogger", "Could not open compat log file '" + tempFile + "' for writing. Log output will be lost."); + if (!m_OutputFile) { + Log(LogWarning, "CompatLogger") + << "Could not open compat log file '" << tempFile << "' for writing. Log output will be lost."; return; } @@ -536,8 +540,10 @@ void CompatLogger::ScheduleNextRotation(void) time_t ts = mktime(&tmthen); - Log(LogNotice, "CompatLogger", "Rescheduling rotation timer for compat log '" - + GetName() + "' to '" + Utility::FormatDateTime("%Y/%m/%d %H:%M:%S %z", ts) + "'"); + Log(LogNotice, "CompatLogger") + << "Rescheduling rotation timer for compat log '" + << GetName() << "' to '" << Utility::FormatDateTime("%Y/%m/%d %H:%M:%S %z", ts) << "'"; + m_RotationTimer->Reschedule(ts); } diff --git a/lib/compat/externalcommandlistener.cpp b/lib/compat/externalcommandlistener.cpp index 2a3dd68cf..6cdd4a5d7 100644 --- a/lib/compat/externalcommandlistener.cpp +++ b/lib/compat/externalcommandlistener.cpp @@ -81,18 +81,16 @@ void ExternalCommandListener::CommandPipeThread(const String& commandPath) mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; if (!fifo_ok && mkfifo(commandPath.CStr(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) < 0) { - std::ostringstream msgbuf; - msgbuf << "mkfifo() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "ExternalCommandListener", msgbuf.str()); + Log(LogCritical, "ExternalCommandListener") + << "mkfifo() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; return; } /* mkfifo() uses umask to mask off some bits, which means we need to chmod() the * fifo to get the right mask. */ if (chmod(commandPath.CStr(), mode) < 0) { - std::ostringstream msgbuf; - msgbuf << "chmod() on fifo '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "ExternalCommandListener", msgbuf.str()); + Log(LogCritical, "ExternalCommandListener") + << "chmod() on fifo '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; return; } @@ -104,18 +102,16 @@ void ExternalCommandListener::CommandPipeThread(const String& commandPath) } while (fd < 0 && errno == EINTR); if (fd < 0) { - std::ostringstream msgbuf; - msgbuf << "open() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "ExternalCommandListener", msgbuf.str()); + Log(LogCritical, "ExternalCommandListener") + << "open() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; return; } FILE *fp = fdopen(fd, "r"); if (fp == NULL) { - std::ostringstream msgbuf; - msgbuf << "fdopen() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "ExternalCommandListener", msgbuf.str()); + Log(LogCritical, "ExternalCommandListener") + << "fdopen() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; return; } @@ -131,13 +127,13 @@ void ExternalCommandListener::CommandPipeThread(const String& commandPath) String command = line; try { - Log(LogInformation, "ExternalCommandListener", "Executing external command: " + command); + Log(LogInformation, "ExternalCommandListener") + << "Executing external command: " << command; ExternalCommandProcessor::Execute(command); } catch (const std::exception& ex) { - std::ostringstream msgbuf; - msgbuf << "External command failed." << DiagnosticInformation(ex); - Log(LogWarning, "ExternalCommandListener", msgbuf.str()); + Log(LogWarning, "ExternalCommandListener") + << "External command failed." << DiagnosticInformation(ex); } } diff --git a/lib/compat/statusdatawriter.cpp b/lib/compat/statusdatawriter.cpp index 5fb97407e..4db6397c4 100644 --- a/lib/compat/statusdatawriter.cpp +++ b/lib/compat/statusdatawriter.cpp @@ -693,7 +693,8 @@ void StatusDataWriter::UpdateObjectsCache(void) Checkable::Ptr parent = dep->GetParent(); if (!parent) { - Log(LogDebug, "StatusDataWriter", "Missing parent for dependency '" + dep->GetName() + "'."); + Log(LogDebug, "StatusDataWriter") + << "Missing parent for dependency '" << dep->GetName() << "'."; continue; } @@ -704,8 +705,9 @@ void StatusDataWriter::UpdateObjectsCache(void) Checkable::Ptr child = dep->GetChild(); if (!child) { + Log(LogDebug, "StatusDataWriter") + << "Missing child for dependency '" << dep->GetName() << "'."; continue; - Log(LogDebug, "StatusDataWriter", "Missing child for dependency '" + dep->GetName() + "'."); } Host::Ptr child_host; @@ -840,5 +842,6 @@ void StatusDataWriter::StatusTimerHandler(void) << boost::errinfo_file_name(statuspathtmp)); } - Log(LogNotice, "StatusDataWriter", "Writing status.dat file took " + Utility::FormatDuration(Utility::GetTime() - start)); + Log(LogNotice, "StatusDataWriter") + << "Writing status.dat file took " << Utility::FormatDuration(Utility::GetTime() - start); } diff --git a/lib/config/configcompiler.cpp b/lib/config/configcompiler.cpp index c58b876bd..9d61ec2da 100644 --- a/lib/config/configcompiler.cpp +++ b/lib/config/configcompiler.cpp @@ -200,7 +200,8 @@ void ConfigCompiler::CompileFile(const String& path, const String& zone) << boost::errinfo_errno(errno) << boost::errinfo_file_name(path)); - Log(LogInformation, "ConfigCompiler", "Compiling config file: " + path); + Log(LogInformation, "ConfigCompiler") + << "Compiling config file: " << path; return CompileStream(path, &stream, zone); } @@ -225,7 +226,8 @@ void ConfigCompiler::CompileText(const String& path, const String& text, const S */ void ConfigCompiler::AddIncludeSearchDir(const String& dir) { - Log(LogInformation, "ConfigCompiler", "Adding include search dir: " + dir); + Log(LogInformation, "ConfigCompiler") + << "Adding include search dir: " << dir; m_IncludeSearchDirs.push_back(dir); } diff --git a/lib/config/configitem.cpp b/lib/config/configitem.cpp index eb3c2af78..7dd1a7816 100644 --- a/lib/config/configitem.cpp +++ b/lib/config/configitem.cpp @@ -172,7 +172,8 @@ DynamicObject::Ptr ConfigItem::Commit(void) ASSERT(!OwnsLock()); #ifdef _DEBUG - Log(LogDebug, "ConfigItem", "Commit called for ConfigItem Type=" + GetType() + ", Name=" + GetName()); + Log(LogDebug, "ConfigItem") + << "Commit called for ConfigItem Type=" << GetType() << ", Name=" << GetName(); #endif /* _DEBUG */ /* Make sure the type is valid. */ @@ -282,7 +283,8 @@ void ConfigItem::ValidateItem(void) void ConfigItem::WriteObjectsFile(const String& filename) { - Log(LogInformation, "ConfigItem", "Dumping config items to file '" + filename + "'"); + Log(LogInformation, "ConfigItem") + << "Dumping config items to file '" << filename << "'"; String tempFilename = filename + ".tmp"; @@ -398,7 +400,8 @@ bool ConfigItem::ValidateItems(const String& objectsFile) BOOST_FOREACH(const DynamicType::Ptr& type, DynamicType::GetTypes()) { int count = std::distance(type->GetObjects().first, type->GetObjects().second); if (count > 0) - Log(LogInformation, "ConfigItem", "Checked " + Convert::ToString(count) + " " + type->GetName() + "(s)."); + Log(LogInformation, "ConfigItem") + << "Checked " << count << " " << type->GetName() << "(s)."; } return !ConfigCompilerContext::GetInstance()->HasErrors(); @@ -413,7 +416,8 @@ bool ConfigItem::ActivateItems(void) try { DynamicObject::RestoreObjects(Application::GetStatePath()); } catch (const std::exception& ex) { - Log(LogCritical, "ConfigItem", "Failed to restore state file: " + DiagnosticInformation(ex)); + Log(LogCritical, "ConfigItem") + << "Failed to restore state file: " << DiagnosticInformation(ex); } Log(LogInformation, "ConfigItem", "Triggering Start signal for config items"); @@ -426,7 +430,8 @@ bool ConfigItem::ActivateItems(void) continue; #ifdef _DEBUG - Log(LogDebug, "ConfigItem", "Activating object '" + object->GetName() + "' of type '" + object->GetType()->GetName() + "'"); + Log(LogDebug, "ConfigItem") + << "Activating object '" << object->GetName() << "' of type '" << object->GetType()->GetName() << "'"; #endif /* _DEBUG */ upq.Enqueue(boost::bind(&DynamicObject::Activate, object)); } diff --git a/lib/config/expression.cpp b/lib/config/expression.cpp index 090476e0f..3e0b19572 100644 --- a/lib/config/expression.cpp +++ b/lib/config/expression.cpp @@ -52,7 +52,8 @@ Value Expression::Evaluate(const Dictionary::Ptr& locals, DebugHint *dhint) cons if (m_Operator != &Expression::OpLiteral) { std::ostringstream msgbuf; ShowCodeFragment(msgbuf, m_DebugInfo, false); - Log(LogDebug, "Expression", "Executing:\n" + msgbuf.str()); + Log(LogDebug, "Expression") + << "Executing:\n" << msgbuf.str(); } #endif /* _DEBUG */ diff --git a/lib/db_ido/dbconnection.cpp b/lib/db_ido/dbconnection.cpp index f5c13bc43..60af3a7bf 100644 --- a/lib/db_ido/dbconnection.cpp +++ b/lib/db_ido/dbconnection.cpp @@ -46,7 +46,9 @@ void DbConnection::OnConfigLoaded(void) DynamicObject::OnConfigLoaded(); if (!GetEnableHa()) { - Log(LogDebug, "DbConnection", "HA functionality disabled. Won't pause IDO connection: " + GetName()); + Log(LogDebug, "DbConnection") + << "HA functionality disabled. Won't pause IDO connection: " << GetName(); + SetHAMode(HARunEverywhere); } } @@ -62,7 +64,8 @@ void DbConnection::Resume(void) { DynamicObject::Resume(); - Log(LogInformation, "DbConnection", "Resuming IDO connection: " + GetName()); + Log(LogInformation, "DbConnection") + << "Resuming IDO connection: " << GetName(); m_CleanUpTimer = make_shared(); m_CleanUpTimer->SetInterval(60); @@ -74,7 +77,8 @@ void DbConnection::Pause(void) { DynamicObject::Pause(); - Log(LogInformation, "DbConnection", "Pausing IDO connection: " + GetName()); + Log(LogInformation, "DbConnection") + << "Pausing IDO connection: " << GetName(); m_CleanUpTimer.reset(); } @@ -160,7 +164,8 @@ void DbConnection::ProgramStatusHandler(void) BOOST_FOREACH(const Dictionary::Pair& kv, vars) { if (!kv.first.IsEmpty()) { - Log(LogDebug, "DbConnection", "icinga application customvar key: '" + kv.first + "' value: '" + Convert::ToString(kv.second) + "'"); + Log(LogDebug, "DbConnection") + << "icinga application customvar key: '" << kv.first << "' value: '" << kv.second << "'"; Dictionary::Ptr fields4 = make_shared(); fields4->Set("varname", Convert::ToString(kv.first)); @@ -211,9 +216,10 @@ void DbConnection::CleanUpHandler(void) continue; CleanUpExecuteQuery(tables[i].name, tables[i].time_column, now - max_age); - Log(LogNotice, "DbConnection", "Cleanup (" + tables[i].name + "): " + Convert::ToString(max_age) + - " now: " + Convert::ToString(now) + - " old: " + Convert::ToString(now - max_age)); + Log(LogNotice, "DbConnection") + << "Cleanup (" << tables[i].name << "): " << max_age + << " now: " << now + << " old: " << now - max_age; } } diff --git a/lib/db_ido/dbevents.cpp b/lib/db_ido/dbevents.cpp index a803ed2bc..40bf896d2 100644 --- a/lib/db_ido/dbevents.cpp +++ b/lib/db_ido/dbevents.cpp @@ -282,7 +282,8 @@ void DbEvents::AddCommentInternal(const Checkable::Ptr& checkable, const Comment return; } - Log(LogDebug, "DbEvents", "adding service comment (id = " + Convert::ToString(comment->GetLegacyId()) + ") for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "adding service comment (id = " << comment->GetLegacyId() << ") for '" << checkable->GetName() << "'"; /* add the service comment */ AddCommentByType(checkable, comment, historical); @@ -340,7 +341,8 @@ void DbEvents::AddCommentByType(const DynamicObject::Ptr& object, const Comment: void DbEvents::RemoveComments(const Checkable::Ptr& checkable) { - Log(LogDebug, "DbEvents", "removing service comments for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "removing service comments for '" << checkable->GetName() << "'"; DbQuery query1; query1.Table = "comments"; @@ -358,7 +360,8 @@ void DbEvents::RemoveComment(const Checkable::Ptr& checkable, const Comment::Ptr return; } - Log(LogDebug, "DbEvents", "removing service comment (id = " + Convert::ToString(comment->GetLegacyId()) + ") for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "removing service comment (id = " << comment->GetLegacyId() << ") for '" << checkable->GetName() << "'"; /* Status */ DbQuery query1; @@ -427,7 +430,8 @@ void DbEvents::AddDowntimeInternal(const Checkable::Ptr& checkable, const Downti return; } - Log(LogDebug, "DbEvents", "adding service downtime (id = " + Convert::ToString(downtime->GetLegacyId()) + ") for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "adding service downtime (id = " << downtime->GetLegacyId() << ") for '" << checkable->GetName() << "'"; /* add the downtime */ AddDowntimeByType(checkable, downtime, historical);} @@ -485,7 +489,8 @@ void DbEvents::AddDowntimeByType(const Checkable::Ptr& checkable, const Downtime void DbEvents::RemoveDowntimes(const Checkable::Ptr& checkable) { - Log(LogDebug, "DbEvents", "removing service downtimes for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "removing service downtimes for '" << checkable->GetName() << "'"; DbQuery query1; query1.Table = "scheduleddowntime"; @@ -503,7 +508,8 @@ void DbEvents::RemoveDowntime(const Checkable::Ptr& checkable, const Downtime::P return; } - Log(LogDebug, "DbEvents", "removing service downtime (id = " + Convert::ToString(downtime->GetLegacyId()) + ") for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "removing service downtime (id = " << downtime->GetLegacyId() << ") for '" << checkable->GetName() << "'"; /* Status */ DbQuery query1; @@ -547,7 +553,8 @@ void DbEvents::TriggerDowntime(const Checkable::Ptr& checkable, const Downtime:: return; } - Log(LogDebug, "DbEvents", "updating triggered service downtime (id = " + Convert::ToString(downtime->GetLegacyId()) + ") for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "updating triggered service downtime (id = " << downtime->GetLegacyId() << ") for '" << checkable->GetName() << "'"; double now = Utility::GetTime(); std::pair time_bag = CompatUtility::ConvertTimestamp(now); @@ -629,7 +636,8 @@ void DbEvents::TriggerDowntime(const Checkable::Ptr& checkable, const Downtime:: void DbEvents::AddAcknowledgementHistory(const Checkable::Ptr& checkable, const String& author, const String& comment, AcknowledgementType type, double expiry) { - Log(LogDebug, "DbEvents", "add acknowledgement history for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "add acknowledgement history for '" << checkable->GetName() << "'"; double now = Utility::GetTime(); std::pair time_bag = CompatUtility::ConvertTimestamp(now); @@ -669,14 +677,16 @@ void DbEvents::AddAcknowledgementHistory(const Checkable::Ptr& checkable, const void DbEvents::AddAcknowledgement(const Checkable::Ptr& checkable, AcknowledgementType type) { - Log(LogDebug, "DbEvents", "add acknowledgement for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "add acknowledgement for '" << checkable->GetName() << "'"; AddAcknowledgementInternal(checkable, type, true); } void DbEvents::RemoveAcknowledgement(const Checkable::Ptr& checkable) { - Log(LogDebug, "DbEvents", "remove acknowledgement for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "remove acknowledgement for '" << checkable->GetName() << "'"; AddAcknowledgementInternal(checkable, AcknowledgementNone, false); } @@ -716,7 +726,8 @@ void DbEvents::AddAcknowledgementInternal(const Checkable::Ptr& checkable, Ackno void DbEvents::AddNotificationHistory(const Notification::Ptr& notification, const Checkable::Ptr& checkable, const std::set& users, NotificationType type, const CheckResult::Ptr& cr, const String& author, const String& text) { - Log(LogDebug, "DbEvents", "add notification history for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "add notification history for '" << checkable->GetName() << "'"; /* start and end happen at the same time */ double now = Utility::GetTime(); @@ -768,7 +779,8 @@ void DbEvents::AddNotificationHistory(const Notification::Ptr& notification, con /* filtered users */ BOOST_FOREACH(const User::Ptr& user, users) { - Log(LogDebug, "DbEvents", "add contact notification history for service '" + checkable->GetName() + "' and user '" + user->GetName() + "'."); + Log(LogDebug, "DbEvents") + << "add contact notification history for service '" << checkable->GetName() << "' and user '" << user->GetName() << "'."; Dictionary::Ptr fields2 = make_shared(); fields2->Set("contact_object_id", user); @@ -788,7 +800,8 @@ void DbEvents::AddNotificationHistory(const Notification::Ptr& notification, con /* statehistory */ void DbEvents::AddStateChangeHistory(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr, StateType type) { - Log(LogDebug, "DbEvents", "add state change history for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "add state change history for '" << checkable->GetName() << "'"; double now = Utility::GetTime(); std::pair time_bag = CompatUtility::ConvertTimestamp(now); @@ -897,7 +910,8 @@ void DbEvents::AddCheckResultLogHistory(const Checkable::Ptr& checkable, const C type = LogEntryTypeServiceCritical; break; default: - Log(LogCritical, "DbEvents", "Unknown service state: " + Convert::ToString(state_after)); + Log(LogCritical, "DbEvents") + << "Unknown service state: " << state_after; return; } } else { @@ -922,7 +936,8 @@ void DbEvents::AddCheckResultLogHistory(const Checkable::Ptr& checkable, const C type = LogEntryTypeHostDown; break; default: - Log(LogCritical, "DbEvents", "Unknown host state: " + Convert::ToString(state_after)); + Log(LogCritical, "DbEvents") + << "Unknown host state: " << state_after; return; } @@ -1076,7 +1091,8 @@ void DbEvents::AddFlappingLogHistory(const Checkable::Ptr& checkable, FlappingSt flapping_state_str = "DISABLED"; break; default: - Log(LogCritical, "DbEvents", "Unknown flapping state: " + Convert::ToString(flapping_state)); + Log(LogCritical, "DbEvents") + << "Unknown flapping state: " << flapping_state; return; } @@ -1106,7 +1122,8 @@ void DbEvents::AddFlappingLogHistory(const Checkable::Ptr& checkable, FlappingSt void DbEvents::AddLogHistory(const Checkable::Ptr& checkable, String buffer, LogEntryType type) { - Log(LogDebug, "DbEvents", "add log entry history for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "add log entry history for '" << checkable->GetName() << "'"; double now = Utility::GetTime(); std::pair time_bag = CompatUtility::ConvertTimestamp(now); @@ -1139,7 +1156,8 @@ void DbEvents::AddLogHistory(const Checkable::Ptr& checkable, String buffer, Log /* flappinghistory */ void DbEvents::AddFlappingHistory(const Checkable::Ptr& checkable, FlappingState flapping_state) { - Log(LogDebug, "DbEvents", "add flapping history for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "add flapping history for '" << checkable->GetName() << "'"; double now = Utility::GetTime(); std::pair time_bag = CompatUtility::ConvertTimestamp(now); @@ -1167,7 +1185,8 @@ void DbEvents::AddFlappingHistory(const Checkable::Ptr& checkable, FlappingState fields1->Set("reason_type", 2); break; default: - Log(LogDebug, "DbEvents", "Unhandled flapping state: " + Convert::ToString(flapping_state)); + Log(LogDebug, "DbEvents") + << "Unhandled flapping state: " << flapping_state; return; } @@ -1199,7 +1218,8 @@ void DbEvents::AddServiceCheckHistory(const Checkable::Ptr& checkable, const Che if (!cr) return; - Log(LogDebug, "DbEvents", "add service check history for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "add service check history for '" << checkable->GetName() << "'"; Host::Ptr host; Service::Ptr service; @@ -1263,7 +1283,8 @@ void DbEvents::AddServiceCheckHistory(const Checkable::Ptr& checkable, const Che /* eventhandlers */ void DbEvents::AddEventHandlerHistory(const Checkable::Ptr& checkable) { - Log(LogDebug, "DbEvents", "add eventhandler history for '" + checkable->GetName() + "'"); + Log(LogDebug, "DbEvents") + << "add eventhandler history for '" << checkable->GetName() << "'"; double now = Utility::GetTime(); std::pair time_bag = CompatUtility::ConvertTimestamp(now); diff --git a/lib/db_ido/dbobject.cpp b/lib/db_ido/dbobject.cpp index f9c5a335b..d276513c9 100644 --- a/lib/db_ido/dbobject.cpp +++ b/lib/db_ido/dbobject.cpp @@ -127,7 +127,8 @@ void DbObject::SendStatusUpdate(void) if (GetType()->GetTable() != "endpoint") { String node = IcingaApplication::GetInstance()->GetNodeName(); - Log(LogDebug, "DbObject", "Endpoint node: '" + node + "' status update for '" + GetObject()->GetName() + "'"); + Log(LogDebug, "DbObject") + << "Endpoint node: '" << node << "' status update for '" << GetObject()->GetName() << "'"; Endpoint::Ptr endpoint = Endpoint::GetByName(node); if (endpoint) @@ -160,7 +161,8 @@ void DbObject::SendVarsConfigUpdate(void) Dictionary::Ptr vars = CompatUtility::GetCustomAttributeConfig(custom_var_object); if (vars) { - Log(LogDebug, "DbObject", "Updating object vars for '" + custom_var_object->GetName() + "'"); + Log(LogDebug, "DbObject") + << "Updating object vars for '" << custom_var_object->GetName() << "'"; ObjectLock olock (vars); @@ -168,8 +170,9 @@ void DbObject::SendVarsConfigUpdate(void) if (!kv.first.IsEmpty()) { int overridden = custom_var_object->IsVarOverridden(kv.first) ? 1 : 0; - Log(LogDebug, "DbObject", "object customvar key: '" + kv.first + "' value: '" + Convert::ToString(kv.second) + - "' overridden: " + Convert::ToString(overridden)); + Log(LogDebug, "DbObject") + << "object customvar key: '" << kv.first << "' value: '" << kv.second + << "' overridden: " << overridden; Dictionary::Ptr fields = make_shared(); fields->Set("varname", Convert::ToString(kv.first)); @@ -202,7 +205,8 @@ void DbObject::SendVarsStatusUpdate(void) Dictionary::Ptr vars = CompatUtility::GetCustomAttributeConfig(custom_var_object); if (vars) { - Log(LogDebug, "DbObject", "Updating object vars for '" + custom_var_object->GetName() + "'"); + Log(LogDebug, "DbObject") + << "Updating object vars for '" << custom_var_object->GetName() << "'"; ObjectLock olock (vars); @@ -210,8 +214,9 @@ void DbObject::SendVarsStatusUpdate(void) if (!kv.first.IsEmpty()) { int overridden = custom_var_object->IsVarOverridden(kv.first) ? 1 : 0; - Log(LogDebug, "DbObject", "object customvar key: '" + kv.first + "' value: '" + Convert::ToString(kv.second) + - "' overridden: " + Convert::ToString(overridden)); + Log(LogDebug, "DbObject") + << "object customvar key: '" << kv.first << "' value: '" << kv.second + << "' overridden: " << overridden; Dictionary::Ptr fields = make_shared(); fields->Set("varname", Convert::ToString(kv.first)); @@ -322,7 +327,8 @@ void DbObject::VarsChangedHandler(const CustomVarObject::Ptr& object) { DbObject::Ptr dbobj = GetOrCreateByObject(object); - Log(LogDebug, "DbObject", "Vars changed for object '" + object->GetName() + "'"); + Log(LogDebug, "DbObject") + << "Vars changed for object '" << object->GetName() << "'"; if (!dbobj) return; diff --git a/lib/db_ido/endpointdbobject.cpp b/lib/db_ido/endpointdbobject.cpp index 90c477550..39ec869b3 100644 --- a/lib/db_ido/endpointdbobject.cpp +++ b/lib/db_ido/endpointdbobject.cpp @@ -62,7 +62,8 @@ Dictionary::Ptr EndpointDbObject::GetStatusFields(void) const Dictionary::Ptr fields = make_shared(); Endpoint::Ptr endpoint = static_pointer_cast(GetObject()); - Log(LogDebug, "EndpointDbObject", "update status for endpoint '" + endpoint->GetName() + "'"); + Log(LogDebug, "EndpointDbObject") + << "update status for endpoint '" << endpoint->GetName() << "'"; fields->Set("identity", endpoint->GetName()); fields->Set("node", IcingaApplication::GetInstance()->GetNodeName()); @@ -75,7 +76,8 @@ void EndpointDbObject::UpdateConnectedStatus(const Endpoint::Ptr& endpoint) { bool connected = EndpointIsConnected(endpoint); - Log(LogDebug, "EndpointDbObject", "update is_connected=" + Convert::ToString(connected ? 1 : 0) + " for endpoint '" + endpoint->GetName() + "'"); + Log(LogDebug, "EndpointDbObject") + << "update is_connected=" << connected << " for endpoint '" << endpoint->GetName() << "'"; DbQuery query1; query1.Table = "endpointstatus"; diff --git a/lib/db_ido/hostdbobject.cpp b/lib/db_ido/hostdbobject.cpp index b3bd6bdd8..fda26ae26 100644 --- a/lib/db_ido/hostdbobject.cpp +++ b/lib/db_ido/hostdbobject.cpp @@ -184,7 +184,8 @@ void HostDbObject::OnConfigUpdate(void) if (!parent) continue; - Log(LogDebug, "HostDbObject", "host parents: " + parent->GetName()); + Log(LogDebug, "HostDbObject") + << "host parents: " << parent->GetName(); /* parents: host_id, parent_host_object_id */ Dictionary::Ptr fields1 = make_shared(); @@ -201,19 +202,22 @@ void HostDbObject::OnConfigUpdate(void) } /* host dependencies */ - Log(LogDebug, "HostDbObject", "host dependencies for '" + host->GetName() + "'"); + Log(LogDebug, "HostDbObject") + << "host dependencies for '" << host->GetName() << "'"; BOOST_FOREACH(const Dependency::Ptr& dep, host->GetDependencies()) { Checkable::Ptr parent = dep->GetParent(); if (!parent) { - Log(LogDebug, "HostDbObject", "Missing parent for dependency '" + dep->GetName() + "'."); + Log(LogDebug, "HostDbObject") + << "Missing parent for dependency '" << dep->GetName() << "'."; continue; } int state_filter = dep->GetStateFilter(); - Log(LogDebug, "HostDbObject", "parent host: " + parent->GetName()); + Log(LogDebug, "HostDbObject") + << "parent host: " << parent->GetName(); Dictionary::Ptr fields2 = make_shared(); fields2->Set("host_object_id", parent); @@ -232,10 +236,12 @@ void HostDbObject::OnConfigUpdate(void) OnQuery(query2); } - Log(LogDebug, "HostDbObject", "host contacts: " + host->GetName()); + Log(LogDebug, "HostDbObject") + << "host contacts: " << host->GetName(); BOOST_FOREACH(const User::Ptr& user, CompatUtility::GetCheckableNotificationUsers(host)) { - Log(LogDebug, "HostDbObject", "host contacts: " + user->GetName()); + Log(LogDebug, "HostDbObject") + << "host contacts: " << user->GetName(); Dictionary::Ptr fields_contact = make_shared(); fields_contact->Set("host_id", DbValue::FromObjectInsertID(host)); @@ -250,10 +256,12 @@ void HostDbObject::OnConfigUpdate(void) OnQuery(query_contact); } - Log(LogDebug, "HostDbObject", "host contactgroups: " + host->GetName()); + Log(LogDebug, "HostDbObject") + << "host contactgroups: " << host->GetName(); BOOST_FOREACH(const UserGroup::Ptr& usergroup, CompatUtility::GetCheckableNotificationUserGroups(host)) { - Log(LogDebug, "HostDbObject", "host contactgroups: " + usergroup->GetName()); + Log(LogDebug, "HostDbObject") + << "host contactgroups: " << usergroup->GetName(); Dictionary::Ptr fields_contact = make_shared(); fields_contact->Set("host_id", DbValue::FromObjectInsertID(host)); diff --git a/lib/db_ido/servicedbobject.cpp b/lib/db_ido/servicedbobject.cpp index f8db77b10..d9229dd94 100644 --- a/lib/db_ido/servicedbobject.cpp +++ b/lib/db_ido/servicedbobject.cpp @@ -177,17 +177,20 @@ void ServiceDbObject::OnConfigUpdate(void) Service::Ptr service = static_pointer_cast(GetObject()); /* service dependencies */ - Log(LogDebug, "ServiceDbObject", "service dependencies for '" + service->GetName() + "'"); + Log(LogDebug, "ServiceDbObject") + << "service dependencies for '" << service->GetName() << "'"; BOOST_FOREACH(const Dependency::Ptr& dep, service->GetDependencies()) { Checkable::Ptr parent = dep->GetParent(); if (!parent) { - Log(LogDebug, "ServiceDbObject", "Missing parent for dependency '" + dep->GetName() + "'."); + Log(LogDebug, "ServiceDbObject") + << "Missing parent for dependency '" << dep->GetName() << "'."; continue; } - Log(LogDebug, "ServiceDbObject", "service parents: " + parent->GetName()); + Log(LogDebug, "ServiceDbObject") + << "service parents: " << parent->GetName(); int state_filter = dep->GetStateFilter(); @@ -212,10 +215,12 @@ void ServiceDbObject::OnConfigUpdate(void) } /* service contacts, contactgroups */ - Log(LogDebug, "ServiceDbObject", "service contacts: " + service->GetName()); + Log(LogDebug, "ServiceDbObject") + << "service contacts: " << service->GetName(); BOOST_FOREACH(const User::Ptr& user, CompatUtility::GetCheckableNotificationUsers(service)) { - Log(LogDebug, "ServiceDbObject", "service contacts: " + user->GetName()); + Log(LogDebug, "ServiceDbObject") + << "service contacts: " << user->GetName(); Dictionary::Ptr fields_contact = make_shared(); fields_contact->Set("service_id", DbValue::FromObjectInsertID(service)); @@ -233,7 +238,8 @@ void ServiceDbObject::OnConfigUpdate(void) Log(LogDebug, "ServiceDbObject", "service contactgroups: " + service->GetName()); BOOST_FOREACH(const UserGroup::Ptr& usergroup, CompatUtility::GetCheckableNotificationUserGroups(service)) { - Log(LogDebug, "ServiceDbObject", "service contactgroups: " + usergroup->GetName()); + Log(LogDebug, "ServiceDbObject") + << "service contactgroups: " << usergroup->GetName(); Dictionary::Ptr fields_contact = make_shared(); fields_contact->Set("service_id", DbValue::FromObjectInsertID(service)); diff --git a/lib/db_ido/userdbobject.cpp b/lib/db_ido/userdbobject.cpp index a5481e142..53da290db 100644 --- a/lib/db_ido/userdbobject.cpp +++ b/lib/db_ido/userdbobject.cpp @@ -85,7 +85,8 @@ void UserDbObject::OnConfigUpdate(void) User::Ptr user = static_pointer_cast(GetObject()); /* contact addresses */ - Log(LogDebug, "UserDbObject", "contact addresses for '" + user->GetName() + "'"); + Log(LogDebug, "UserDbObject") + << "contact addresses for '" << user->GetName() << "'"; Dictionary::Ptr vars = user->GetVars(); diff --git a/lib/db_ido_mysql/idomysqlconnection.cpp b/lib/db_ido_mysql/idomysqlconnection.cpp index d80efd633..c67de4429 100644 --- a/lib/db_ido_mysql/idomysqlconnection.cpp +++ b/lib/db_ido_mysql/idomysqlconnection.cpp @@ -97,7 +97,8 @@ void IdoMysqlConnection::ExceptionHandler(boost::exception_ptr exp) { Log(LogCritical, "IdoMysqlConnection", "Exception during database operation: Verify that your database is operational!"); - Log(LogDebug, "IdoMysqlConnection", "Exception during database operation: " + DiagnosticInformation(exp)); + Log(LogDebug, "IdoMysqlConnection") + << "Exception during database operation: " << DiagnosticInformation(exp); boost::mutex::scoped_lock lock(m_ConnectionMutex); @@ -191,18 +192,16 @@ void IdoMysqlConnection::Reconnect(void) /* connection */ if (!mysql_init(&m_Connection)) { - std::ostringstream msgbuf; - msgbuf << "mysql_init() failed: \"" << mysql_error(&m_Connection) << "\""; - Log(LogCritical, "IdoMysqlConnection", msgbuf.str()); + Log(LogCritical, "IdoMysqlConnection") + << "mysql_init() failed: \"" << mysql_error(&m_Connection) << "\""; BOOST_THROW_EXCEPTION(std::bad_alloc()); } if (!mysql_real_connect(&m_Connection, host, user, passwd, db, port, NULL, CLIENT_FOUND_ROWS)) { - std::ostringstream msgbuf; - msgbuf << "Connection to database '" << db << "' with user '" << user << "' on '" << host << ":" << port + Log(LogCritical, "IdoMysqlConnection") + << "Connection to database '" << db << "' with user '" << user << "' on '" << host << ":" << port << "' failed: \"" << mysql_error(&m_Connection) << "\""; - Log(LogCritical, "IdoMysqlConnection", msgbuf.str()); BOOST_THROW_EXCEPTION(std::runtime_error(mysql_error(&m_Connection))); } @@ -225,8 +224,9 @@ void IdoMysqlConnection::Reconnect(void) String version = row->Get("version"); if (Utility::CompareVersion(SCHEMA_VERSION, version) < 0) { - Log(LogCritical, "IdoMysqlConnection", "Schema version '" + version + "' does not match the required version '" + - SCHEMA_VERSION + "'! Please check the upgrade documentation."); + Log(LogCritical, "IdoMysqlConnection") + << "Schema version '" << version << "' does not match the required version '" + << SCHEMA_VERSION << "'! Please check the upgrade documentation."; Application::Exit(EXIT_FAILURE); } @@ -273,8 +273,8 @@ void IdoMysqlConnection::Reconnect(void) double status_update_age = Utility::GetTime() - status_update_time; - Log(LogNotice, "IdoMysqlConnection", "Last update by '" + - endpoint_name + "' was " + Convert::ToString(status_update_age) + "s ago."); + Log(LogNotice, "IdoMysqlConnection") + << "Last update by '" << endpoint_name << "' was " << status_update_age << "s ago."; if (status_update_age < GetFailoverTimeout()) { mysql_close(&m_Connection); @@ -285,8 +285,8 @@ void IdoMysqlConnection::Reconnect(void) /* activate the IDO only, if we're authoritative in this zone */ if (IsPaused()) { - Log(LogNotice, "IdoMysqlConnection", "Local endpoint '" + - my_endpoint->GetName() + "' is not authoritative, bailing out."); + Log(LogNotice, "IdoMysqlConnection") + << "Local endpoint '" << my_endpoint->GetName() << "' is not authoritative, bailing out."; mysql_close(&m_Connection); m_Connected = false; @@ -298,9 +298,8 @@ void IdoMysqlConnection::Reconnect(void) Log(LogNotice, "IdoMysqlConnection", "Enabling IDO connection."); } - std::ostringstream msgbuf; - msgbuf << "MySQL IDO instance id: " << static_cast(m_InstanceID) << " (schema version: '" + version + "')"; - Log(LogInformation, "IdoMysqlConnection", msgbuf.str()); + Log(LogInformation, "IdoMysqlConnection") + << "MySQL IDO instance id: " << static_cast(m_InstanceID) << " (schema version: '" + version + "')"; /* set session time zone to utc */ Query("SET SESSION TIME_ZONE='+00:00'"); @@ -340,8 +339,9 @@ void IdoMysqlConnection::Reconnect(void) /* deactivate all deleted configuration objects */ BOOST_FOREACH(const DbObject::Ptr& dbobj, active_dbobjs) { if (dbobj->GetObject() == NULL) { - Log(LogNotice, "IdoMysqlConnection", "Deactivate deleted object name1: '" + Convert::ToString(dbobj->GetName1() + - "' name2: '" + Convert::ToString(dbobj->GetName2() + "'."))); + Log(LogNotice, "IdoMysqlConnection") + << "Deactivate deleted object name1: '" << dbobj->GetName1() + << "' name2: '" << dbobj->GetName2() + "'."; DeactivateObject(dbobj); } } diff --git a/lib/db_ido_pgsql/idopgsqlconnection.cpp b/lib/db_ido_pgsql/idopgsqlconnection.cpp index 28eb34470..b01f6d88d 100644 --- a/lib/db_ido_pgsql/idopgsqlconnection.cpp +++ b/lib/db_ido_pgsql/idopgsqlconnection.cpp @@ -99,7 +99,8 @@ void IdoPgsqlConnection::ExceptionHandler(boost::exception_ptr exp) { Log(LogWarning, "IdoPgsqlConnection", "Exception during database operation: Verify that your database is operational!"); - Log(LogDebug, "IdoPgsqlConnection", "Exception during database operation: " + DiagnosticInformation(exp)); + Log(LogDebug, "IdoPgsqlConnection") + << "Exception during database operation: " << DiagnosticInformation(exp); boost::mutex::scoped_lock lock(m_ConnectionMutex); @@ -202,10 +203,9 @@ void IdoPgsqlConnection::Reconnect(void) PQfinish(m_Connection); m_Connection = NULL; - std::ostringstream msgbuf; - msgbuf << "Connection to database '" << db << "' with user '" << user << "' on '" << host << ":" << port + Log(LogCritical, "IdoPgsqlConnection") + << "Connection to database '" << db << "' with user '" << user << "' on '" << host << ":" << port << "' failed: \"" << message << "\""; - Log(LogCritical, "IdoPgsqlConnection", msgbuf.str()); BOOST_THROW_EXCEPTION(std::runtime_error(message)); } @@ -224,8 +224,9 @@ void IdoPgsqlConnection::Reconnect(void) String version = row->Get("version"); if (Utility::CompareVersion(SCHEMA_VERSION, version) < 0) { - Log(LogCritical, "IdoPgsqlConnection", "Schema version '" + version + "' does not match the required version '" + - SCHEMA_VERSION + "'! Please check the upgrade documentation."); + Log(LogCritical, "IdoPgsqlConnection") + << "Schema version '" << version << "' does not match the required version '" + << SCHEMA_VERSION << "'! Please check the upgrade documentation."; Application::Exit(EXIT_FAILURE); } @@ -269,8 +270,8 @@ void IdoPgsqlConnection::Reconnect(void) double status_update_age = Utility::GetTime() - status_update_time; - Log(LogNotice, "IdoPgsqlConnection", "Last update by '" + - endpoint_name + "' was " + Convert::ToString(status_update_age) + "s ago."); + Log(LogNotice, "IdoPgsqlConnection") + << "Last update by '" << endpoint_name << "' was " << status_update_age << "s ago."; if (status_update_age < GetFailoverTimeout()) { PQfinish(m_Connection); @@ -281,8 +282,8 @@ void IdoPgsqlConnection::Reconnect(void) /* activate the IDO only, if we're authoritative in this zone */ if (IsPaused()) { - Log(LogNotice, "IdoPgsqlConnection", "Local endpoint '" + - my_endpoint->GetName() + "' is not authoritative, bailing out."); + Log(LogNotice, "IdoPgsqlConnection") + << "Local endpoint '" << my_endpoint->GetName() << "' is not authoritative, bailing out."; PQfinish(m_Connection); m_Connection = NULL; @@ -294,9 +295,8 @@ void IdoPgsqlConnection::Reconnect(void) Log(LogNotice, "IdoPgsqlConnection", "Enabling IDO connection."); } - std::ostringstream msgbuf; - msgbuf << "pgSQL IDO instance id: " << static_cast(m_InstanceID) << " (schema version: '" + version + "')"; - Log(LogInformation, "IdoPgsqlConnection", msgbuf.str()); + Log(LogInformation, "IdoPgsqlConnection") + << "pgSQL IDO instance id: " << static_cast(m_InstanceID) << " (schema version: '" + version + "')"; /* record connection */ Query("INSERT INTO " + GetTablePrefix() + "conninfo " + @@ -336,8 +336,9 @@ void IdoPgsqlConnection::Reconnect(void) /* deactivate all deleted configuration objects */ BOOST_FOREACH(const DbObject::Ptr& dbobj, active_dbobjs) { if (dbobj->GetObject() == NULL) { - Log(LogNotice, "IdoPgsqlConnection", "Deactivate deleted object name1: '" + Convert::ToString(dbobj->GetName1() + - "' name2: '" + Convert::ToString(dbobj->GetName2() + "'."))); + Log(LogNotice, "IdoPgsqlConnection") + << "Deactivate deleted object name1: '" << dbobj->GetName1() + << "' name2: '" << dbobj->GetName2() + "'."; DeactivateObject(dbobj); } } @@ -352,15 +353,15 @@ IdoPgsqlResult IdoPgsqlConnection::Query(const String& query) { AssertOnWorkQueue(); - Log(LogDebug, "IdoPgsqlConnection", "Query: " + query); + Log(LogDebug, "IdoPgsqlConnection") + << "Query: " << query; PGresult *result = PQexec(m_Connection, query.CStr()); if (!result) { String message = PQerrorMessage(m_Connection); - std::ostringstream msgbuf; - msgbuf << "Error \"" << message << "\" when executing query \"" << query << "\""; - Log(LogCritical, "IdoPgsqlConnection", msgbuf.str()); + Log(LogCritical, "IdoPgsqlConnection") + << "Error \"" << message << "\" when executing query \"" << query << "\""; BOOST_THROW_EXCEPTION( database_error() @@ -381,9 +382,8 @@ IdoPgsqlResult IdoPgsqlConnection::Query(const String& query) String message = PQresultErrorMessage(result); PQclear(result); - std::ostringstream msgbuf; - msgbuf << "Error \"" << message << "\" when executing query \"" << query << "\""; - Log(LogCritical, "IdoPgsqlConnection", msgbuf.str()); + Log(LogCritical, "IdoPgsqlConnection") + << "Error \"" << message << "\" when executing query \"" << query << "\""; BOOST_THROW_EXCEPTION( database_error() @@ -405,9 +405,8 @@ DbReference IdoPgsqlConnection::GetSequenceValue(const String& table, const Stri ASSERT(row); - std::ostringstream msgbuf; - msgbuf << "Sequence Value: " << row->Get("id"); - Log(LogDebug, "IdoPgsqlConnection", msgbuf.str()); + Log(LogDebug, "IdoPgsqlConnection") + << "Sequence Value: " << row->Get("id"); return DbReference(Convert::ToLong(row->Get("id"))); } @@ -713,8 +712,10 @@ void IdoPgsqlConnection::InternalExecuteQuery(const DbQuery& query, DbQueryType if (type == DbQueryInsert && query.Table == "notifications" && query.NotificationObject) { // FIXME remove hardcoded table name String idField = "notification_id"; - SetNotificationInsertID(query.NotificationObject, GetSequenceValue(GetTablePrefix() + query.Table, idField)); - Log(LogDebug, "IdoPgsqlConnection", "saving contactnotification notification_id=" + Convert::ToString(static_cast(GetSequenceValue(GetTablePrefix() + query.Table, idField)))); + DbReference seqval = GetSequenceValue(GetTablePrefix() + query.Table, idField); + SetNotificationInsertID(query.NotificationObject, seqval); + Log(LogDebug, "IdoPgsqlConnection") + << "saving contactnotification notification_id=" << Convert::ToString(seqval); } } diff --git a/lib/icinga/api.cpp b/lib/icinga/api.cpp index 9e6afed7e..471d9324f 100644 --- a/lib/icinga/api.cpp +++ b/lib/icinga/api.cpp @@ -32,7 +32,8 @@ Value API::GetAnswerToEverything(const Dictionary::Ptr& params) if (params) text = params->Get("text"); - Log(LogInformation, "API", "Hello from the Icinga 2 API: " + text); + Log(LogInformation, "API") + << "Hello from the Icinga 2 API: " << text; return 42; } diff --git a/lib/icinga/checkable-check.cpp b/lib/icinga/checkable-check.cpp index af37cead8..1290c1b34 100644 --- a/lib/icinga/checkable-check.cpp +++ b/lib/icinga/checkable-check.cpp @@ -417,11 +417,12 @@ void Checkable::ProcessCheckResult(const CheckResult::Ptr& cr, const MessageOrig olock.Unlock(); -// Log(LogDebug, "Checkable", "Flapping: Checkable " + GetName() + -// " was: " + Convert::ToString(was_flapping) + -// " is: " + Convert::ToString(is_flapping) + -// " threshold: " + Convert::ToString(GetFlappingThreshold()) + -// "% current: " + Convert::ToString(GetFlappingCurrent()) + "%."); +// Log(LogDebug, "Checkable") +// << "Flapping: Checkable " << GetName() +// << " was: " << (was_flapping) +// << " is: " << is_flapping) +// << " threshold: " << GetFlappingThreshold() +// << "% current: " + GetFlappingCurrent()) << "%."; OnNewCheckResult(GetSelf(), cr, origin); @@ -433,10 +434,12 @@ void Checkable::ProcessCheckResult(const CheckResult::Ptr& cr, const MessageOrig if (hardChange) { OnStateChange(GetSelf(), cr, StateTypeHard, origin); - Log(LogNotice, "Checkable", "State Change: Checkable " + GetName() + " hard state change from " + old_state_str + " to " + new_state_str + " detected."); + Log(LogNotice, "Checkable") + << "State Change: Checkable " << GetName() << " hard state change from " << old_state_str << " to " << new_state_str << " detected."; } else if (stateChange) { OnStateChange(GetSelf(), cr, StateTypeSoft, origin); - Log(LogNotice, "Checkable", "State Change: Checkable " + GetName() + " soft state change from " + old_state_str + " to " + new_state_str + " detected."); + Log(LogNotice, "Checkable") + << "State Change: Checkable " << GetName() << " soft state change from " << old_state_str << " to " << new_state_str << " detected."; } if (GetStateType() == StateTypeSoft || hardChange || recovery) @@ -448,12 +451,14 @@ void Checkable::ProcessCheckResult(const CheckResult::Ptr& cr, const MessageOrig if (!was_flapping && is_flapping) { OnNotificationsRequested(GetSelf(), NotificationFlappingStart, cr, "", ""); - Log(LogNotice, "Checkable", "Flapping: Checkable " + GetName() + " started flapping (" + Convert::ToString(GetFlappingThreshold()) + "% < " + Convert::ToString(GetFlappingCurrent()) + "%)."); + Log(LogNotice, "Checkable") + << "Flapping: Checkable " << GetName() << " started flapping (" << GetFlappingThreshold() << "% < " << GetFlappingCurrent() << "%)."; OnFlappingChanged(GetSelf(), FlappingStarted); } else if (was_flapping && !is_flapping) { OnNotificationsRequested(GetSelf(), NotificationFlappingEnd, cr, "", ""); - Log(LogNotice, "Checkable", "Flapping: Checkable " + GetName() + " stopped flapping (" + Convert::ToString(GetFlappingThreshold()) + "% >= " + Convert::ToString(GetFlappingCurrent()) + "%)."); + Log(LogNotice, "Checkable") + << "Flapping: Checkable " << GetName() << " stopped flapping (" << GetFlappingThreshold() << "% >= " << GetFlappingCurrent() << "%)."; OnFlappingChanged(GetSelf(), FlappingStopped); } else if (send_notification) OnNotificationsRequested(GetSelf(), recovery ? NotificationRecovery : NotificationProblem, cr, "", ""); diff --git a/lib/icinga/checkable-dependency.cpp b/lib/icinga/checkable-dependency.cpp index d6e87133e..213031eb9 100644 --- a/lib/icinga/checkable-dependency.cpp +++ b/lib/icinga/checkable-dependency.cpp @@ -63,7 +63,8 @@ std::set Checkable::GetReverseDependencies(void) const bool Checkable::IsReachable(DependencyType dt, Dependency::Ptr *failedDependency, int rstack) const { if (rstack > 20) { - Log(LogWarning, "Checkable", "Too many nested dependencies for service '" + GetName() + "': Dependency failed."); + Log(LogWarning, "Checkable") + << "Too many nested dependencies for service '" << GetName() << "': Dependency failed."; return false; } diff --git a/lib/icinga/checkable-downtime.cpp b/lib/icinga/checkable-downtime.cpp index 20207f02e..6bb640aff 100644 --- a/lib/icinga/checkable-downtime.cpp +++ b/lib/icinga/checkable-downtime.cpp @@ -104,8 +104,10 @@ String Checkable::AddDowntime(const String& author, const String& comment, l_DowntimesCache[uid] = GetSelf(); } - Log(LogNotice, "Checkable", "Added downtime with ID '" + Convert::ToString(downtime->GetLegacyId()) + - "' between '" + Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", startTime) + "' and '" + Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime) + "'."); + Log(LogNotice, "Checkable") + << "Added downtime with ID '" << downtime->GetLegacyId() + << "' between '" << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", startTime) + << "' and '" << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime) << "'."; OnDowntimeAdded(GetSelf(), downtime, origin); @@ -131,7 +133,8 @@ void Checkable::RemoveDowntime(const String& id, bool cancelled, const MessageOr String config_owner = downtime->GetConfigOwner(); if (!config_owner.IsEmpty()) { - Log(LogWarning, "Checkable", "Cannot remove downtime with ID '" + Convert::ToString(legacy_id) + "'. It is owned by scheduled downtime object '" + config_owner + "'"); + Log(LogWarning, "Checkable") + << "Cannot remove downtime with ID '" << legacy_id << "'. It is owned by scheduled downtime object '" << config_owner << "'"; return; } @@ -145,7 +148,8 @@ void Checkable::RemoveDowntime(const String& id, bool cancelled, const MessageOr downtime->SetWasCancelled(cancelled); - Log(LogNotice, "Checkable", "Removed downtime with ID '" + Convert::ToString(downtime->GetLegacyId()) + "' from service '" + owner->GetName() + "'."); + Log(LogNotice, "Checkable") + << "Removed downtime with ID '" << downtime->GetLegacyId() << "' from service '" << owner->GetName() << "'."; OnDowntimeRemoved(owner, downtime, origin); } @@ -178,16 +182,19 @@ void Checkable::TriggerDowntime(const String& id) return; if (downtime->IsActive() && downtime->IsTriggered()) { - Log(LogDebug, "Checkable", "Not triggering downtime with ID '" + Convert::ToString(downtime->GetLegacyId()) + "': already triggered."); + Log(LogDebug, "Checkable") + << "Not triggering downtime with ID '" << downtime->GetLegacyId() << "': already triggered."; return; } if (downtime->IsExpired()) { - Log(LogDebug, "Checkable", "Not triggering downtime with ID '" + Convert::ToString(downtime->GetLegacyId()) + "': expired."); + Log(LogDebug, "Checkable") + << "Not triggering downtime with ID '" << downtime->GetLegacyId() << "': expired."; return; } - Log(LogNotice, "Checkable", "Triggering downtime with ID '" + Convert::ToString(downtime->GetLegacyId()) + "'."); + Log(LogNotice, "Checkable") + << "Triggering downtime with ID '" << downtime->GetLegacyId() << "'."; if (downtime->GetTriggerTime() == 0) downtime->SetTriggerTime(Utility::GetTime()); diff --git a/lib/icinga/checkable-event.cpp b/lib/icinga/checkable-event.cpp index afc9235e2..8ac20823c 100644 --- a/lib/icinga/checkable-event.cpp +++ b/lib/icinga/checkable-event.cpp @@ -75,7 +75,8 @@ void Checkable::ExecuteEventHandler(void) if (!ec) return; - Log(LogNotice, "Checkable", "Executing event handler '" + ec->GetName() + "' for service '" + GetName() + "'"); + Log(LogNotice, "Checkable") + << "Executing event handler '" << ec->GetName() << "' for service '" << GetName() << "'"; ec->Execute(GetSelf()); diff --git a/lib/icinga/checkable-flapping.cpp b/lib/icinga/checkable-flapping.cpp index 70608aebd..fe3de9364 100644 --- a/lib/icinga/checkable-flapping.cpp +++ b/lib/icinga/checkable-flapping.cpp @@ -80,7 +80,8 @@ void Checkable::UpdateFlappingStatus(bool stateChange) if (negative < 0) negative = 0; -// Log(LogDebug, "Checkable", "Flapping counter for '" + GetName() + "' is positive=" + Convert::ToString(positive) + ", negative=" + Convert::ToString(negative)); +// Log(LogDebug, "Checkable") +// << "Flapping counter for '" << GetName() << "' is positive=" << positive << ", negative=" << negative; SetFlappingLastChange(now); SetFlappingPositive(positive); diff --git a/lib/icinga/checkable-notification.cpp b/lib/icinga/checkable-notification.cpp index 01ec04c91..cd255d843 100644 --- a/lib/icinga/checkable-notification.cpp +++ b/lib/icinga/checkable-notification.cpp @@ -51,32 +51,33 @@ void Checkable::SendNotifications(NotificationType type, const CheckResult::Ptr& if (!IcingaApplication::GetInstance()->GetEnableNotifications() || !GetEnableNotifications()) { if (!force) { - Log(LogInformation, "Checkable", "Notifications are disabled for service '" + GetName() + "'."); + Log(LogInformation, "Checkable") + << "Notifications are disabled for service '" << GetName() << "'."; return; } SetForceNextNotification(false); } - Log(LogInformation, "Checkable", "Checking for configured notifications for object '" + GetName() + "'"); + Log(LogInformation, "Checkable") + << "Checking for configured notifications for object '" << GetName() << "'"; std::set notifications = GetNotifications(); if (notifications.empty()) - Log(LogInformation, "Checkable", "Checkable '" + GetName() + "' does not have any notifications."); + Log(LogInformation, "Checkable") + << "Checkable '" << GetName() << "' does not have any notifications."; - Log(LogDebug, "Checkable", "Checkable '" + GetName() + "' has " + Convert::ToString(notifications.size()) + " notification(s)."); + Log(LogDebug, "Checkable") + << "Checkable '" << GetName() << "' has " << notifications.size() << " notification(s)."; BOOST_FOREACH(const Notification::Ptr& notification, notifications) { try { notification->BeginExecuteNotification(type, cr, force, author, text); } catch (const std::exception& ex) { - std::ostringstream msgbuf; - msgbuf << "Exception occured during notification for service '" - << GetName() << "': " << DiagnosticInformation(ex); - String message = msgbuf.str(); - - Log(LogWarning, "Checkable", message); + Log(LogWarning, "Checkable") + << "Exception occured during notification for service '" + << GetName() << "': " << DiagnosticInformation(ex); } } } diff --git a/lib/icinga/dependency-apply.cpp b/lib/icinga/dependency-apply.cpp index 9133bc5c4..5e5695582 100644 --- a/lib/icinga/dependency-apply.cpp +++ b/lib/icinga/dependency-apply.cpp @@ -62,9 +62,8 @@ bool Dependency::EvaluateApplyRuleOne(const Checkable::Ptr& checkable, const App if (!rule.EvaluateFilter(locals)) return false; - std::ostringstream msgbuf2; - msgbuf2 << "Applying dependency '" << rule.GetName() << "' to object '" << checkable->GetName() << "' for rule " << di; - Log(LogDebug, "Dependency", msgbuf2.str()); + Log(LogDebug, "Dependency") + << "Applying dependency '" << rule.GetName() << "' to object '" << checkable->GetName() << "' for rule " << di; ConfigItemBuilder::Ptr builder = make_shared(di); builder->SetType("Dependency"); @@ -127,7 +126,8 @@ void Dependency::EvaluateApplyRule(const ApplyRule& rule) } if (apply_count == 0) - Log(LogWarning, "Dependency", "Apply rule '" + rule.GetName() + "' for host does not match anywhere!"); + Log(LogWarning, "Dependency") + << "Apply rule '" << rule.GetName() << "' for host does not match anywhere!"; } else if (rule.GetTargetType() == "Service") { apply_count = 0; @@ -145,10 +145,12 @@ void Dependency::EvaluateApplyRule(const ApplyRule& rule) } if (apply_count == 0) - Log(LogWarning, "Dependency", "Apply rule '" + rule.GetName() + "' for service does not match anywhere!"); + Log(LogWarning, "Dependency") + << "Apply rule '" << rule.GetName() << "' for service does not match anywhere!"; } else { - Log(LogWarning, "Dependency", "Wrong target type for apply rule '" + rule.GetName() + "'!"); + Log(LogWarning, "Dependency") + << "Wrong target type for apply rule '" << rule.GetName() << "'!"; } } diff --git a/lib/icinga/dependency.cpp b/lib/icinga/dependency.cpp index 3b3826177..09310e0bc 100644 --- a/lib/icinga/dependency.cpp +++ b/lib/icinga/dependency.cpp @@ -66,16 +66,19 @@ void Dependency::OnStateLoaded(void) if (childHost) { if (GetChildServiceName().IsEmpty()) { - Log(LogDebug, "Dependency", "Dependency '" + GetName() + "' child host '" + GetChildHostName() + "."); + Log(LogDebug, "Dependency") + << "Dependency '" << GetName() << "' child host '" << GetChildHostName() << "."; m_Child = childHost; } else { - Log(LogDebug, "Dependency", "Dependency '" + GetName() + "' child host '" + GetChildHostName() + "' service '" + GetChildServiceName() + "' ."); + Log(LogDebug, "Dependency") + << "Dependency '" << GetName() << "' child host '" << GetChildHostName() << "' service '" << GetChildServiceName() << "' ."; m_Child = childHost->GetServiceByShortName(GetChildServiceName()); } } if (!m_Child) - Log(LogWarning, "Dependency", "Dependency '" + GetName() + "' references an invalid child object and will be ignored."); + Log(LogWarning, "Dependency") + << "Dependency '" << GetName() << "' references an invalid child object and will be ignored."; else m_Child->AddDependency(GetSelf()); @@ -83,16 +86,19 @@ void Dependency::OnStateLoaded(void) if (parentHost) { if (GetParentServiceName().IsEmpty()) { - Log(LogDebug, "Dependency", "Dependency '" + GetName() + "' parent host '" + GetParentHostName() + "."); + Log(LogDebug, "Dependency") + << "Dependency '" << GetName() << "' parent host '" << GetParentHostName() << "."; m_Parent = parentHost; } else { - Log(LogDebug, "Dependency", "Dependency '" + GetName() + "' parent host '" + GetParentHostName() + "' service '" + GetParentServiceName() + "' ."); + Log(LogDebug, "Dependency") + << "Dependency '" << GetName() << "' parent host '" << GetParentHostName() << "' service '" << GetParentServiceName() << "' ."; m_Parent = parentHost->GetServiceByShortName(GetParentServiceName()); } } if (!m_Parent) - Log(LogWarning, "Dependency", "Dependency '" + GetName() + "' references an invalid parent object and will always fail."); + Log(LogWarning, "Dependency") + << "Dependency '" << GetName() << "' references an invalid parent object and will always fail."; else m_Parent->AddReverseDependency(GetSelf()); } @@ -121,19 +127,22 @@ bool Dependency::IsAvailable(DependencyType dt) const /* ignore if it's the same checkable object */ if (parent == GetChild()) { - Log(LogNotice, "Dependency", "Dependency '" + GetName() + "' passed: Parent and child " + (service ? "service" : "host") + " are identical."); + Log(LogNotice, "Dependency") + << "Dependency '" << GetName() << "' passed: Parent and child " << (service ? "service" : "host") << " are identical."; return true; } /* ignore pending */ if (!parent->GetLastCheckResult()) { - Log(LogNotice, "Dependency", "Dependency '" + GetName() + "' passed: " + (service ? "Service" : "Host") + " '" + parent->GetName() + "' hasn't been checked yet."); + Log(LogNotice, "Dependency") + << "Dependency '" << GetName() << "' passed: " << (service ? "Service" : "Host") << " '" << parent->GetName() << "' hasn't been checked yet."; return true; } /* ignore soft states */ if (parent->GetStateType() == StateTypeSoft) { - Log(LogNotice, "Dependency", "Dependency '" + GetName() + "' passed: " + (service ? "Service" : "Host") + " '" + parent->GetName() + "' is in a soft state."); + Log(LogNotice, "Dependency") + << "Dependency '" << GetName() << "' passed: " << (service ? "Service" : "Host") << " '" << parent->GetName() << "' is in a soft state."; return true; } @@ -146,28 +155,34 @@ bool Dependency::IsAvailable(DependencyType dt) const /* check state */ if (state & GetStateFilter()) { - Log(LogNotice, "Dependency", "Dependency '" + GetName() + "' passed: " + (service ? "Service" : "Host") + " '" + parent->GetName() + "' matches state filter."); + Log(LogNotice, "Dependency") + << "Dependency '" << GetName() << "' passed: " << (service ? "Service" : "Host") << " '" << parent->GetName() << "' matches state filter."; return true; } /* ignore if not in time period */ TimePeriod::Ptr tp = GetPeriod(); if (tp && !tp->IsInside(Utility::GetTime())) { - Log(LogNotice, "Dependency", "Dependency '" + GetName() + "' passed: Outside time period."); + Log(LogNotice, "Dependency") + << "Dependency '" << GetName() << "' passed: Outside time period."; return true; } if (dt == DependencyCheckExecution && !GetDisableChecks()) { - Log(LogNotice, "Dependency", "Dependency '" + GetName() + "' passed: Checks are not disabled."); + Log(LogNotice, "Dependency") + << "Dependency '" << GetName() << "' passed: Checks are not disabled."; return true; } else if (dt == DependencyNotification && !GetDisableNotifications()) { - Log(LogNotice, "Dependency", "Dependency '" + GetName() + "' passed: Notifications are not disabled"); + Log(LogNotice, "Dependency") + << "Dependency '" << GetName() << "' passed: Notifications are not disabled"; return true; } - Log(LogNotice, "Dependency", "Dependency '" + GetName() + "' failed. Parent " + - (service ? "service" : "host") + " '" + parent->GetName() + "' is " + - (service ? Service::StateToString(service->GetState()) : Host::StateToString(host->GetState()))); + Log(LogNotice, "Dependency") + << "Dependency '" << GetName() << "' failed. Parent " + << (service ? "service" : "host") << " '" << parent->GetName() << "' is " + << (service ? Service::StateToString(service->GetState()) : Host::StateToString(host->GetState())); + return false; } diff --git a/lib/icinga/hostgroup.cpp b/lib/icinga/hostgroup.cpp index 8c2ccae1f..8c8482ab1 100644 --- a/lib/icinga/hostgroup.cpp +++ b/lib/icinga/hostgroup.cpp @@ -51,15 +51,15 @@ bool HostGroup::EvaluateObjectRuleOne(const Host::Ptr& host, const ObjectRule& r if (!rule.EvaluateFilter(locals)) return false; - std::ostringstream msgbuf2; - msgbuf2 << "Assigning membership for group '" << rule.GetName() << "' to host '" << host->GetName() << "' for rule " << di; - Log(LogDebug, "HostGroup", msgbuf2.str()); + Log(LogDebug, "HostGroup") + << "Assigning membership for group '" << rule.GetName() << "' to host '" << host->GetName() << "' for rule " << di; String group_name = rule.GetName(); HostGroup::Ptr group = HostGroup::GetByName(group_name); if (!group) { - Log(LogCritical, "HostGroup", "Invalid membership assignment. Group '" + group_name + "' does not exist."); + Log(LogCritical, "HostGroup") + << "Invalid membership assignment. Group '" << group_name << "' does not exist."; return false; } @@ -113,8 +113,9 @@ void HostGroup::RemoveMember(const Host::Ptr& host) bool HostGroup::ResolveGroupMembership(Host::Ptr const& host, bool add, int rstack) { if (add && rstack > 20) { - Log(LogWarning, "HostGroup", "Too many nested groups for group '" + GetName() + "': Host '" + - host->GetName() + "' membership assignment failed."); + Log(LogWarning, "HostGroup") + << "Too many nested groups for group '" << GetName() << "': Host '" + << host->GetName() << "' membership assignment failed."; return false; } diff --git a/lib/icinga/legacytimeperiod.cpp b/lib/icinga/legacytimeperiod.cpp index fc87ae660..edacace87 100644 --- a/lib/icinga/legacytimeperiod.cpp +++ b/lib/icinga/legacytimeperiod.cpp @@ -323,7 +323,9 @@ bool LegacyTimePeriod::IsInDayDefinition(const String& daydef, tm *reference) ParseTimeRange(daydef, &begin, &end, &stride, reference); - Log(LogDebug, "LegacyTimePeriod", "ParseTimeRange: '" + daydef + "' => " + Convert::ToString(static_cast(mktime(&begin))) + " -> " + Convert::ToString(static_cast(mktime(&end))) + ", stride: " + Convert::ToString(stride)); + Log(LogDebug, "LegacyTimePeriod") + << "ParseTimeRange: '" << daydef << "' => " << mktime(&begin) + << " -> " << mktime(&end) << ", stride: " << stride; return IsInTimeRange(&begin, &end, stride, reference); } @@ -451,20 +453,23 @@ Array::Ptr LegacyTimePeriod::ScriptFunc(const TimePeriod::Ptr& tp, double begin, tm reference = Utility::LocalTime(refts); #ifdef _DEBUG - Log(LogDebug, "LegacyTimePeriod", "Checking reference time " + Convert::ToString(static_cast(refts))); + Log(LogDebug, "LegacyTimePeriod") + << "Checking reference time " << refts; #endif /* _DEBUG */ ObjectLock olock(ranges); BOOST_FOREACH(const Dictionary::Pair& kv, ranges) { if (!IsInDayDefinition(kv.first, &reference)) { #ifdef _DEBUG - Log(LogDebug, "LegacyTimePeriod", "Not in day definition '" + kv.first + "'."); + Log(LogDebug, "LegacyTimePeriod") + << "Not in day definition '" << kv.first << "'."; #endif /* _DEBUG */ continue; } #ifdef _DEBUG - Log(LogDebug, "LegacyTimePeriod", "In day definition '" + kv.first + "'."); + Log(LogDebug, "LegacyTimePeriod") + << "In day definition '" << kv.first << "'."; #endif /* _DEBUG */ ProcessTimeRanges(kv.second, &reference, segments); @@ -472,7 +477,8 @@ Array::Ptr LegacyTimePeriod::ScriptFunc(const TimePeriod::Ptr& tp, double begin, } } - Log(LogDebug, "LegacyTimePeriod", "Legacy timeperiod update returned " + Convert::ToString(static_cast(segments->GetLength())) + " segments."); + Log(LogDebug, "LegacyTimePeriod") + << "Legacy timeperiod update returned " << segments->GetLength() << " segments."; return segments; } diff --git a/lib/icinga/macroprocessor.cpp b/lib/icinga/macroprocessor.cpp index 09c04ba2b..a0e63c9da 100644 --- a/lib/icinga/macroprocessor.cpp +++ b/lib/icinga/macroprocessor.cpp @@ -183,7 +183,8 @@ String MacroProcessor::InternalResolveMacros(const String& str, const ResolverLi if (!found) { if (!missingMacro) - Log(LogWarning, "MacroProcessor", "Macro '" + name + "' is not defined."); + Log(LogWarning, "MacroProcessor") + << "Macro '" << name << "' is not defined."; else *missingMacro = name; } diff --git a/lib/icinga/notification-apply.cpp b/lib/icinga/notification-apply.cpp index 3c0b64ed6..bb1e560be 100644 --- a/lib/icinga/notification-apply.cpp +++ b/lib/icinga/notification-apply.cpp @@ -62,9 +62,8 @@ bool Notification::EvaluateApplyRuleOne(const Checkable::Ptr& checkable, const A if (!rule.EvaluateFilter(locals)) return false; - std::ostringstream msgbuf2; - msgbuf2 << "Applying notification '" << rule.GetName() << "' to object '" << checkable->GetName() << "' for rule " << di; - Log(LogDebug, "Notification", msgbuf2.str()); + Log(LogDebug, "Notification") + << "Applying notification '" << rule.GetName() << "' to object '" << checkable->GetName() << "' for rule " << di; ConfigItemBuilder::Ptr builder = make_shared(di); builder->SetType("Notification"); @@ -122,7 +121,8 @@ void Notification::EvaluateApplyRule(const ApplyRule& rule) } if (apply_count == 0) - Log(LogWarning, "Notification", "Apply rule '" + rule.GetName() + "' for host does not match anywhere!"); + Log(LogWarning, "Notification") + << "Apply rule '" << rule.GetName() << "' for host does not match anywhere!"; } else if (rule.GetTargetType() == "Service") { apply_count = 0; @@ -140,10 +140,12 @@ void Notification::EvaluateApplyRule(const ApplyRule& rule) } if (apply_count == 0) - Log(LogWarning, "Notification", "Apply rule '" + rule.GetName() + "' for service does not match anywhere!"); + Log(LogWarning, "Notification") + << "Apply rule '" << rule.GetName() << "' for service does not match anywhere!"; } else { - Log(LogWarning, "Notification", "Wrong target type for apply rule '" + rule.GetName() + "'!"); + Log(LogWarning, "Notification") + << "Wrong target type for apply rule '" << rule.GetName() << "'!"; } } void Notification::EvaluateApplyRules(const std::vector& rules) diff --git a/lib/icinga/notification.cpp b/lib/icinga/notification.cpp index 1031c2884..c7602b688 100644 --- a/lib/icinga/notification.cpp +++ b/lib/icinga/notification.cpp @@ -231,7 +231,8 @@ void Notification::BeginExecuteNotification(NotificationType type, const CheckRe TimePeriod::Ptr tp = GetPeriod(); if (tp && !tp->IsInside(Utility::GetTime())) { - Log(LogNotice, "Notification", "Not sending notifications for notification object '" + GetName() + "': not in timeperiod"); + Log(LogNotice, "Notification") + << "Not sending notifications for notification object '" << GetName() << "': not in timeperiod"; return; } @@ -240,22 +241,26 @@ void Notification::BeginExecuteNotification(NotificationType type, const CheckRe if (type == NotificationProblem) { if (times && times->Contains("begin") && now < checkable->GetLastHardStateChange() + times->Get("begin")) { - Log(LogNotice, "Notification", "Not sending notifications for notification object '" + GetName() + "': before escalation range"); + Log(LogNotice, "Notification") + << "Not sending notifications for notification object '" << GetName() << "': before escalation range"; return; } if (times && times->Contains("end") && now > checkable->GetLastHardStateChange() + times->Get("end")) { - Log(LogNotice, "Notification", "Not sending notifications for notification object '" + GetName() + "': after escalation range"); + Log(LogNotice, "Notification") + << "Not sending notifications for notification object '" << GetName() << "': after escalation range"; return; } } unsigned long ftype = 1 << type; - Log(LogDebug, "Notification", "FType=" + Convert::ToString(ftype) + ", TypeFilter=" + Convert::ToString(GetTypeFilter())); + Log(LogDebug, "Notification") + << "FType=" << ftype << ", TypeFilter=" << GetTypeFilter(); if (!(ftype & GetTypeFilter())) { - Log(LogNotice, "Notification", "Not sending notifications for notification object '" + GetName() + "': type filter does not match"); + Log(LogNotice, "Notification") + << "Not sending notifications for notification object '" << GetName() << "': type filter does not match"; return; } @@ -271,7 +276,8 @@ void Notification::BeginExecuteNotification(NotificationType type, const CheckRe fstate = HostStateToFilter(host->GetState()); if (!(fstate & GetStateFilter())) { - Log(LogNotice, "Notification", "Not sending notifications for notification object '" + GetName() + "': state filter does not match"); + Log(LogNotice, "Notification") + << "Not sending notifications for notification object '" << GetName() << "': state filter does not match"; return; } } @@ -303,7 +309,9 @@ void Notification::BeginExecuteNotification(NotificationType type, const CheckRe if (!user->GetEnableNotifications() || !CheckNotificationUserFilters(type, user, force)) continue; - Log(LogInformation, "Notification", "Sending notification for user '" + user->GetName() + "'"); + Log(LogInformation, "Notification") + << "Sending notification for user '" << user->GetName() << "'"; + Utility::QueueAsyncCallback(boost::bind(&Notification::ExecuteNotificationHelper, this, type, user, cr, force, author, text)); /* collect all notified users */ @@ -322,16 +330,18 @@ bool Notification::CheckNotificationUserFilters(NotificationType type, const Use TimePeriod::Ptr tp = user->GetPeriod(); if (tp && !tp->IsInside(Utility::GetTime())) { - Log(LogNotice, "Notification", "Not sending notifications for notification object '" + - GetName() + " and user '" + user->GetName() + "': user not in timeperiod"); + Log(LogNotice, "Notification") + << "Not sending notifications for notification object '" + << GetName() << " and user '" << user->GetName() << "': user not in timeperiod"; return false; } unsigned long ftype = 1 << type; if (!(ftype & user->GetTypeFilter())) { - Log(LogNotice, "Notification", "Not sending notifications for notification object '" + - GetName() + " and user '" + user->GetName() + "': type filter does not match"); + Log(LogNotice, "Notification") + << "Not sending notifications for notification object '" + << GetName() << " and user '" << user->GetName() << "': type filter does not match"; return false; } @@ -348,8 +358,9 @@ bool Notification::CheckNotificationUserFilters(NotificationType type, const Use fstate = HostStateToFilter(host->GetState()); if (!(fstate & user->GetStateFilter())) { - Log(LogNotice, "Notification", "Not sending notifications for notification object '" + - GetName() + " and user '" + user->GetName() + "': state filter does not match"); + Log(LogNotice, "Notification") + << "Not sending notifications for notification object '" + << GetName() << " and user '" << user->GetName() << "': state filter does not match"; return false; } } @@ -365,7 +376,8 @@ void Notification::ExecuteNotificationHelper(NotificationType type, const User:: NotificationCommand::Ptr command = GetCommand(); if (!command) { - Log(LogDebug, "Notification", "No notification_command found for notification '" + GetName() + "'. Skipping execution."); + Log(LogDebug, "Notification") + << "No notification_command found for notification '" << GetName() << "'. Skipping execution."; return; } @@ -380,12 +392,12 @@ void Notification::ExecuteNotificationHelper(NotificationType type, const User:: /* required by compatlogger */ Service::OnNotificationSentToUser(GetSelf(), GetCheckable(), user, type, cr, author, text, command->GetName()); - Log(LogInformation, "Notification", "Completed sending notification for object '" + GetCheckable()->GetName() + "'"); + Log(LogInformation, "Notification") + << "Completed sending notification for object '" << GetCheckable()->GetName() << "'"; } catch (const std::exception& ex) { - std::ostringstream msgbuf; - msgbuf << "Exception occured during notification for object '" - << GetCheckable()->GetName() << "': " << DiagnosticInformation(ex); - Log(LogWarning, "Notification", msgbuf.str()); + Log(LogWarning, "Notification") + << "Exception occured during notification for object '" + << GetCheckable()->GetName() << "': " << DiagnosticInformation(ex); } } diff --git a/lib/icinga/pluginutility.cpp b/lib/icinga/pluginutility.cpp index 4ad707db8..55e9f028a 100644 --- a/lib/icinga/pluginutility.cpp +++ b/lib/icinga/pluginutility.cpp @@ -102,7 +102,8 @@ void PluginUtility::ExecuteCommand(const Command::Ptr& commandObj, const Checkab continue; } catch (const std::exception& ex) { /* tried to convert a string */ - Log(LogWarning, "PluginUtility", "Error evaluating set_if value '" + set_if_resolved + "': " + ex.what()); + Log(LogWarning, "PluginUtility") + << "Error evaluating set_if value '" << set_if_resolved << "': " << ex.what(); continue; } } diff --git a/lib/icinga/scheduleddowntime-apply.cpp b/lib/icinga/scheduleddowntime-apply.cpp index 172153376..22ca00ad3 100644 --- a/lib/icinga/scheduleddowntime-apply.cpp +++ b/lib/icinga/scheduleddowntime-apply.cpp @@ -61,9 +61,8 @@ bool ScheduledDowntime::EvaluateApplyRule(const Checkable::Ptr& checkable, const if (!rule.EvaluateFilter(locals)) return false; - std::ostringstream msgbuf2; - msgbuf2 << "Applying scheduled downtime '" << rule.GetName() << "' to object '" << checkable->GetName() << "' for rule " << di; - Log(LogDebug, "ScheduledDowntime", msgbuf2.str()); + Log(LogDebug, "ScheduledDowntime") + << "Applying scheduled downtime '" << rule.GetName() << "' to object '" << checkable->GetName() << "' for rule " << di; ConfigItemBuilder::Ptr builder = make_shared(di); builder->SetType("ScheduledDowntime"); @@ -122,7 +121,8 @@ void ScheduledDowntime::EvaluateApplyRules(const std::vector& rules) } if (apply_count == 0) - Log(LogWarning, "ScheduledDowntime", "Apply rule '" + rule.GetName() + "' for host does not match anywhere!"); + Log(LogWarning, "ScheduledDowntime") + << "Apply rule '" << rule.GetName() << "' for host does not match anywhere!"; } else if (rule.GetTargetType() == "Service") { apply_count = 0; @@ -140,10 +140,12 @@ void ScheduledDowntime::EvaluateApplyRules(const std::vector& rules) } if (apply_count == 0) - Log(LogWarning, "ScheduledDowntime", "Apply rule '" + rule.GetName() + "' for service does not match anywhere!"); + Log(LogWarning, "ScheduledDowntime") + << "Apply rule '" << rule.GetName() << "' for service does not match anywhere!"; } else { - Log(LogWarning, "ScheduledDowntime", "Wrong target type for apply rule '" + rule.GetName() + "'!"); + Log(LogWarning, "ScheduledDowntime") + << "Wrong target type for apply rule '" << rule.GetName() << "'!"; } } } diff --git a/lib/icinga/scheduleddowntime.cpp b/lib/icinga/scheduleddowntime.cpp index fa7722075..34f6582f5 100644 --- a/lib/icinga/scheduleddowntime.cpp +++ b/lib/icinga/scheduleddowntime.cpp @@ -91,7 +91,8 @@ std::pair ScheduledDowntime::FindNextSegment(void) time_t refts = Utility::GetTime(); tm reference = Utility::LocalTime(refts); - Log(LogDebug, "ScheduledDowntime", "Finding next scheduled downtime segment for time " + Convert::ToString(static_cast(refts))); + Log(LogDebug, "ScheduledDowntime") + << "Finding next scheduled downtime segment for time " << refts; Dictionary::Ptr ranges = GetRanges(); diff --git a/lib/icinga/service-apply.cpp b/lib/icinga/service-apply.cpp index 9ba215dbb..3312b6a23 100644 --- a/lib/icinga/service-apply.cpp +++ b/lib/icinga/service-apply.cpp @@ -54,9 +54,8 @@ bool Service::EvaluateApplyRuleOne(const Host::Ptr& host, const ApplyRule& rule) if (!rule.EvaluateFilter(locals)) return false; - std::ostringstream msgbuf2; - msgbuf2 << "Applying service '" << rule.GetName() << "' to host '" << host->GetName() << "' for rule " << di; - Log(LogDebug, "Service", msgbuf2.str()); + Log(LogDebug, "Service") + << "Applying service '" << rule.GetName() << "' to host '" << host->GetName() << "' for rule " << di; ConfigItemBuilder::Ptr builder = make_shared(di); builder->SetType("Service"); @@ -109,7 +108,8 @@ void Service::EvaluateApplyRule(const ApplyRule& rule) } if (apply_count == 0) - Log(LogWarning, "Service", "Apply rule '" + rule.GetName() + "' for host does not match anywhere!"); + Log(LogWarning, "Service") + << "Apply rule '" << rule.GetName() << "' for host does not match anywhere!"; } void Service::EvaluateApplyRules(const std::vector& rules) diff --git a/lib/icinga/servicegroup.cpp b/lib/icinga/servicegroup.cpp index be8daa389..76aa92833 100644 --- a/lib/icinga/servicegroup.cpp +++ b/lib/icinga/servicegroup.cpp @@ -54,15 +54,15 @@ bool ServiceGroup::EvaluateObjectRuleOne(const Service::Ptr& service, const Obje if (!rule.EvaluateFilter(locals)) return false; - std::ostringstream msgbuf2; - msgbuf2 << "Assigning membership for group '" << rule.GetName() << "' to service '" << service->GetName() << "' for rule " << di; - Log(LogDebug, "ServiceGroup", msgbuf2.str()); + Log(LogDebug, "ServiceGroup") + << "Assigning membership for group '" << rule.GetName() << "' to service '" << service->GetName() << "' for rule " << di; String group_name = rule.GetName(); ServiceGroup::Ptr group = ServiceGroup::GetByName(group_name); if (!group) { - Log(LogCritical, "ServiceGroup", "Invalid membership assignment. Group '" + group_name + "' does not exist."); + Log(LogCritical, "ServiceGroup") + << "Invalid membership assignment. Group '" << group_name << "' does not exist."; return false; } @@ -116,8 +116,9 @@ void ServiceGroup::RemoveMember(const Service::Ptr& service) bool ServiceGroup::ResolveGroupMembership(Service::Ptr const& service, bool add, int rstack) { if (add && rstack > 20) { - Log(LogWarning, "ServiceGroup", "Too many nested groups for group '" + GetName() + "': Service '" + - service->GetName() + "' membership assignment failed."); + Log(LogWarning, "ServiceGroup") + << "Too many nested groups for group '" << GetName() << "': Service '" + << service->GetName() << "' membership assignment failed."; return false; } diff --git a/lib/icinga/timeperiod.cpp b/lib/icinga/timeperiod.cpp index 292373a52..929249b63 100644 --- a/lib/icinga/timeperiod.cpp +++ b/lib/icinga/timeperiod.cpp @@ -55,7 +55,9 @@ void TimePeriod::AddSegment(double begin, double end) { ASSERT(OwnsLock()); - Log(LogDebug, "TimePeriod", "Adding segment '" + Utility::FormatDateTime("%c", begin) + "' <-> '" + Utility::FormatDateTime("%c", end) + "' to TimePeriod '" + GetName() + "'"); + Log(LogDebug, "TimePeriod") + << "Adding segment '" << Utility::FormatDateTime("%c", begin) << "' <-> '" + << Utility::FormatDateTime("%c", end) << "' to TimePeriod '" << GetName() << "'"; if (GetValidBegin().IsEmpty() || begin < GetValidBegin()) SetValidBegin(begin); @@ -106,7 +108,9 @@ void TimePeriod::RemoveSegment(double begin, double end) { ASSERT(OwnsLock()); - Log(LogDebug, "TimePeriod", "Removing segment '" + Utility::FormatDateTime("%c", begin) + "' <-> '" + Utility::FormatDateTime("%c", end) + "' from TimePeriod '" + GetName() + "'"); + Log(LogDebug, "TimePeriod") + << "Removing segment '" << Utility::FormatDateTime("%c", begin) << "' <-> '" + << Utility::FormatDateTime("%c", end) << "' from TimePeriod '" << GetName() << "'"; if (GetValidBegin().IsEmpty() || begin < GetValidBegin()) SetValidBegin(begin); @@ -154,7 +158,9 @@ void TimePeriod::PurgeSegments(double end) { ASSERT(OwnsLock()); - Log(LogDebug, "TimePeriod", "Purging segments older than '" + Utility::FormatDateTime("%c", end) + "' from TimePeriod '" + GetName() + "'"); + Log(LogDebug, "TimePeriod") + << "Purging segments older than '" << Utility::FormatDateTime("%c", end) + << "' from TimePeriod '" << GetName() << "'"; if (GetValidBegin().IsEmpty() || end < GetValidBegin()) return; @@ -275,15 +281,19 @@ void TimePeriod::Dump(void) { Array::Ptr segments = GetSegments(); - Log(LogDebug, "TimePeriod", "Dumping TimePeriod '" + GetName() + "'"); - Log(LogDebug, "TimePeriod", "Valid from '" + Utility::FormatDateTime("%c", GetValidBegin()) + "' until '" + Utility::FormatDateTime("%c", GetValidEnd())); + Log(LogDebug, "TimePeriod") + << "Dumping TimePeriod '" << GetName() << "'"; + + Log(LogDebug, "TimePeriod") + << "Valid from '" << Utility::FormatDateTime("%c", GetValidBegin()) + << "' until '" << Utility::FormatDateTime("%c", GetValidEnd()); if (segments) { ObjectLock dlock(segments); BOOST_FOREACH(const Dictionary::Ptr& segment, segments) { - Log(LogDebug, "TimePeriod", "Segment: " + - Utility::FormatDateTime("%c", segment->Get("begin")) + " <-> " + - Utility::FormatDateTime("%c", segment->Get("end"))); + Log(LogDebug, "TimePeriod") + << "Segment: " << Utility::FormatDateTime("%c", segment->Get("begin")) << " <-> " + << Utility::FormatDateTime("%c", segment->Get("end")); } } diff --git a/lib/icinga/usergroup.cpp b/lib/icinga/usergroup.cpp index c17a0b622..4bfa70bd2 100644 --- a/lib/icinga/usergroup.cpp +++ b/lib/icinga/usergroup.cpp @@ -51,15 +51,15 @@ bool UserGroup::EvaluateObjectRuleOne(const User::Ptr& user, const ObjectRule& r if (!rule.EvaluateFilter(locals)) return false; - std::ostringstream msgbuf2; - msgbuf2 << "Assigning membership for group '" << rule.GetName() << "' to user '" << user->GetName() << "' for rule " << di; - Log(LogDebug, "UserGroup", msgbuf2.str()); + Log(LogDebug, "UserGroup") + << "Assigning membership for group '" << rule.GetName() << "' to user '" << user->GetName() << "' for rule " << di; String group_name = rule.GetName(); UserGroup::Ptr group = UserGroup::GetByName(group_name); if (!group) { - Log(LogCritical, "UserGroup", "Invalid membership assignment. Group '" + group_name + "' does not exist."); + Log(LogCritical, "UserGroup") + << "Invalid membership assignment. Group '" << group_name << "' does not exist."; return false; } @@ -113,8 +113,9 @@ void UserGroup::RemoveMember(const User::Ptr& user) bool UserGroup::ResolveGroupMembership(User::Ptr const& user, bool add, int rstack) { if (add && rstack > 20) { - Log(LogWarning, "UserGroup", "Too many nested groups for group '" + GetName() + "': User '" + - user->GetName() + "' membership assignment failed."); + Log(LogWarning, "UserGroup") + << "Too many nested groups for group '" << GetName() << "': User '" + << user->GetName() << "' membership assignment failed."; return false; } diff --git a/lib/livestatus/attributefilter.cpp b/lib/livestatus/attributefilter.cpp index a62c2ae99..6260afef1 100644 --- a/lib/livestatus/attributefilter.cpp +++ b/lib/livestatus/attributefilter.cpp @@ -69,12 +69,14 @@ bool AttributeFilter::Apply(const Table::Ptr& table, const Value& row) boost::smatch what; ret = boost::regex_search(operand.GetData(), what, expr); } catch (boost::exception&) { - Log(LogWarning, "AttributeFilter", "Regex '" + m_Operand + " " + m_Operator + " " + Convert::ToString(value) + "' error."); + Log(LogWarning, "AttributeFilter") + << "Regex '" << m_Operand << " " << m_Operator << " " << value << "' error."; ret = false; } - //Log(LogDebug, "LivestatusListener/AttributeFilter", "Attribute filter '" + m_Operand + " " + m_Operator + " " + - // static_cast(value) + "' " + (ret ? "matches" : "doesn't match") + "." ); + //Log(LogDebug, "LivestatusListener/AttributeFilter") + // << "Attribute filter '" << m_Operand + " " << m_Operator << " " + // << value << "' " << (ret ? "matches" : "doesn't match") << "."; return ret; } else if (m_Operator == "=~") { @@ -87,12 +89,14 @@ bool AttributeFilter::Apply(const Table::Ptr& table, const Value& row) boost::smatch what; ret = boost::regex_search(operand.GetData(), what, expr); } catch (boost::exception&) { - Log(LogWarning, "AttributeFilter", "Regex '" + m_Operand + " " + m_Operator + " " + Convert::ToString(value) + "' error."); + Log(LogWarning, "AttributeFilter") + << "Regex '" << m_Operand << " " << m_Operator << " " << value << "' error."; ret = false; } - //Log(LogDebug, "LivestatusListener/AttributeFilter", "Attribute filter '" + m_Operand + " " + m_Operator + " " + - // static_cast(value) + "' " + (ret ? "matches" : "doesn't match") + "." ); + //Log(LogDebug, "LivestatusListener/AttributeFilter") + // << "Attribute filter '" << m_Operand << " " << m_Operator << " " + // << value << "' " << (ret ? "matches" : "doesn't match") << "."; return ret; } else if (m_Operator == "<") { diff --git a/lib/livestatus/livestatuslistener.cpp b/lib/livestatus/livestatuslistener.cpp index 190b4dc6b..a942e08fd 100644 --- a/lib/livestatus/livestatuslistener.cpp +++ b/lib/livestatus/livestatuslistener.cpp @@ -74,13 +74,15 @@ void LivestatusListener::Start(void) try { socket->Bind(GetBindHost(), GetBindPort(), AF_UNSPEC); } catch (std::exception&) { - Log(LogCritical, "LivestatusListener", "Cannot bind tcp socket on host '" + GetBindHost() + "' port '" + GetBindPort() + "'."); + Log(LogCritical, "LivestatusListener") + << "Cannot bind TCP socket on host '" << GetBindHost() << "' port '" << GetBindPort() << "'."; return; } boost::thread thread(boost::bind(&LivestatusListener::ServerThreadProc, this, socket)); thread.detach(); - Log(LogInformation, "LivestatusListener", "Created tcp socket listening on host '" + GetBindHost() + "' port '" + GetBindPort() + "'."); + Log(LogInformation, "LivestatusListener") + << "Created TCP socket listening on host '" << GetBindHost() << "' port '" << GetBindPort() << "'."; } else if (GetSocketType() == "unix") { #ifndef _WIN32 @@ -88,7 +90,8 @@ void LivestatusListener::Start(void) try { socket->Bind(GetSocketPath()); } catch (std::exception&) { - Log(LogCritical, "LivestatusListener", "Cannot bind unix socket in '" + GetSocketPath() + "'."); + Log(LogCritical, "LivestatusListener") + << "Cannot bind UNIX socket to '" << GetSocketPath() << "'."; return; } @@ -96,17 +99,17 @@ void LivestatusListener::Start(void) mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; if (chmod(GetSocketPath().CStr(), mode) < 0) { - std::ostringstream msgbuf; - msgbuf << "chmod() on unix socket '" << GetSocketPath() << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; - Log(LogCritical, "LivestatusListener", msgbuf.str()); + Log(LogCritical, "LivestatusListener") + << "chmod() on unix socket '" << GetSocketPath() << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; return; } boost::thread thread(boost::bind(&LivestatusListener::ServerThreadProc, this, socket)); thread.detach(); - Log(LogInformation, "LivestatusListener", "Created unix socket in '" + GetSocketPath() + "'."); + Log(LogInformation, "LivestatusListener") + << "Created UNIX socket in '" << GetSocketPath() << "'."; #else - /* no unix sockets on windows */ + /* no UNIX sockets on windows */ Log(LogCritical, "LivestatusListener", "Unix sockets are not supported on Windows."); return; #endif diff --git a/lib/livestatus/livestatusquery.cpp b/lib/livestatus/livestatusquery.cpp index 32776d155..44a522cfd 100644 --- a/lib/livestatus/livestatusquery.cpp +++ b/lib/livestatus/livestatusquery.cpp @@ -206,10 +206,12 @@ LivestatusQuery::LivestatusQuery(const std::vector& lines, const String& if (header == "Or" || header == "StatsOr") { filter = make_shared(); - Log(LogDebug, "LivestatusQuery", "Add OR filter for " + params + " column(s). " + Convert::ToString(deq.size()) + " filters available."); + Log(LogDebug, "LivestatusQuery") + << "Add OR filter for " << params << " column(s). " << deq.size() << " filters available."; } else { filter = make_shared(); - Log(LogDebug, "LivestatusQuery", "Add AND filter for " + params + " column(s). " + Convert::ToString(deq.size()) + " filters available."); + Log(LogDebug, "LivestatusQuery") + << "Add AND filter for " << params << " column(s). " << deq.size() << " filters available."; } if (num > deq.size()) { @@ -221,7 +223,8 @@ LivestatusQuery::LivestatusQuery(const std::vector& lines, const String& while (num > 0 && num--) { filter->AddSubFilter(deq.back()); - Log(LogDebug, "LivestatusQuery", "Add " + Convert::ToString(num) + " filter."); + Log(LogDebug, "LivestatusQuery") + << "Add " << num << " filter."; deq.pop_back(); if (&deq == &stats) aggregators.pop_back(); @@ -349,7 +352,8 @@ Filter::Ptr LivestatusQuery::ParseFilter(const String& params, unsigned long& fr } } - Log(LogDebug, "LivestatusQuery", "Parsed filter with attr: '" + attr + "' op: '" + op + "' val: '" + val + "'."); + Log(LogDebug, "LivestatusQuery") + << "Parsed filter with attr: '" << attr << "' op: '" << op << "' val: '" << val << "'."; return filter; } @@ -433,7 +437,8 @@ String LivestatusQuery::QuoteStringPython(const String& str) { void LivestatusQuery::ExecuteGetHelper(const Stream::Ptr& stream) { - Log(LogInformation, "LivestatusQuery", "Table: " + m_Table); + Log(LogInformation, "LivestatusQuery") + << "Table: " << m_Table; Table::Ptr table = Table::GetByName(m_Table, m_CompatLogPath, m_LogTimeFrom, m_LogTimeUntil); @@ -538,14 +543,16 @@ void LivestatusQuery::ExecuteCommandHelper(const Stream::Ptr& stream) l_ExternalCommands++; } - Log(LogInformation, "LivestatusQuery", "Executing command: " + m_Command); + Log(LogInformation, "LivestatusQuery") + << "Executing command: " << m_Command; ExternalCommandProcessor::Execute(m_Command); SendResponse(stream, LivestatusErrorOK, ""); } void LivestatusQuery::ExecuteErrorHelper(const Stream::Ptr& stream) { - Log(LogDebug, "LivestatusQuery", "ERROR: Code: '" + Convert::ToString(m_ErrorCode) + "' Message: '" + m_ErrorMessage + "'."); + Log(LogDebug, "LivestatusQuery") + << "ERROR: Code: '" << m_ErrorCode << "' Message: '" << m_ErrorMessage << "'."; SendResponse(stream, m_ErrorCode, m_ErrorMessage); } @@ -558,7 +565,7 @@ void LivestatusQuery::SendResponse(const Stream::Ptr& stream, int code, const St try { stream->Write(data.CStr(), data.GetLength()); } catch (const std::exception&) { - Log(LogCritical, "LivestatusQuery", "Cannot write to tcp socket."); + Log(LogCritical, "LivestatusQuery", "Cannot write to TCP socket."); } } } @@ -575,14 +582,15 @@ void LivestatusQuery::PrintFixed16(const Stream::Ptr& stream, int code, const St try { stream->Write(header.CStr(), header.GetLength()); } catch (const std::exception&) { - Log(LogCritical, "LivestatusQuery", "Cannot write to tcp socket."); + Log(LogCritical, "LivestatusQuery", "Cannot write to TCP socket."); } } bool LivestatusQuery::Execute(const Stream::Ptr& stream) { try { - Log(LogInformation, "LivestatusQuery", "Executing livestatus query: " + m_Verb); + Log(LogInformation, "LivestatusQuery") + << "Executing livestatus query: " << m_Verb; if (m_Verb == "GET") ExecuteGetHelper(stream); diff --git a/lib/livestatus/statehisttable.cpp b/lib/livestatus/statehisttable.cpp index 46ca67750..df2843bfa 100644 --- a/lib/livestatus/statehisttable.cpp +++ b/lib/livestatus/statehisttable.cpp @@ -117,7 +117,8 @@ void StateHistTable::UpdateLogEntries(const Dictionary::Ptr& log_entry_attrs, in state_hist_service_states->Add(state_hist_bag); - Log(LogDebug, "StateHistTable", "statehist: Adding new object '" + checkable->GetName() + "' to services cache."); + Log(LogDebug, "StateHistTable") + << "statehist: Adding new object '" << checkable->GetName() << "' to services cache."; } else { state_hist_service_states = m_CheckablesCache[checkable]; state_hist_bag = state_hist_service_states->Get(state_hist_service_states->GetLength()-1); /* fetch latest state from history */ @@ -173,8 +174,8 @@ void StateHistTable::UpdateLogEntries(const Dictionary::Ptr& log_entry_attrs, in state_hist_service_states->Add(state_hist_bag_new); - Log(LogDebug, "StateHistTable", "statehist: State change detected for object '" + - checkable->GetName() + "' in '" + log_line + "'."); + Log(LogDebug, "StateHistTable") + << "statehist: State change detected for object '" << checkable->GetName() << "' in '" << log_line << "'."; } break; case LogEntryTypeHostFlapping: @@ -257,7 +258,8 @@ String StateHistTable::GetPrefix(void) const void StateHistTable::FetchRows(const AddRowFunction& addRowFn) { - Log(LogDebug, "StateHistTable", "Pre-selecting log file from " + Convert::ToString(m_TimeFrom) + " until " + Convert::ToString(m_TimeUntil)); + Log(LogDebug, "StateHistTable") + << "Pre-selecting log file from " << m_TimeFrom << " until " << m_TimeUntil; /* create log file index */ LivestatusLogUtility::CreateLogIndex(m_CompatLogPath, m_LogFileIndex); diff --git a/lib/methods/pluginchecktask.cpp b/lib/methods/pluginchecktask.cpp index c4c260acb..dd7d6f526 100644 --- a/lib/methods/pluginchecktask.cpp +++ b/lib/methods/pluginchecktask.cpp @@ -58,9 +58,10 @@ void PluginCheckTask::ProcessFinishedHandler(const Checkable::Ptr& checkable, co { if (pr.ExitStatus > 3) { Process::Arguments parguments = Process::PrepareCommand(commandLine); - Log(LogWarning, "PluginCheckTask", "Check command for object '" + checkable->GetName() + "' (PID: " + Convert::ToString(pr.PID) + - ", arguments: " + Process::PrettyPrintArguments(parguments) + ") terminated with exit code " + - Convert::ToString(pr.ExitStatus) + ", output: " + pr.Output); + Log(LogWarning, "PluginCheckTask") + << "Check command for object '" << checkable->GetName() << "' (PID: " << pr.PID + << ", arguments: " << Process::PrettyPrintArguments(parguments) << ") terminated with exit code " + << pr.ExitStatus << ", output: " << pr.Output; } String output = pr.Output; diff --git a/lib/methods/plugineventtask.cpp b/lib/methods/plugineventtask.cpp index 345a81d48..5686edd93 100644 --- a/lib/methods/plugineventtask.cpp +++ b/lib/methods/plugineventtask.cpp @@ -56,8 +56,9 @@ void PluginEventTask::ProcessFinishedHandler(const Checkable::Ptr& checkable, co { if (pr.ExitStatus != 0) { Process::Arguments parguments = Process::PrepareCommand(commandLine); - Log(LogNotice, "PluginEventTask", "Event command for object '" + checkable->GetName() + "' (PID: " + Convert::ToString(pr.PID) + - ", arguments: " + Process::PrettyPrintArguments(parguments) + ") terminated with exit code " + - Convert::ToString(pr.ExitStatus) + ", output: " + pr.Output); + Log(LogNotice, "PluginEventTask") + << "Event command for object '" << checkable->GetName() << "' (PID: " << pr.PID + << ", arguments: " << Process::PrettyPrintArguments(parguments) << ") terminated with exit code " + << pr.ExitStatus << ", output: " << pr.Output; } } diff --git a/lib/methods/pluginnotificationtask.cpp b/lib/methods/pluginnotificationtask.cpp index 362c279de..a10c0beab 100644 --- a/lib/methods/pluginnotificationtask.cpp +++ b/lib/methods/pluginnotificationtask.cpp @@ -70,8 +70,9 @@ void PluginNotificationTask::ProcessFinishedHandler(const Checkable::Ptr& checka { if (pr.ExitStatus != 0) { Process::Arguments parguments = Process::PrepareCommand(commandLine); - Log(LogWarning, "PluginNotificationTask", "Notification command for object '" + checkable->GetName() + "' (PID: " + Convert::ToString(pr.PID) + - ", arguments: " + Process::PrettyPrintArguments(parguments) + ") terminated with exit code " + - Convert::ToString(pr.ExitStatus) + ", output: " + pr.Output); + Log(LogWarning, "PluginNotificationTask") + << "Notification command for object '" << checkable->GetName() << "' (PID: " << pr.PID + << ", arguments: " << Process::PrettyPrintArguments(parguments) << ") terminated with exit code " + << pr.ExitStatus << ", output: " << pr.Output; } } diff --git a/lib/notification/notificationcomponent.cpp b/lib/notification/notificationcomponent.cpp index c2da95cf9..522e7a6e1 100644 --- a/lib/notification/notificationcomponent.cpp +++ b/lib/notification/notificationcomponent.cpp @@ -112,15 +112,13 @@ void NotificationComponent::NotificationTimerHandler(void) } try { - Log(LogInformation, "NotificationComponent", "Sending reminder notification for object '" + checkable->GetName() + "'"); + Log(LogInformation, "NotificationComponent") + << "Sending reminder notification for object '" << checkable->GetName() << "'"; notification->BeginExecuteNotification(NotificationProblem, checkable->GetLastCheckResult(), false); } catch (const std::exception& ex) { - std::ostringstream msgbuf; - msgbuf << "Exception occured during notification for object '" - << GetName() << "': " << DiagnosticInformation(ex); - String message = msgbuf.str(); - - Log(LogWarning, "NotificationComponent", message); + Log(LogWarning, "NotificationComponent") + << "Exception occured during notification for object '" + << GetName() << "': " << DiagnosticInformation(ex); } } } diff --git a/lib/perfdata/graphitewriter.cpp b/lib/perfdata/graphitewriter.cpp index 18397905b..ac1ef3714 100644 --- a/lib/perfdata/graphitewriter.cpp +++ b/lib/perfdata/graphitewriter.cpp @@ -177,7 +177,8 @@ void GraphiteWriter::SendMetric(const String& prefix, const String& name, double std::ostringstream msgbuf; msgbuf << prefix << "." << name << " " << Convert::ToString(value) << " " << static_cast(Utility::GetTime()); - Log(LogDebug, "GraphiteWriter", "Add to metric list:'" + msgbuf.str() + "'."); + Log(LogDebug, "GraphiteWriter") + << "Add to metric list:'" << msgbuf.str() << "'."; // do not send \n to debug log msgbuf << "\n"; @@ -191,7 +192,8 @@ void GraphiteWriter::SendMetric(const String& prefix, const String& name, double try { m_Stream->Write(metric.CStr(), metric.GetLength()); } catch (const std::exception& ex) { - Log(LogCritical, "GraphiteWriter", "Cannot write to TCP socket on host '" + GetHost() + "' port '" + GetPort() + "'."); + Log(LogCritical, "GraphiteWriter") + << "Cannot write to TCP socket on host '" << GetHost() << "' port '" << GetPort() << "'."; m_Stream.reset(); } diff --git a/lib/perfdata/perfdatawriter.cpp b/lib/perfdata/perfdatawriter.cpp index 445f34fc2..05b4e059f 100644 --- a/lib/perfdata/perfdatawriter.cpp +++ b/lib/perfdata/perfdatawriter.cpp @@ -122,7 +122,8 @@ void PerfdataWriter::RotateFile(std::ofstream& output, const String& temp_path, output.open(temp_path.CStr()); if (!output.good()) - Log(LogWarning, "PerfdataWriter", "Could not open perfdata file '" + temp_path + "' for writing. Perfdata will be lost."); + Log(LogWarning, "PerfdataWriter") + << "Could not open perfdata file '" << temp_path << "' for writing. Perfdata will be lost."; } void PerfdataWriter::RotationTimerHandler(void) diff --git a/lib/remote/apiclient.cpp b/lib/remote/apiclient.cpp index 966a62f73..644bd1152 100644 --- a/lib/remote/apiclient.cpp +++ b/lib/remote/apiclient.cpp @@ -75,7 +75,8 @@ ConnectionRole ApiClient::GetRole(void) const void ApiClient::SendMessage(const Dictionary::Ptr& message) { if (m_WriteQueue.GetLength() > 20000) { - Log(LogWarning, "remote", "Closing connection for API identity '" + m_Identity + "': Too many queued messages."); + Log(LogWarning, "remote") + << "Closing connection for API identity '" << m_Identity << "': Too many queued messages."; Disconnect(); return; } @@ -93,11 +94,12 @@ void ApiClient::SendMessageSync(const Dictionary::Ptr& message) if (message->Get("method") != "log::SetLogPosition") m_Seen = Utility::GetTime(); } catch (const std::exception& ex) { - std::ostringstream info, debug; + std::ostringstream info; info << "Error while sending JSON-RPC message for identity '" << m_Identity << "'"; - debug << info.str() << std::endl << DiagnosticInformation(ex); - Log(LogWarning, "ApiClient", info.str()); - Log(LogDebug, "ApiClient", debug.str()); + Log(LogWarning, "ApiClient") + << info.str(); + Log(LogDebug, "ApiClient") + << info.str() << "\n" << DiagnosticInformation(ex); Disconnect(); } @@ -110,7 +112,8 @@ void ApiClient::Disconnect(void) void ApiClient::DisconnectSync(void) { - Log(LogWarning, "ApiClient", "API client disconnected for identity '" + m_Identity + "'"); + Log(LogWarning, "ApiClient") + << "API client disconnected for identity '" << m_Identity << "'"; if (m_Endpoint) m_Endpoint->RemoveClient(GetSelf()); @@ -168,7 +171,8 @@ bool ApiClient::ProcessMessage(void) String method = message->Get("method"); - Log(LogNotice, "ApiClient", "Received '" + method + "' message from '" + m_Identity + "'"); + Log(LogNotice, "ApiClient") + << "Received '" << method << "' message from '" << m_Identity << "'"; Dictionary::Ptr resultMessage = make_shared(); diff --git a/lib/remote/apilistener.cpp b/lib/remote/apilistener.cpp index ca9b5bdcc..9ec2f5e76 100644 --- a/lib/remote/apilistener.cpp +++ b/lib/remote/apilistener.cpp @@ -293,13 +293,8 @@ void ApiListener::NewClientHandler(const Socket::Ptr& client, ConnectionRole rol bool verify_ok = tlsStream->IsVerifyOK(); - std::ostringstream msgbuf; - msgbuf << "New client connection for identity '" << identity << "'"; - - if (!verify_ok) - msgbuf << " (unauthenticated)"; - - Log(LogInformation, "ApiListener", msgbuf.str()); + Log(LogInformation, "ApiListener") + << "New client connection for identity '" << identity << "'" << (verify_ok ? "" : " (unauthenticated"); Endpoint::Ptr endpoint;