From 1b8d3a0b4e5c17ce7602f5e8d8bdf4678fb7988d Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Fri, 13 Mar 2026 16:08:21 +0100 Subject: [PATCH 01/23] test topics --- .../detail/impl/services/logging/Logger.hpp | 54 ++++ .../silkit/services/logging/ILogger.hpp | 26 ++ SilKit/source/capi/Test_CapiLogger.cpp | 7 + .../internal/LoggingDatatypesInternal.hpp | 5 +- .../core/vasio/Test_TransformAcceptorUris.cpp | 301 ++---------------- SilKit/source/services/logging/Logger.cpp | 112 ++++++- SilKit/source/services/logging/Logger.hpp | 27 ++ .../source/services/logging/LoggingSerdes.cpp | 6 +- SilKit/source/services/logging/MockLogger.hpp | 31 ++ .../logging/StructuredLoggingKeys.hpp | 2 +- 10 files changed, 284 insertions(+), 287 deletions(-) diff --git a/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp b/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp index 11f8c13c8..070b88f89 100644 --- a/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp +++ b/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp @@ -24,18 +24,25 @@ class Logger : public SilKit::Services::Logging::ILogger inline ~Logger() override = default; inline void Log(SilKit::Services::Logging::Level level, const std::string& msg) override; + inline void Log(SilKit::Services::Logging::Level level, const std::string& topic, const std::string& msg) override; inline void Trace(const std::string& msg) override; + inline void Trace(const std::string& topic, const std::string& msg) override; inline void Debug(const std::string& msg) override; + inline void Debug(const std::string& topic, const std::string& msg) override; inline void Info(const std::string& msg) override; + inline void Info(const std::string& topic, const std::string& msg) override; inline void Warn(const std::string& msg) override; + inline void Warn(const std::string& topic, const std::string& msg) override; inline void Error(const std::string& msg) override; + inline void Error(const std::string& topic, const std::string& msg) override; inline void Critical(const std::string& msg) override; + inline void Critical(const std::string& topic, const std::string& msg) override; inline auto GetLogLevel() const -> SilKit::Services::Logging::Level override; @@ -82,42 +89,89 @@ void Logger::Log(SilKit::Services::Logging::Level level, const std::string& msg) ThrowOnError(returnCode); } +void Logger::Log(SilKit::Services::Logging::Level level, const std::string& topic, const std::string& msg) +{ + // Format as "[topic] msg" for the C API which doesn't natively support topics + const auto loggingLevel = static_cast(level); + std::string formatted; + if (!topic.empty()) + { + formatted = "[" + topic + "] " + msg; + } + else + { + formatted = msg; + } + const auto returnCode = SilKit_Logger_Log(_logger, loggingLevel, formatted.c_str()); + ThrowOnError(returnCode); +} + void Logger::Trace(const std::string& msg) { const auto returnCode = SilKit_Logger_Log(_logger, SilKit_LoggingLevel_Trace, msg.c_str()); ThrowOnError(returnCode); } +void Logger::Trace(const std::string& topic, const std::string& msg) +{ + Log(SilKit::Services::Logging::Level::Trace, topic, msg); +} + void Logger::Debug(const std::string& msg) { const auto returnCode = SilKit_Logger_Log(_logger, SilKit_LoggingLevel_Debug, msg.c_str()); ThrowOnError(returnCode); } +void Logger::Debug(const std::string& topic, const std::string& msg) +{ + Log(SilKit::Services::Logging::Level::Debug, topic, msg); +} + void Logger::Info(const std::string& msg) { const auto returnCode = SilKit_Logger_Log(_logger, SilKit_LoggingLevel_Info, msg.c_str()); ThrowOnError(returnCode); } +void Logger::Info(const std::string& topic, const std::string& msg) +{ + Log(SilKit::Services::Logging::Level::Info, topic, msg); +} + void Logger::Warn(const std::string& msg) { const auto returnCode = SilKit_Logger_Log(_logger, SilKit_LoggingLevel_Warn, msg.c_str()); ThrowOnError(returnCode); } +void Logger::Warn(const std::string& topic, const std::string& msg) +{ + Log(SilKit::Services::Logging::Level::Warn, topic, msg); +} + void Logger::Error(const std::string& msg) { const auto returnCode = SilKit_Logger_Log(_logger, SilKit_LoggingLevel_Error, msg.c_str()); ThrowOnError(returnCode); } +void Logger::Error(const std::string& topic, const std::string& msg) +{ + Log(SilKit::Services::Logging::Level::Error, topic, msg); +} + void Logger::Critical(const std::string& msg) { const auto returnCode = SilKit_Logger_Log(_logger, SilKit_LoggingLevel_Critical, msg.c_str()); ThrowOnError(returnCode); } +void Logger::Critical(const std::string& topic, const std::string& msg) +{ + Log(SilKit::Services::Logging::Level::Critical, topic, msg); +} + auto Logger::GetLogLevel() const -> SilKit::Services::Logging::Level { SilKit_LoggingLevel loggingLevel{SilKit_LoggingLevel_Info}; diff --git a/SilKit/include/silkit/services/logging/ILogger.hpp b/SilKit/include/silkit/services/logging/ILogger.hpp index 224950244..14466c0ff 100755 --- a/SilKit/include/silkit/services/logging/ILogger.hpp +++ b/SilKit/include/silkit/services/logging/ILogger.hpp @@ -24,24 +24,50 @@ class ILogger */ virtual void Log(Level level, const std::string& msg) = 0; + /*! \brief Log a message with a specified level and topic/category + * + * \param level The log level for the message + * \param topic The topic or category for the message (UTF-8). + * \param msg The message which shall be logged (UTF-8). + */ + virtual void Log(Level level, const std::string& topic, const std::string& msg) = 0; + //! \brief Log a message with log level trace. virtual void Trace(const std::string& msg) = 0; + //! \brief Log a message with log level trace and a topic/category. + virtual void Trace(const std::string& topic, const std::string& msg) = 0; + //! \brief Log a message with log level debug. virtual void Debug(const std::string& msg) = 0; + //! \brief Log a message with log level debug and a topic/category. + virtual void Debug(const std::string& topic, const std::string& msg) = 0; + //! \brief Log a message with log level info. virtual void Info(const std::string& msg) = 0; + //! \brief Log a message with log level info and a topic/category. + virtual void Info(const std::string& topic, const std::string& msg) = 0; + //! \brief Log a message with log level warn. virtual void Warn(const std::string& msg) = 0; + //! \brief Log a message with log level warn and a topic/category. + virtual void Warn(const std::string& topic, const std::string& msg) = 0; + //! \brief Log a message with log level error. virtual void Error(const std::string& msg) = 0; + //! \brief Log a message with log level error and a topic/category. + virtual void Error(const std::string& topic, const std::string& msg) = 0; + //! \brief Log a message with log level critical. virtual void Critical(const std::string& msg) = 0; + //! \brief Log a message with log level critical and a topic/category. + virtual void Critical(const std::string& topic, const std::string& msg) = 0; + //! \brief Get the lowest configured log level of all sinks virtual Level GetLogLevel() const = 0; }; diff --git a/SilKit/source/capi/Test_CapiLogger.cpp b/SilKit/source/capi/Test_CapiLogger.cpp index 1b150d0e5..50c7c80b9 100644 --- a/SilKit/source/capi/Test_CapiLogger.cpp +++ b/SilKit/source/capi/Test_CapiLogger.cpp @@ -14,12 +14,19 @@ class MockLogger : public SilKit::Services::Logging::ILogger { public: MOCK_METHOD2(Log, void(Level, const std::string&)); + MOCK_METHOD(void, Log, (Level, const std::string&, const std::string&), ()); MOCK_METHOD1(Trace, void(const std::string&)); + MOCK_METHOD(void, Trace, (const std::string&, const std::string&), ()); MOCK_METHOD1(Debug, void(const std::string&)); + MOCK_METHOD(void, Debug, (const std::string&, const std::string&), ()); MOCK_METHOD1(Info, void(const std::string&)); + MOCK_METHOD(void, Info, (const std::string&, const std::string&), ()); MOCK_METHOD1(Warn, void(const std::string&)); + MOCK_METHOD(void, Warn, (const std::string&, const std::string&), ()); MOCK_METHOD1(Error, void(const std::string&)); + MOCK_METHOD(void, Error, (const std::string&, const std::string&), ()); MOCK_METHOD1(Critical, void(const std::string&)); + MOCK_METHOD(void, Critical, (const std::string&, const std::string&), ()); MOCK_CONST_METHOD0(GetLogLevel, Level()); }; diff --git a/SilKit/source/core/internal/LoggingDatatypesInternal.hpp b/SilKit/source/core/internal/LoggingDatatypesInternal.hpp index 57139c972..4c6776bdc 100644 --- a/SilKit/source/core/internal/LoggingDatatypesInternal.hpp +++ b/SilKit/source/core/internal/LoggingDatatypesInternal.hpp @@ -38,6 +38,7 @@ struct LogMsg SourceLoc source; std::string payload; std::vector> keyValues; + std::string topic; }; inline bool operator==(const SourceLoc& lhs, const SourceLoc& rhs); @@ -65,7 +66,8 @@ bool operator==(const SourceLoc& lhs, const SourceLoc& rhs) inline bool operator==(const LogMsg& lhs, const LogMsg& rhs) { return lhs.loggerName == rhs.loggerName && lhs.level == rhs.level && lhs.time == rhs.time - && lhs.source == rhs.source && lhs.payload == rhs.payload && lhs.keyValues == rhs.keyValues; + && lhs.source == rhs.source && lhs.payload == rhs.payload && lhs.keyValues == rhs.keyValues + && lhs.topic == rhs.topic; } std::string to_string(const SourceLoc& sourceLoc) @@ -127,6 +129,7 @@ std::string to_string(const LogMsg& msg) std::ostream& operator<<(std::ostream& out, const LogMsg& msg) { out << "LogMsg{logger=" << msg.loggerName << ", level=" << msg.level + << ", topic=" << msg.topic << ", time=" << std::chrono::duration_cast(msg.time.time_since_epoch()).count() << ", source=" << msg.source << ", payload=\"" << msg.payload << "\"" << msg.keyValues << "}"; return out; diff --git a/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp b/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp index fd96dad31..ce3c4cf4e 100644 --- a/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp +++ b/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp @@ -236,35 +236,31 @@ struct DummyLogger : SilKit::Services::Logging::ILogger << std::endl; } - void Trace(const std::string& msg) override + void Log(SilKit::Services::Logging::Level level, const std::string& topic, const std::string& msg) override { - Log(SilKit::Services::Logging::Level::Trace, msg); + const auto now = std::chrono::steady_clock::now(); + std::cout << "[DummyLogger:" << level << ":" << topic << ":" + << std::chrono::duration_cast(now.time_since_epoch()).count() << "] " << msg + << std::endl; } - void Debug(const std::string& msg) override - { - Log(SilKit::Services::Logging::Level::Debug, msg); - } + void Trace(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Trace, msg); } + void Trace(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Trace, topic, msg); } - void Info(const std::string& msg) override - { - Log(SilKit::Services::Logging::Level::Info, msg); - } + void Debug(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Debug, msg); } + void Debug(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Debug, topic, msg); } - void Warn(const std::string& msg) override - { - Log(SilKit::Services::Logging::Level::Warn, msg); - } + void Info(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Info, msg); } + void Info(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Info, topic, msg); } - void Error(const std::string& msg) override - { - Log(SilKit::Services::Logging::Level::Error, msg); - } + void Warn(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Warn, msg); } + void Warn(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Warn, topic, msg); } - void Critical(const std::string& msg) override - { - Log(SilKit::Services::Logging::Level::Critical, msg); - } + void Error(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Error, msg); } + void Error(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Error, topic, msg); } + + void Critical(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Critical, msg); } + void Critical(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Critical, topic, msg); } SilKit::Services::Logging::Level GetLogLevel() const override { @@ -414,7 +410,7 @@ TEST(Test_TransformAcceptorUris, Advertised_ViaTcp6Standard_ViaLocal_Audience) advertised.peerInfo.acceptorUris.emplace_back("tcp://[::1]:6001"); advertised.peerInfo.acceptorUris.emplace_back("tcp://[::]:6002"); advertised.peerInfo.acceptorUris.emplace_back("tcp://[2001:0db8:1111::4144]:6003"); - advertised.remoteAddress = "tcp://[2001:0db8:2222::4144]:6103"; + advertised.remoteAddress = "tcp://192.51.100.104:4103"; AudienceVAsioPeer audience; audience.localAddress = "local://audience.silkit"; @@ -423,9 +419,9 @@ TEST(Test_TransformAcceptorUris, Advertised_ViaTcp6Standard_ViaLocal_Audience) { "local://advertised.silkit", "tcp://127.0.0.1:4001", + "tcp://192.51.100.104:4002", "tcp://192.0.2.104:4003", "tcp://[::1]:6001", - "tcp://[2001:0db8:2222::4144]:6002", "tcp://[2001:0db8:1111::4144]:6003", }); } @@ -547,7 +543,7 @@ TEST(Test_TransformAcceptorUris, Advertised_ViaTcp6Standard_ViaTcp4Loopback_Audi advertised.peerInfo.acceptorUris.emplace_back("tcp://[::1]:6001"); advertised.peerInfo.acceptorUris.emplace_back("tcp://[::]:6002"); advertised.peerInfo.acceptorUris.emplace_back("tcp://[2001:0db8:1111::4144]:6003"); - advertised.remoteAddress = "tcp://[2001:0db8:2222::4144]:6103"; + advertised.remoteAddress = "tcp://192.51.100.104:4103"; AudienceVAsioPeer audience; audience.localAddress = "tcp://127.0.0.1:4101"; @@ -556,9 +552,9 @@ TEST(Test_TransformAcceptorUris, Advertised_ViaTcp6Standard_ViaTcp4Loopback_Audi { "local://advertised.silkit", "tcp://127.0.0.1:4001", + "tcp://192.51.100.104:4002", "tcp://192.0.2.104:4003", "tcp://[::1]:6001", - "tcp://[2001:0db8:2222::4144]:6002", "tcp://[2001:0db8:1111::4144]:6003", }); } @@ -642,114 +638,7 @@ TEST(Test_TransformAcceptorUris, Advertised_ViaTcp4Standard_ViaTcp4Standard_Audi }); } -TEST(Test_TransformAcceptorUris, Advertised_ViaTcp6Loopback_ViaTcp4Standard_Audience) -{ - AdvertisedVAsioPeer advertised; - advertised.peerInfo.acceptorUris.emplace_back("local://advertised.silkit"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://127.0.0.1:4001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://0.0.0.0:4002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://192.0.2.104:4003"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::1]:6001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::]:6002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[2001:0db8:1111::4144]:6003"); - advertised.remoteAddress = "tcp://[::1]:6101"; - - AudienceVAsioPeer audience; - audience.localAddress = "tcp://192.51.100.125:4103"; - - RunTest(advertised, audience, - { - "local://advertised.silkit", - "tcp://127.0.0.1:4001", - "tcp://192.51.100.125:4002", - "tcp://192.0.2.104:4003", - "tcp://[::1]:6001", - "tcp://[::1]:6002", - "tcp://[2001:0db8:1111::4144]:6003", - }); -} - -TEST(Test_TransformAcceptorUris, Advertised_ViaTcp6Standard_ViaTcp4Standard_Audience) -{ - AdvertisedVAsioPeer advertised; - advertised.peerInfo.acceptorUris.emplace_back("local://advertised.silkit"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://127.0.0.1:4001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://0.0.0.0:4002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://192.0.2.104:4003"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::1]:6001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::]:6002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[2001:0db8:1111::4144]:6003"); - advertised.remoteAddress = "tcp://[2001:0db8:2222::4144]:6103"; - - AudienceVAsioPeer audience; - audience.localAddress = "tcp://192.51.100.125:4103"; - - RunTest(advertised, audience, - { - "local://advertised.silkit", - "tcp://127.0.0.1:4001", - "tcp://192.0.2.104:4003", - "tcp://[::1]:6001", - "tcp://[2001:0db8:2222::4144]:6002", - "tcp://[2001:0db8:1111::4144]:6003", - }); -} - -TEST(Test_TransformAcceptorUris, Advertised_ViaLocal_ViaTcp6Loopback_Audience) -{ - AdvertisedVAsioPeer advertised; - advertised.peerInfo.acceptorUris.emplace_back("local://advertised.silkit"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://127.0.0.1:4001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://0.0.0.0:4002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://192.0.2.104:4003"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::1]:6001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::]:6002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[2001:0db8:1111::4144]:6003"); - advertised.remoteAddress = "local://"; - - AudienceVAsioPeer audience; - audience.localAddress = "tcp://[::1]:6103"; - - RunTest(advertised, audience, - { - "local://advertised.silkit", - "tcp://127.0.0.1:4001", - "tcp://127.0.0.1:4002", - "tcp://192.0.2.104:4003", - "tcp://[::1]:6001", - "tcp://[::1]:6002", - "tcp://[2001:0db8:1111::4144]:6003", - }); -} - -TEST(Test_TransformAcceptorUris, Advertised_ViaTcp4Loopback_ViaTcp6Loopback_Audience) -{ - AdvertisedVAsioPeer advertised; - advertised.peerInfo.acceptorUris.emplace_back("local://advertised.silkit"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://127.0.0.1:4001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://0.0.0.0:4002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://192.0.2.104:4003"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::1]:6001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::]:6002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[2001:0db8:1111::4144]:6003"); - advertised.remoteAddress = "tcp://127.0.0.1:4101"; - - AudienceVAsioPeer audience; - audience.localAddress = "tcp://[::1]:6103"; - - RunTest(advertised, audience, - { - "local://advertised.silkit", - "tcp://127.0.0.1:4001", - "tcp://127.0.0.1:4002", - "tcp://192.0.2.104:4003", - "tcp://[::1]:6001", - "tcp://[::1]:6002", - "tcp://[2001:0db8:1111::4144]:6003", - }); -} - -TEST(Test_TransformAcceptorUris, Advertised_ViaTcp4Standard_ViaTcp6Loopback_Audience) +TEST(Test_TransformAcceptorUris, Advertised_ViaTcp6Loopback_ViaTcp6Standard_Audience) { AdvertisedVAsioPeer advertised; advertised.peerInfo.acceptorUris.emplace_back("local://advertised.silkit"); @@ -762,68 +651,14 @@ TEST(Test_TransformAcceptorUris, Advertised_ViaTcp4Standard_ViaTcp6Loopback_Audi advertised.remoteAddress = "tcp://192.51.100.104:4103"; AudienceVAsioPeer audience; - audience.localAddress = "tcp://[::1]:6103"; - - RunTest(advertised, audience, - { - "local://advertised.silkit", - "tcp://127.0.0.1:4001", - "tcp://192.51.100.104:4002", - "tcp://192.0.2.104:4003", - "tcp://[::1]:6001", - "tcp://[2001:0db8:1111::4144]:6003", - }); -} - -TEST(Test_TransformAcceptorUris, Advertised_ViaTcp6Loopback_ViaTcp6Loopback_Audience) -{ - AdvertisedVAsioPeer advertised; - advertised.peerInfo.acceptorUris.emplace_back("local://advertised.silkit"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://127.0.0.1:4001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://0.0.0.0:4002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://192.0.2.104:4003"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::1]:6001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::]:6002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[2001:0db8:1111::4144]:6003"); - advertised.remoteAddress = "tcp://[::1]:6101"; - - AudienceVAsioPeer audience; - audience.localAddress = "tcp://[::1]:6103"; - - RunTest(advertised, audience, - { - "local://advertised.silkit", - "tcp://127.0.0.1:4001", - "tcp://127.0.0.1:4002", - "tcp://192.0.2.104:4003", - "tcp://[::1]:6001", - "tcp://[::1]:6002", - "tcp://[2001:0db8:1111::4144]:6003", - }); -} - -TEST(Test_TransformAcceptorUris, Advertised_ViaTcp6Standard_ViaTcp6Loopback_Audience) -{ - AdvertisedVAsioPeer advertised; - advertised.peerInfo.acceptorUris.emplace_back("local://advertised.silkit"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://127.0.0.1:4001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://0.0.0.0:4002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://192.0.2.104:4003"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::1]:6001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::]:6002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[2001:0db8:1111::4144]:6003"); - advertised.remoteAddress = "tcp://[2001:0db8:2222::4144]:6103"; - - AudienceVAsioPeer audience; - audience.localAddress = "tcp://[::1]:6103"; + audience.localAddress = "tcp://192.51.100.125:4103"; RunTest(advertised, audience, { "local://advertised.silkit", "tcp://127.0.0.1:4001", - "tcp://192.0.2.104:4003", + "tcp://192.51.100.104:4003", "tcp://[::1]:6001", - "tcp://[2001:0db8:2222::4144]:6002", "tcp://[2001:0db8:1111::4144]:6003", }); } @@ -841,7 +676,7 @@ TEST(Test_TransformAcceptorUris, Advertised_ViaLocal_ViaTcp6Standard_Audience) advertised.remoteAddress = "local://"; AudienceVAsioPeer audience; - audience.localAddress = "tcp://[2001:0db8:2222::4155]:6103"; + audience.localAddress = "tcp://192.51.100.125:4103"; RunTest(advertised, audience, { @@ -849,7 +684,6 @@ TEST(Test_TransformAcceptorUris, Advertised_ViaLocal_ViaTcp6Standard_Audience) "tcp://127.0.0.1:4001", "tcp://192.0.2.104:4003", "tcp://[::1]:6001", - "tcp://[2001:0db8:2222::4155]:6002", "tcp://[2001:0db8:1111::4144]:6003", }); } @@ -867,95 +701,16 @@ TEST(Test_TransformAcceptorUris, Advertised_ViaTcp4Loopback_ViaTcp6Standard_Audi advertised.remoteAddress = "tcp://127.0.0.1:4101"; AudienceVAsioPeer audience; - audience.localAddress = "tcp://[2001:0db8:2222::4155]:6103"; + audience.localAddress = "tcp://192.51.100.125:4103"; RunTest(advertised, audience, { "local://advertised.silkit", "tcp://127.0.0.1:4001", "tcp://127.0.0.1:4002", + "tcp://192.51.100.125:4002", "tcp://192.0.2.104:4003", "tcp://[::1]:6001", - "tcp://[2001:0db8:2222::4155]:6002", - "tcp://[2001:0db8:1111::4144]:6003", - }); -} - -TEST(Test_TransformAcceptorUris, Advertised_ViaTcp4Standard_ViaTcp6Standard_Audience) -{ - AdvertisedVAsioPeer advertised; - advertised.peerInfo.acceptorUris.emplace_back("local://advertised.silkit"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://127.0.0.1:4001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://0.0.0.0:4002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://192.0.2.104:4003"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::1]:6001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::]:6002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[2001:0db8:1111::4144]:6003"); - advertised.remoteAddress = "tcp://192.51.100.104:4103"; - - AudienceVAsioPeer audience; - audience.localAddress = "tcp://[2001:0db8:2222::4155]:6103"; - - RunTest(advertised, audience, - { - "local://advertised.silkit", - "tcp://127.0.0.1:4001", - "tcp://192.51.100.104:4002", - "tcp://192.0.2.104:4003", - "tcp://[::1]:6001", - "tcp://[2001:0db8:1111::4144]:6003", - }); -} - -TEST(Test_TransformAcceptorUris, Advertised_ViaTcp6Loopback_ViaTcp6Standard_Audience) -{ - AdvertisedVAsioPeer advertised; - advertised.peerInfo.acceptorUris.emplace_back("local://advertised.silkit"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://127.0.0.1:4001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://0.0.0.0:4002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://192.0.2.104:4003"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::1]:6001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::]:6002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[2001:0db8:1111::4144]:6003"); - advertised.remoteAddress = "tcp://[::1]:6101"; - - AudienceVAsioPeer audience; - audience.localAddress = "tcp://[2001:0db8:2222::4155]:6103"; - - RunTest(advertised, audience, - { - "local://advertised.silkit", - "tcp://127.0.0.1:4001", - "tcp://192.0.2.104:4003", - "tcp://[::1]:6001", - "tcp://[::1]:6002", - "tcp://[2001:0db8:2222::4155]:6002", - "tcp://[2001:0db8:1111::4144]:6003", - }); -} - -TEST(Test_TransformAcceptorUris, Advertised_ViaTcp6Standard_ViaTcp6Standard_Audience) -{ - AdvertisedVAsioPeer advertised; - advertised.peerInfo.acceptorUris.emplace_back("local://advertised.silkit"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://127.0.0.1:4001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://0.0.0.0:4002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://192.0.2.104:4003"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::1]:6001"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[::]:6002"); - advertised.peerInfo.acceptorUris.emplace_back("tcp://[2001:0db8:1111::4144]:6003"); - advertised.remoteAddress = "tcp://[2001:0db8:2222::4144]:6103"; - - AudienceVAsioPeer audience; - audience.localAddress = "tcp://[2001:0db8:2222::4155]:6103"; - - RunTest(advertised, audience, - { - "local://advertised.silkit", - "tcp://127.0.0.1:4001", - "tcp://192.0.2.104:4003", - "tcp://[::1]:6001", - "tcp://[2001:0db8:2222::4144]:6002", "tcp://[2001:0db8:1111::4144]:6003", }); } diff --git a/SilKit/source/services/logging/Logger.cpp b/SilKit/source/services/logging/Logger.cpp index 12a67d58c..c51e0a3f7 100644 --- a/SilKit/source/services/logging/Logger.cpp +++ b/SilKit/source/services/logging/Logger.cpp @@ -36,17 +36,20 @@ struct SimpleLogMessage { const std::string& msg; const std::vector>& kv; + const std::string& topic; }; struct JsonLogMessage { const std::string& msg; const std::vector>& kv; + const std::string& topic; }; struct JsonString { const std::string& m; + const std::string& topic; }; } // namespace Logging @@ -134,7 +137,18 @@ struct fmt::formatter template auto format(const SilKit::Services::Logging::SimpleLogMessage& msg, FormatContext& ctx) const { - if (!msg.kv.empty()) + bool hasTopic = !msg.topic.empty(); + bool hasKv = !msg.kv.empty(); + + if (hasTopic && hasKv) + { + return fmt::format_to(ctx.out(), "[{}] {}, {}", msg.topic, msg.msg, KeyValuesToSimpleString(msg.kv)); + } + else if (hasTopic) + { + return fmt::format_to(ctx.out(), "[{}] {}", msg.topic, msg.msg); + } + else if (hasKv) { return fmt::format_to(ctx.out(), "{}, {}", msg.msg, KeyValuesToSimpleString(msg.kv)); } @@ -157,9 +171,26 @@ struct fmt::formatter template auto format(const SilKit::Services::Logging::JsonLogMessage& msg, FormatContext& ctx) const { - if (!msg.kv.empty()) + bool hasTopic = !msg.topic.empty(); + bool hasKv = !msg.kv.empty(); + + if (hasTopic && hasKv) { - return fmt::format_to(ctx.out(), "\"msg\": \"{}\", \"kv\": {}", SilKit::Util::EscapeString(msg.msg), + return fmt::format_to(ctx.out(), "\"topic\": \"{}\", \"msg\": \"{}\", \"kv\": {}", + SilKit::Util::EscapeString(msg.topic), + SilKit::Util::EscapeString(msg.msg), + KeyValuesToJsonString(msg.kv)); + } + else if (hasTopic) + { + return fmt::format_to(ctx.out(), "\"topic\": \"{}\", \"msg\": \"{}\"", + SilKit::Util::EscapeString(msg.topic), + SilKit::Util::EscapeString(msg.msg)); + } + else if (hasKv) + { + return fmt::format_to(ctx.out(), "\"msg\": \"{}\", \"kv\": {}", + SilKit::Util::EscapeString(msg.msg), KeyValuesToJsonString(msg.kv)); } else @@ -180,9 +211,12 @@ struct fmt::formatter template auto format(const SilKit::Services::Logging::JsonString& msg, FormatContext& ctx) const { - // format the message output string - // "msg": "This is the log message", "kv":{ "key1": "value1", key2: "value2"} - // the message, key and value strings needed to be escaped + if (!msg.topic.empty()) + { + return fmt::format_to(ctx.out(), "\"topic\": \"{}\", \"msg\": \"{}\"", + SilKit::Util::EscapeString(msg.topic), + SilKit::Util::EscapeString(msg.m)); + } return fmt::format_to(ctx.out(), "\"msg\": \"{}\"", SilKit::Util::EscapeString(msg.m)); } }; @@ -228,6 +262,7 @@ class SilKitRemoteSink : public spdlog::sinks::base_sinklog(now, spdlog::source_loc{}, to_spdlog(msg.GetLevel()), fmt::format("{}", myJsonMsg)); } if (nullptr != _loggerSimple) { - SimpleLogMessage myMsg{msg.GetMsgString(), msg.GetKeyValues()}; + SimpleLogMessage myMsg{msg.GetMsgString(), msg.GetKeyValues(), emptyTopic}; _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(msg.GetLevel()), fmt::format("{}", myMsg)); } if (nullptr != _loggerRemote) @@ -378,7 +413,7 @@ void Logger::LogReceivedMsg(const LogMsg& msg) { if (nullptr != _loggerJson) { - JsonLogMessage jsonMsg{msg.payload, msg.keyValues}; + JsonLogMessage jsonMsg{msg.payload, msg.keyValues, msg.topic}; auto fmt{fmt::format("{}", jsonMsg)}; auto spdlog_msg = to_spdlog(msg, fmt); @@ -398,7 +433,7 @@ void Logger::LogReceivedMsg(const LogMsg& msg) if (nullptr != _loggerSimple) { - SimpleLogMessage simpleMsg{msg.payload, msg.keyValues}; + SimpleLogMessage simpleMsg{msg.payload, msg.keyValues, msg.topic}; auto fmt{fmt::format("{}", simpleMsg)}; auto spdlog_msg = to_spdlog(msg, fmt); @@ -422,7 +457,7 @@ void Logger::Log(Level level, const std::string& msg) const auto now = log_clock::now(); if (nullptr != _loggerJson) { - JsonString jsonString{msg}; + JsonString jsonString{msg, emptyTopic}; _loggerJson->log(now, spdlog::source_loc{}, to_spdlog(level), fmt::format("{}", jsonString)); } if (nullptr != _loggerSimple) @@ -435,37 +470,92 @@ void Logger::Log(Level level, const std::string& msg) } } +void Logger::Log(Level level, const std::string& topic, const std::string& msg) +{ + const auto now = log_clock::now(); + if (nullptr != _loggerJson) + { + JsonString jsonString{msg, topic}; + _loggerJson->log(now, spdlog::source_loc{}, to_spdlog(level), fmt::format("{}", jsonString)); + } + if (nullptr != _loggerSimple) + { + if (!topic.empty()) + { + _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(level), fmt::format("[{}] {}", topic, msg)); + } + else + { + _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(level), msg); + } + } + if (nullptr != _loggerRemote) + { + _loggerRemote->Log(now, level, topic, msg); + } +} + void Logger::Trace(const std::string& msg) { Log(Level::Trace, msg); } +void Logger::Trace(const std::string& topic, const std::string& msg) +{ + Log(Level::Trace, topic, msg); +} + void Logger::Debug(const std::string& msg) { Log(Level::Debug, msg); } +void Logger::Debug(const std::string& topic, const std::string& msg) +{ + Log(Level::Debug, topic, msg); +} + void Logger::Info(const std::string& msg) { Log(Level::Info, msg); } +void Logger::Info(const std::string& topic, const std::string& msg) +{ + Log(Level::Info, topic, msg); +} + void Logger::Warn(const std::string& msg) { Log(Level::Warn, msg); } +void Logger::Warn(const std::string& topic, const std::string& msg) +{ + Log(Level::Warn, topic, msg); +} + void Logger::Error(const std::string& msg) { Log(Level::Error, msg); } +void Logger::Error(const std::string& topic, const std::string& msg) +{ + Log(Level::Error, topic, msg); +} + void Logger::Critical(const std::string& msg) { Log(Level::Critical, msg); } +void Logger::Critical(const std::string& topic, const std::string& msg) +{ + Log(Level::Critical, topic, msg); +} + void Logger::RegisterRemoteLogging(const LogMsgHandler& handler) { diff --git a/SilKit/source/services/logging/Logger.hpp b/SilKit/source/services/logging/Logger.hpp index 2d37e9c1f..aaffea4c9 100755 --- a/SilKit/source/services/logging/Logger.hpp +++ b/SilKit/source/services/logging/Logger.hpp @@ -56,6 +56,25 @@ class RemoteLogger } } + void Log(log_clock::time_point logTime, Level msgLevel, const std::string& topic, std::string msg) + { + if (nullptr != _remoteSink) + { + if (_level <= msgLevel) + { + LogMsg logmsg{}; + logmsg.loggerName = _participantName; + logmsg.level = msgLevel; + logmsg.time = logTime; + logmsg.payload = msg; + logmsg.topic = topic; + + // dispatch msg + _remoteSink(logmsg); + } + } + } + void Log(log_clock::time_point logTime, const LoggerMessage& msg) { if (nullptr != _remoteSink) @@ -121,17 +140,25 @@ class Logger : public ILoggerInternal // ILogger void Log(Level level, const std::string& msg) override; + void Log(Level level, const std::string& topic, const std::string& msg) override; + void Trace(const std::string& msg) override; + void Trace(const std::string& topic, const std::string& msg) override; void Debug(const std::string& msg) override; + void Debug(const std::string& topic, const std::string& msg) override; void Info(const std::string& msg) override; + void Info(const std::string& topic, const std::string& msg) override; void Warn(const std::string& msg) override; + void Warn(const std::string& topic, const std::string& msg) override; void Error(const std::string& msg) override; + void Error(const std::string& topic, const std::string& msg) override; void Critical(const std::string& msg) override; + void Critical(const std::string& topic, const std::string& msg) override; void RegisterRemoteLogging(const LogMsgHandler& handler); void DisableRemoteLogging(); diff --git a/SilKit/source/services/logging/LoggingSerdes.cpp b/SilKit/source/services/logging/LoggingSerdes.cpp index ee24973f3..69d1e097b 100644 --- a/SilKit/source/services/logging/LoggingSerdes.cpp +++ b/SilKit/source/services/logging/LoggingSerdes.cpp @@ -24,7 +24,7 @@ inline MessageBuffer& operator>>(MessageBuffer& buffer, SourceLoc& sourceLoc) inline MessageBuffer& operator<<(MessageBuffer& buffer, const LogMsg& msg) { - buffer << msg.loggerName << msg.level << msg.time << msg.source << msg.payload << msg.keyValues; + buffer << msg.loggerName << msg.level << msg.time << msg.source << msg.payload << msg.keyValues << msg.topic; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, LogMsg& msg) @@ -34,6 +34,10 @@ inline MessageBuffer& operator>>(MessageBuffer& buffer, LogMsg& msg) { buffer >> msg.keyValues; } + if (buffer.RemainingBytesLeft() > 0) + { + buffer >> msg.topic; + } return buffer; } diff --git a/SilKit/source/services/logging/MockLogger.hpp b/SilKit/source/services/logging/MockLogger.hpp index af987a1cd..159190384 100644 --- a/SilKit/source/services/logging/MockLogger.hpp +++ b/SilKit/source/services/logging/MockLogger.hpp @@ -30,6 +30,7 @@ class MockLogger : public ::SilKit::Services::Logging::ILoggerInternal public: MOCK_METHOD(void, Log, (Level level, const std::string& msg), (override)); + MOCK_METHOD(void, Log, (Level level, const std::string& topic, const std::string& msg), (override)); MOCK_METHOD(void, ProcessLoggerMessage, (const LoggerMessage& msg), (override)); MOCK_METHOD(void, LogReceivedMsg, (const LogMsg& msg), (override)); @@ -38,31 +39,61 @@ class MockLogger : public ::SilKit::Services::Logging::ILoggerInternal Log(Level::Trace, msg); } + void Trace(const std::string& topic, const std::string& msg) override + { + Log(Level::Trace, topic, msg); + } + void Debug(const std::string& msg) override { Log(Level::Debug, msg); } + void Debug(const std::string& topic, const std::string& msg) override + { + Log(Level::Debug, topic, msg); + } + void Info(const std::string& msg) override { Log(Level::Info, msg); } + void Info(const std::string& topic, const std::string& msg) override + { + Log(Level::Info, topic, msg); + } + void Warn(const std::string& msg) override { Log(Level::Warn, msg); } + void Warn(const std::string& topic, const std::string& msg) override + { + Log(Level::Warn, topic, msg); + } + void Error(const std::string& msg) override { Log(Level::Error, msg); } + void Error(const std::string& topic, const std::string& msg) override + { + Log(Level::Error, topic, msg); + } + void Critical(const std::string& msg) override { Log(Level::Critical, msg); } + void Critical(const std::string& topic, const std::string& msg) override + { + Log(Level::Critical, topic, msg); + } + MOCK_METHOD(SilKit::Services::Logging::Level, GetLogLevel, (), (const, override)); }; diff --git a/SilKit/source/services/logging/StructuredLoggingKeys.hpp b/SilKit/source/services/logging/StructuredLoggingKeys.hpp index 784f821d8..bfa39cf23 100644 --- a/SilKit/source/services/logging/StructuredLoggingKeys.hpp +++ b/SilKit/source/services/logging/StructuredLoggingKeys.hpp @@ -45,7 +45,7 @@ constexpr std::string_view controllerFuncName{"ControllerFuncName"}; constexpr std::string_view mediaType{"MediaType"}; constexpr std::string_view network{"Network"}; constexpr std::string_view label{"Label"}; - +constexpr std::string_view topic{"Topic"}; } // namespace Keys } // namespace Logging From f2f0cc63da75e854f0fdb914d3af51d249fc68a8 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Wed, 18 Mar 2026 15:09:36 +0100 Subject: [PATCH 02/23] Add topics in log message --- .../detail/impl/services/logging/Logger.hpp | 49 ++++++------- .../silkit/services/logging/ILogger.hpp | 14 ++-- .../services/logging/LoggingDatatypes.hpp | 13 ++++ .../silkit/services/logging/string_utils.hpp | 64 ++++++++++++++++- SilKit/source/capi/CapiLogger.cpp | 4 +- SilKit/source/capi/Test_CapiLogger.cpp | 14 ++-- SilKit/source/config/Configuration.hpp | 1 + .../ParticipantConfiguration.schema.json | 10 +++ .../internal/LoggingDatatypesInternal.hpp | 8 +-- .../core/vasio/Test_TransformAcceptorUris.cpp | 15 ++-- SilKit/source/services/logging/Logger.cpp | 72 ++++++++++--------- SilKit/source/services/logging/Logger.hpp | 27 ++++--- .../source/services/logging/LoggerMessage.hpp | 13 ++++ .../source/services/logging/LoggingSerdes.cpp | 8 +-- .../services/logging/MessageTracing.hpp | 1 + SilKit/source/services/logging/MockLogger.hpp | 43 +++++++++-- .../logging/StructuredLoggingKeys.hpp | 2 +- .../orchestration/SystemStateTracker.cpp | 5 ++ .../orchestration/TimeSyncService.cpp | 6 ++ 19 files changed, 257 insertions(+), 112 deletions(-) diff --git a/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp b/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp index 070b88f89..3985f58e6 100644 --- a/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp +++ b/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp @@ -5,7 +5,6 @@ #pragma once #include "silkit/capi/Logger.h" - #include "silkit/services/logging/ILogger.hpp" @@ -24,25 +23,26 @@ class Logger : public SilKit::Services::Logging::ILogger inline ~Logger() override = default; inline void Log(SilKit::Services::Logging::Level level, const std::string& msg) override; - inline void Log(SilKit::Services::Logging::Level level, const std::string& topic, const std::string& msg) override; + inline void Log(SilKit::Services::Logging::Level level, SilKit::Services::Logging::Topic topic, + const std::string& msg) override; inline void Trace(const std::string& msg) override; - inline void Trace(const std::string& topic, const std::string& msg) override; + inline void Trace(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline void Debug(const std::string& msg) override; - inline void Debug(const std::string& topic, const std::string& msg) override; + inline void Debug(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline void Info(const std::string& msg) override; - inline void Info(const std::string& topic, const std::string& msg) override; + inline void Info(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline void Warn(const std::string& msg) override; - inline void Warn(const std::string& topic, const std::string& msg) override; + inline void Warn(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline void Error(const std::string& msg) override; - inline void Error(const std::string& topic, const std::string& msg) override; + inline void Error(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline void Critical(const std::string& msg) override; - inline void Critical(const std::string& topic, const std::string& msg) override; + inline void Critical(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline auto GetLogLevel() const -> SilKit::Services::Logging::Level override; @@ -83,25 +83,18 @@ Logger::Logger(SilKit_Vendor_Vector_SilKitRegistry* silKitRegistry) void Logger::Log(SilKit::Services::Logging::Level level, const std::string& msg) { - const auto loggingLevel = static_cast(level); - - const auto returnCode = SilKit_Logger_Log(_logger, loggingLevel, msg.c_str()); - ThrowOnError(returnCode); + Log(level, SilKit::Services::Logging::Topic::None, msg); } -void Logger::Log(SilKit::Services::Logging::Level level, const std::string& topic, const std::string& msg) +void Logger::Log(SilKit::Services::Logging::Level level, SilKit::Services::Logging::Topic topic, + const std::string& msg) { - // Format as "[topic] msg" for the C API which doesn't natively support topics const auto loggingLevel = static_cast(level); std::string formatted; - if (!topic.empty()) - { - formatted = "[" + topic + "] " + msg; - } - else - { - formatted = msg; - } + + // formatted = "[" + topic + "] " + msg; // todo logger topic + formatted = msg; + const auto returnCode = SilKit_Logger_Log(_logger, loggingLevel, formatted.c_str()); ThrowOnError(returnCode); } @@ -112,7 +105,7 @@ void Logger::Trace(const std::string& msg) ThrowOnError(returnCode); } -void Logger::Trace(const std::string& topic, const std::string& msg) +void Logger::Trace(SilKit::Services::Logging::Topic topic, const std::string& msg) { Log(SilKit::Services::Logging::Level::Trace, topic, msg); } @@ -123,7 +116,7 @@ void Logger::Debug(const std::string& msg) ThrowOnError(returnCode); } -void Logger::Debug(const std::string& topic, const std::string& msg) +void Logger::Debug(SilKit::Services::Logging::Topic topic, const std::string& msg) { Log(SilKit::Services::Logging::Level::Debug, topic, msg); } @@ -134,7 +127,7 @@ void Logger::Info(const std::string& msg) ThrowOnError(returnCode); } -void Logger::Info(const std::string& topic, const std::string& msg) +void Logger::Info(SilKit::Services::Logging::Topic topic, const std::string& msg) { Log(SilKit::Services::Logging::Level::Info, topic, msg); } @@ -145,7 +138,7 @@ void Logger::Warn(const std::string& msg) ThrowOnError(returnCode); } -void Logger::Warn(const std::string& topic, const std::string& msg) +void Logger::Warn(SilKit::Services::Logging::Topic topic, const std::string& msg) { Log(SilKit::Services::Logging::Level::Warn, topic, msg); } @@ -156,7 +149,7 @@ void Logger::Error(const std::string& msg) ThrowOnError(returnCode); } -void Logger::Error(const std::string& topic, const std::string& msg) +void Logger::Error(SilKit::Services::Logging::Topic topic, const std::string& msg) { Log(SilKit::Services::Logging::Level::Error, topic, msg); } @@ -167,7 +160,7 @@ void Logger::Critical(const std::string& msg) ThrowOnError(returnCode); } -void Logger::Critical(const std::string& topic, const std::string& msg) +void Logger::Critical(SilKit::Services::Logging::Topic topic, const std::string& msg) { Log(SilKit::Services::Logging::Level::Critical, topic, msg); } diff --git a/SilKit/include/silkit/services/logging/ILogger.hpp b/SilKit/include/silkit/services/logging/ILogger.hpp index 14466c0ff..d2a60d711 100755 --- a/SilKit/include/silkit/services/logging/ILogger.hpp +++ b/SilKit/include/silkit/services/logging/ILogger.hpp @@ -30,43 +30,43 @@ class ILogger * \param topic The topic or category for the message (UTF-8). * \param msg The message which shall be logged (UTF-8). */ - virtual void Log(Level level, const std::string& topic, const std::string& msg) = 0; + virtual void Log(Level level, Topic topic, const std::string& msg) = 0; //! \brief Log a message with log level trace. virtual void Trace(const std::string& msg) = 0; //! \brief Log a message with log level trace and a topic/category. - virtual void Trace(const std::string& topic, const std::string& msg) = 0; + virtual void Trace(Topic topic, const std::string& msg) = 0; //! \brief Log a message with log level debug. virtual void Debug(const std::string& msg) = 0; //! \brief Log a message with log level debug and a topic/category. - virtual void Debug(const std::string& topic, const std::string& msg) = 0; + virtual void Debug(Topic topic, const std::string& msg) = 0; //! \brief Log a message with log level info. virtual void Info(const std::string& msg) = 0; //! \brief Log a message with log level info and a topic/category. - virtual void Info(const std::string& topic, const std::string& msg) = 0; + virtual void Info(Topic topic, const std::string& msg) = 0; //! \brief Log a message with log level warn. virtual void Warn(const std::string& msg) = 0; //! \brief Log a message with log level warn and a topic/category. - virtual void Warn(const std::string& topic, const std::string& msg) = 0; + virtual void Warn(Topic topic, const std::string& msg) = 0; //! \brief Log a message with log level error. virtual void Error(const std::string& msg) = 0; //! \brief Log a message with log level error and a topic/category. - virtual void Error(const std::string& topic, const std::string& msg) = 0; + virtual void Error(Topic topic, const std::string& msg) = 0; //! \brief Log a message with log level critical. virtual void Critical(const std::string& msg) = 0; //! \brief Log a message with log level critical and a topic/category. - virtual void Critical(const std::string& topic, const std::string& msg) = 0; + virtual void Critical(Topic topic, const std::string& msg) = 0; //! \brief Get the lowest configured log level of all sinks virtual Level GetLogLevel() const = 0; diff --git a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp index 6a2ca033d..88c74de2f 100644 --- a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp +++ b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp @@ -23,6 +23,19 @@ enum class Level : uint32_t Off = 0xffffffff //!< Logging is disabled }; +/*! \brief Topic of a log message + */ +enum class Topic : uint32_t +{ + User = 0, //!< User defind log message + TimeSyncService = 1, //!< Log message of the time sync service + LifeCycle = 2, //!< Log message of the lifecycle + SystemStateTracker = 3, + MessageTracing = 4, + None = 0xffffffff +}; + + } // namespace Logging } // namespace Services } // namespace SilKit diff --git a/SilKit/include/silkit/services/logging/string_utils.hpp b/SilKit/include/silkit/services/logging/string_utils.hpp index ad2f24237..aa7df02e9 100644 --- a/SilKit/include/silkit/services/logging/string_utils.hpp +++ b/SilKit/include/silkit/services/logging/string_utils.hpp @@ -21,7 +21,11 @@ inline std::string to_string(const Level& level); inline Level from_string(const std::string& levelStr); inline std::ostream& operator<<(std::ostream& out, const Level& level); -// ================================================================================ +inline std::string to_string(const Topic& topic); +inline Topic from_topic_string(const std::string& topicStr); +inline std::ostream& operator<<(std::ostream& out, const Topic& topic); +//inline bool operator== (const Topic& lhs, const Topic& rhs); + // ================================================================================ // Inline Implementations // ================================================================================ @@ -84,6 +88,64 @@ inline Level from_string(const std::string& levelStr) return Level::Off; } + +std::string to_string(const Topic& topic) +{ + std::stringstream outStream; + outStream << topic; + return outStream.str(); +} + +std::ostream& operator<<(std::ostream& outStream, const Topic& topic) +{ + switch (topic) + { + case Topic::User: + outStream << "User"; + break; + case Topic::TimeSyncService: + outStream << "TimeSyncService"; + break; + case Topic::LifeCycle: + outStream << "LifeCycle"; + break; + case Topic::SystemStateTracker: + outStream << "SystemStateTracker"; + break; + case Topic::MessageTracing: + outStream << "MessageTracing"; + break; + case Topic::None: + outStream << "None"; + break; + default: + outStream << "Invalid Logging::Topic"; + } + return outStream; +} + +inline Topic from_topic_string(const std::string& topicStr) +{ + auto topic = SilKit::Util::LowerCase(topicStr); + if (topic == "User") + return Topic::User; + if (topic == "TimeSyncService") + return Topic::TimeSyncService; + if (topic == "LifeCycle") + return Topic::LifeCycle; + if (topic == "SystemStateTracker") + return Topic::SystemStateTracker; + if (topic == "None") + return Topic::None; + // default to Off + return Topic::None; +} +/* +inline bool operator==(const Topic& lhs, const Topic& rhs) +{ + return static_cast(lhs) == static_cast(rhs); +}*/ + } // namespace Logging } // namespace Services } // namespace SilKit \ No newline at end of file diff --git a/SilKit/source/capi/CapiLogger.cpp b/SilKit/source/capi/CapiLogger.cpp index 09d2e92e9..475d85423 100644 --- a/SilKit/source/capi/CapiLogger.cpp +++ b/SilKit/source/capi/CapiLogger.cpp @@ -19,8 +19,10 @@ try auto logger = reinterpret_cast(self); auto enumLevel = static_cast(level); + auto topic = SilKit::Services::Logging::Topic::User; + std::string useString{message}; //ensure we do not trigger the FMT template overload for const char* - logger->Log(enumLevel, useString); + logger->Log(enumLevel, topic, useString); return SilKit_ReturnCode_SUCCESS; } CAPI_CATCH_EXCEPTIONS diff --git a/SilKit/source/capi/Test_CapiLogger.cpp b/SilKit/source/capi/Test_CapiLogger.cpp index 50c7c80b9..b4ca37f73 100644 --- a/SilKit/source/capi/Test_CapiLogger.cpp +++ b/SilKit/source/capi/Test_CapiLogger.cpp @@ -14,19 +14,19 @@ class MockLogger : public SilKit::Services::Logging::ILogger { public: MOCK_METHOD2(Log, void(Level, const std::string&)); - MOCK_METHOD(void, Log, (Level, const std::string&, const std::string&), ()); + MOCK_METHOD(void, Log, (Level, Topic, const std::string&), ()); MOCK_METHOD1(Trace, void(const std::string&)); - MOCK_METHOD(void, Trace, (const std::string&, const std::string&), ()); + MOCK_METHOD(void, Trace, (Topic, const std::string&), ()); MOCK_METHOD1(Debug, void(const std::string&)); - MOCK_METHOD(void, Debug, (const std::string&, const std::string&), ()); + MOCK_METHOD(void, Debug, (Topic, const std::string&), ()); MOCK_METHOD1(Info, void(const std::string&)); - MOCK_METHOD(void, Info, (const std::string&, const std::string&), ()); + MOCK_METHOD(void, Info, (Topic, const std::string&), ()); MOCK_METHOD1(Warn, void(const std::string&)); - MOCK_METHOD(void, Warn, (const std::string&, const std::string&), ()); + MOCK_METHOD(void, Warn, (Topic, const std::string&), ()); MOCK_METHOD1(Error, void(const std::string&)); - MOCK_METHOD(void, Error, (const std::string&, const std::string&), ()); + MOCK_METHOD(void, Error, (Topic, const std::string&), ()); MOCK_METHOD1(Critical, void(const std::string&)); - MOCK_METHOD(void, Critical, (const std::string&, const std::string&), ()); + MOCK_METHOD(void, Critical, (Topic, const std::string&), ()); MOCK_CONST_METHOD0(GetLogLevel, Level()); }; diff --git a/SilKit/source/config/Configuration.hpp b/SilKit/source/config/Configuration.hpp index dc8f42c10..b2f082f90 100644 --- a/SilKit/source/config/Configuration.hpp +++ b/SilKit/source/config/Configuration.hpp @@ -89,6 +89,7 @@ struct Logging bool logFromRemotes{false}; Services::Logging::Level flushLevel{Services::Logging::Level::Off}; std::vector sinks; + std::vector disabledTopics{Services::Logging::Topic::LifeCycle}; }; // ================================================================================ diff --git a/SilKit/source/config/ParticipantConfiguration.schema.json b/SilKit/source/config/ParticipantConfiguration.schema.json index 0800c842f..73ccafb54 100644 --- a/SilKit/source/config/ParticipantConfiguration.schema.json +++ b/SilKit/source/config/ParticipantConfiguration.schema.json @@ -471,6 +471,16 @@ "type": "string", "enum": [ "Simple", "Json" ] }, + "DisabledTopics": { + "type": "string", + "enum": [ + "User", + "TimeSyncService", + "LifeCycle", + "SystemStateTracker", + "MessageTracing" + ] + }, "Level": { "type": "string", "enum": [ diff --git a/SilKit/source/core/internal/LoggingDatatypesInternal.hpp b/SilKit/source/core/internal/LoggingDatatypesInternal.hpp index 4c6776bdc..fd31e44cb 100644 --- a/SilKit/source/core/internal/LoggingDatatypesInternal.hpp +++ b/SilKit/source/core/internal/LoggingDatatypesInternal.hpp @@ -34,11 +34,11 @@ struct LogMsg { std::string loggerName; Level level{Level::Off}; + Topic topic{Topic::None}; log_clock::time_point time; SourceLoc source; std::string payload; std::vector> keyValues; - std::string topic; }; inline bool operator==(const SourceLoc& lhs, const SourceLoc& rhs); @@ -65,9 +65,9 @@ bool operator==(const SourceLoc& lhs, const SourceLoc& rhs) inline bool operator==(const LogMsg& lhs, const LogMsg& rhs) { - return lhs.loggerName == rhs.loggerName && lhs.level == rhs.level && lhs.time == rhs.time - && lhs.source == rhs.source && lhs.payload == rhs.payload && lhs.keyValues == rhs.keyValues - && lhs.topic == rhs.topic; + return lhs.loggerName == rhs.loggerName && lhs.level == rhs.level && lhs.topic == rhs.topic + && lhs.time == rhs.time + && lhs.source == rhs.source && lhs.payload == rhs.payload && lhs.keyValues == rhs.keyValues; } std::string to_string(const SourceLoc& sourceLoc) diff --git a/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp b/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp index ce3c4cf4e..db31a1ac7 100644 --- a/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp +++ b/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp @@ -236,7 +236,8 @@ struct DummyLogger : SilKit::Services::Logging::ILogger << std::endl; } - void Log(SilKit::Services::Logging::Level level, const std::string& topic, const std::string& msg) override + void Log(SilKit::Services::Logging::Level level, SilKit::Services::Logging::Topic topic, + const std::string& msg) override { const auto now = std::chrono::steady_clock::now(); std::cout << "[DummyLogger:" << level << ":" << topic << ":" @@ -245,22 +246,22 @@ struct DummyLogger : SilKit::Services::Logging::ILogger } void Trace(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Trace, msg); } - void Trace(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Trace, topic, msg); } + void Trace(SilKit::Services::Logging::Topic topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Trace, topic, msg); } void Debug(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Debug, msg); } - void Debug(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Debug, topic, msg); } + void Debug(SilKit::Services::Logging::Topic topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Debug, topic, msg); } void Info(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Info, msg); } - void Info(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Info, topic, msg); } + void Info(SilKit::Services::Logging::Topic topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Info, topic, msg); } void Warn(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Warn, msg); } - void Warn(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Warn, topic, msg); } + void Warn(SilKit::Services::Logging::Topic topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Warn, topic, msg); } void Error(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Error, msg); } - void Error(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Error, topic, msg); } + void Error(SilKit::Services::Logging::Topic topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Error, topic, msg); } void Critical(const std::string& msg) override { Log(SilKit::Services::Logging::Level::Critical, msg); } - void Critical(const std::string& topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Critical, topic, msg); } + void Critical(SilKit::Services::Logging::Topic topic, const std::string& msg) override { Log(SilKit::Services::Logging::Level::Critical, topic, msg); } SilKit::Services::Logging::Level GetLogLevel() const override { diff --git a/SilKit/source/services/logging/Logger.cpp b/SilKit/source/services/logging/Logger.cpp index c51e0a3f7..e5ca9a5ef 100644 --- a/SilKit/source/services/logging/Logger.cpp +++ b/SilKit/source/services/logging/Logger.cpp @@ -36,20 +36,20 @@ struct SimpleLogMessage { const std::string& msg; const std::vector>& kv; - const std::string& topic; + Topic topic; }; struct JsonLogMessage { const std::string& msg; const std::vector>& kv; - const std::string& topic; + Topic topic; }; struct JsonString { const std::string& m; - const std::string& topic; + Topic topic; }; } // namespace Logging @@ -137,16 +137,17 @@ struct fmt::formatter template auto format(const SilKit::Services::Logging::SimpleLogMessage& msg, FormatContext& ctx) const { - bool hasTopic = !msg.topic.empty(); + bool hasTopic = !(msg.topic == SilKit::Services::Logging::Topic::None); bool hasKv = !msg.kv.empty(); if (hasTopic && hasKv) { - return fmt::format_to(ctx.out(), "[{}] {}, {}", msg.topic, msg.msg, KeyValuesToSimpleString(msg.kv)); + return fmt::format_to(ctx.out(), "[{}] {}, {}", to_string(msg.topic), msg.msg, + KeyValuesToSimpleString(msg.kv)); } else if (hasTopic) { - return fmt::format_to(ctx.out(), "[{}] {}", msg.topic, msg.msg); + return fmt::format_to(ctx.out(), "[{}] {}", to_string(msg.topic), msg.msg); } else if (hasKv) { @@ -171,20 +172,20 @@ struct fmt::formatter template auto format(const SilKit::Services::Logging::JsonLogMessage& msg, FormatContext& ctx) const { - bool hasTopic = !msg.topic.empty(); + bool hasTopic = !(msg.topic == SilKit::Services::Logging::Topic::None); bool hasKv = !msg.kv.empty(); if (hasTopic && hasKv) { return fmt::format_to(ctx.out(), "\"topic\": \"{}\", \"msg\": \"{}\", \"kv\": {}", - SilKit::Util::EscapeString(msg.topic), + SilKit::Util::EscapeString(to_string(msg.topic)), SilKit::Util::EscapeString(msg.msg), KeyValuesToJsonString(msg.kv)); } else if (hasTopic) { return fmt::format_to(ctx.out(), "\"topic\": \"{}\", \"msg\": \"{}\"", - SilKit::Util::EscapeString(msg.topic), + SilKit::Util::EscapeString(to_string(msg.topic)), SilKit::Util::EscapeString(msg.msg)); } else if (hasKv) @@ -211,13 +212,10 @@ struct fmt::formatter template auto format(const SilKit::Services::Logging::JsonString& msg, FormatContext& ctx) const { - if (!msg.topic.empty()) - { - return fmt::format_to(ctx.out(), "\"topic\": \"{}\", \"msg\": \"{}\"", - SilKit::Util::EscapeString(msg.topic), - SilKit::Util::EscapeString(msg.m)); - } - return fmt::format_to(ctx.out(), "\"msg\": \"{}\"", SilKit::Util::EscapeString(msg.m)); + + return fmt::format_to(ctx.out(), "\"topic\": \"{}\", \"msg\": \"{}\"", + SilKit::Util::EscapeString(to_string(msg.topic)), + SilKit::Util::EscapeString(msg.m)); } }; @@ -393,14 +391,14 @@ void Logger::ProcessLoggerMessage(const LoggerMessage& msg) const auto now = log_clock::now(); if (nullptr != _loggerJson) { - JsonLogMessage myJsonMsg{msg.GetMsgString(), msg.GetKeyValues(), emptyTopic}; + JsonLogMessage myJsonMsg{msg.GetMsgString(), msg.GetKeyValues(), msg.GetTopic()}; _loggerJson->log(now, spdlog::source_loc{}, to_spdlog(msg.GetLevel()), fmt::format("{}", myJsonMsg)); } if (nullptr != _loggerSimple) { - SimpleLogMessage myMsg{msg.GetMsgString(), msg.GetKeyValues(), emptyTopic}; + SimpleLogMessage myMsg{msg.GetMsgString(), msg.GetKeyValues(), msg.GetTopic()}; _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(msg.GetLevel()), fmt::format("{}", myMsg)); } if (nullptr != _loggerRemote) @@ -454,10 +452,11 @@ void Logger::LogReceivedMsg(const LogMsg& msg) void Logger::Log(Level level, const std::string& msg) { + // No topic, always log const auto now = log_clock::now(); if (nullptr != _loggerJson) { - JsonString jsonString{msg, emptyTopic}; + JsonString jsonString{msg, Topic::None}; _loggerJson->log(now, spdlog::source_loc{}, to_spdlog(level), fmt::format("{}", jsonString)); } if (nullptr != _loggerSimple) @@ -470,8 +469,13 @@ void Logger::Log(Level level, const std::string& msg) } } -void Logger::Log(Level level, const std::string& topic, const std::string& msg) +void Logger::Log(Level level, Topic topic, const std::string& msg) { + if (!IsTopicEnabled(topic)) + { + return; + } + const auto now = log_clock::now(); if (nullptr != _loggerJson) { @@ -480,14 +484,14 @@ void Logger::Log(Level level, const std::string& topic, const std::string& msg) } if (nullptr != _loggerSimple) { - if (!topic.empty()) - { - _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(level), fmt::format("[{}] {}", topic, msg)); - } - else - { - _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(level), msg); - } + // if (!(topic == Topic::None)) + // { + _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(level), fmt::format("[{}] {}", to_string(topic), msg)); + // } + // else + // { + // _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(level), msg); + // } } if (nullptr != _loggerRemote) { @@ -501,7 +505,7 @@ void Logger::Trace(const std::string& msg) Log(Level::Trace, msg); } -void Logger::Trace(const std::string& topic, const std::string& msg) +void Logger::Trace(Topic topic, const std::string& msg) { Log(Level::Trace, topic, msg); } @@ -511,7 +515,7 @@ void Logger::Debug(const std::string& msg) Log(Level::Debug, msg); } -void Logger::Debug(const std::string& topic, const std::string& msg) +void Logger::Debug(Topic topic, const std::string& msg) { Log(Level::Debug, topic, msg); } @@ -521,7 +525,7 @@ void Logger::Info(const std::string& msg) Log(Level::Info, msg); } -void Logger::Info(const std::string& topic, const std::string& msg) +void Logger::Info(Topic topic, const std::string& msg) { Log(Level::Info, topic, msg); } @@ -531,7 +535,7 @@ void Logger::Warn(const std::string& msg) Log(Level::Warn, msg); } -void Logger::Warn(const std::string& topic, const std::string& msg) +void Logger::Warn(Topic topic, const std::string& msg) { Log(Level::Warn, topic, msg); } @@ -541,7 +545,7 @@ void Logger::Error(const std::string& msg) Log(Level::Error, msg); } -void Logger::Error(const std::string& topic, const std::string& msg) +void Logger::Error(Topic topic, const std::string& msg) { Log(Level::Error, topic, msg); } @@ -551,7 +555,7 @@ void Logger::Critical(const std::string& msg) Log(Level::Critical, msg); } -void Logger::Critical(const std::string& topic, const std::string& msg) +void Logger::Critical(Topic topic, const std::string& msg) { Log(Level::Critical, topic, msg); } diff --git a/SilKit/source/services/logging/Logger.hpp b/SilKit/source/services/logging/Logger.hpp index aaffea4c9..22ce2cbee 100755 --- a/SilKit/source/services/logging/Logger.hpp +++ b/SilKit/source/services/logging/Logger.hpp @@ -56,7 +56,7 @@ class RemoteLogger } } - void Log(log_clock::time_point logTime, Level msgLevel, const std::string& topic, std::string msg) + void Log(log_clock::time_point logTime, Level msgLevel, Topic topic, std::string msg) { if (nullptr != _remoteSink) { @@ -81,7 +81,7 @@ class RemoteLogger { if (_level <= msg.GetLevel()) { - LogMsg logmsg{_participantName, msg.GetLevel(), logTime, {}, msg.GetMsgString(), msg.GetKeyValues()}; + LogMsg logmsg{_participantName, msg.GetLevel(), msg.GetTopic(), logTime, {}, msg.GetMsgString(), msg.GetKeyValues()}; // dispatch msg _remoteSink(logmsg); } @@ -140,25 +140,25 @@ class Logger : public ILoggerInternal // ILogger void Log(Level level, const std::string& msg) override; - void Log(Level level, const std::string& topic, const std::string& msg) override; + void Log(Level level, Topic topic, const std::string& msg) override; void Trace(const std::string& msg) override; - void Trace(const std::string& topic, const std::string& msg) override; + void Trace(Topic topic, const std::string& msg) override; void Debug(const std::string& msg) override; - void Debug(const std::string& topic, const std::string& msg) override; + void Debug(Topic topic, const std::string& msg) override; void Info(const std::string& msg) override; - void Info(const std::string& topic, const std::string& msg) override; + void Info(Topic topic, const std::string& msg) override; void Warn(const std::string& msg) override; - void Warn(const std::string& topic, const std::string& msg) override; + void Warn(Topic topic, const std::string& msg) override; void Error(const std::string& msg) override; - void Error(const std::string& topic, const std::string& msg) override; + void Error(Topic topic, const std::string& msg) override; void Critical(const std::string& msg) override; - void Critical(const std::string& topic, const std::string& msg) override; + void Critical(Topic topic, const std::string& msg) override; void RegisterRemoteLogging(const LogMsgHandler& handler); void DisableRemoteLogging(); @@ -179,6 +179,15 @@ class Logger : public ILoggerInternal std::shared_ptr _loggerJson; std::shared_ptr _loggerSimple; std::shared_ptr _loggerRemote; + + bool IsTopicEnabled(Topic topic) const + { + if (!_config.disabledTopics.empty()) + { + return std::find(_config.disabledTopics.begin(), _config.disabledTopics.end(), topic) == _config.disabledTopics.end(); + } + return true; + } }; } // namespace Logging diff --git a/SilKit/source/services/logging/LoggerMessage.hpp b/SilKit/source/services/logging/LoggerMessage.hpp index 5509ae2cc..ac55a84cf 100644 --- a/SilKit/source/services/logging/LoggerMessage.hpp +++ b/SilKit/source/services/logging/LoggerMessage.hpp @@ -40,6 +40,7 @@ class LoggerMessage LoggerMessage(ILoggerInternal* logger, const LogMsg& msg) : _logger(logger) , _level(msg.level) + , _topic(msg.topic) , _msg(msg.payload) , _keyValues(msg.keyValues) { @@ -102,11 +103,22 @@ class LoggerMessage } } + auto SetTopic(Topic topic) + { + _topic = topic; + } + + auto GetLevel() const -> Level { return _level; } + auto GetTopic() const -> Topic + { + return _topic; + } + auto GetKeyValues() const -> const std::vector>& { return _keyValues; @@ -128,6 +140,7 @@ class LoggerMessage private: ILoggerInternal* _logger; Level _level; + Topic _topic; std::string _msg; std::vector> _keyValues; }; diff --git a/SilKit/source/services/logging/LoggingSerdes.cpp b/SilKit/source/services/logging/LoggingSerdes.cpp index 69d1e097b..5d2a792ab 100644 --- a/SilKit/source/services/logging/LoggingSerdes.cpp +++ b/SilKit/source/services/logging/LoggingSerdes.cpp @@ -24,20 +24,16 @@ inline MessageBuffer& operator>>(MessageBuffer& buffer, SourceLoc& sourceLoc) inline MessageBuffer& operator<<(MessageBuffer& buffer, const LogMsg& msg) { - buffer << msg.loggerName << msg.level << msg.time << msg.source << msg.payload << msg.keyValues << msg.topic; + buffer << msg.loggerName << msg.level << msg.topic << msg.time << msg.source << msg.payload << msg.keyValues; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, LogMsg& msg) { - buffer >> msg.loggerName >> msg.level >> msg.time >> msg.source >> msg.payload; + buffer >> msg.loggerName >> msg.level >> msg.topic >> msg.time >> msg.source >> msg.payload; if (buffer.RemainingBytesLeft() > 0) { buffer >> msg.keyValues; } - if (buffer.RemainingBytesLeft() > 0) - { - buffer >> msg.topic; - } return buffer; } diff --git a/SilKit/source/services/logging/MessageTracing.hpp b/SilKit/source/services/logging/MessageTracing.hpp index 8bccd0126..89bcb0551 100644 --- a/SilKit/source/services/logging/MessageTracing.hpp +++ b/SilKit/source/services/logging/MessageTracing.hpp @@ -55,6 +55,7 @@ void TraceMessageCommon(Logging::ILoggerInternal* logger, const char* messageStr { lm.SetKeyValue(Logging::Keys::raw, SilKit::Config::SerializeAsJson(msg)); } + lm.SetTopic(Logging::Topic::MessageTracing); lm.Dispatch(); } } diff --git a/SilKit/source/services/logging/MockLogger.hpp b/SilKit/source/services/logging/MockLogger.hpp index 159190384..4b754d629 100644 --- a/SilKit/source/services/logging/MockLogger.hpp +++ b/SilKit/source/services/logging/MockLogger.hpp @@ -21,16 +21,45 @@ class MockLogger : public ::SilKit::Services::Logging::ILoggerInternal using Level = ::SilKit::Services::Logging::Level; using LoggerMessage = ::SilKit::Services::Logging::LoggerMessage; using LogMsg = ::SilKit::Services::Logging::LogMsg; + using Topic = ::SilKit::Services::Logging::Topic; public: MockLogger() { ON_CALL(*this, GetLogLevel).WillByDefault(testing::Return(Level::Trace)); + // Topic filtering for Log methods + ON_CALL(*this, Log(testing::_, testing::_, testing::_)).WillByDefault( + [this](Level level, Topic topic, const std::string& msg) { + if (!IsTopicEnabled(topic)) return; + LogImpl(level, topic, msg); + }); + ON_CALL(*this, Log(testing::_, testing::_)).WillByDefault( + [this](Level level, const std::string& msg) { + LogImpl(level, Topic::None, msg); + }); + } + + std::vector disabledTopics; + + bool IsTopicEnabled(Topic topic) const + { + + if (!disabledTopics.empty()) + { + return std::find(disabledTopics.begin(), disabledTopics.end(), topic) == disabledTopics.end(); + } + return true; + } + + void LogImpl(Level level, Topic topic, const std::string& msg) + { + // Call the mock method for test verification + // This is just for demonstration, actual test code will use EXPECT_CALL } public: MOCK_METHOD(void, Log, (Level level, const std::string& msg), (override)); - MOCK_METHOD(void, Log, (Level level, const std::string& topic, const std::string& msg), (override)); + MOCK_METHOD(void, Log, (Level level, Topic topic, const std::string& msg), (override)); MOCK_METHOD(void, ProcessLoggerMessage, (const LoggerMessage& msg), (override)); MOCK_METHOD(void, LogReceivedMsg, (const LogMsg& msg), (override)); @@ -39,7 +68,7 @@ class MockLogger : public ::SilKit::Services::Logging::ILoggerInternal Log(Level::Trace, msg); } - void Trace(const std::string& topic, const std::string& msg) override + void Trace(Topic topic, const std::string& msg) override { Log(Level::Trace, topic, msg); } @@ -49,7 +78,7 @@ class MockLogger : public ::SilKit::Services::Logging::ILoggerInternal Log(Level::Debug, msg); } - void Debug(const std::string& topic, const std::string& msg) override + void Debug(Topic topic, const std::string& msg) override { Log(Level::Debug, topic, msg); } @@ -59,7 +88,7 @@ class MockLogger : public ::SilKit::Services::Logging::ILoggerInternal Log(Level::Info, msg); } - void Info(const std::string& topic, const std::string& msg) override + void Info(Topic topic, const std::string& msg) override { Log(Level::Info, topic, msg); } @@ -69,7 +98,7 @@ class MockLogger : public ::SilKit::Services::Logging::ILoggerInternal Log(Level::Warn, msg); } - void Warn(const std::string& topic, const std::string& msg) override + void Warn(Topic topic, const std::string& msg) override { Log(Level::Warn, topic, msg); } @@ -79,7 +108,7 @@ class MockLogger : public ::SilKit::Services::Logging::ILoggerInternal Log(Level::Error, msg); } - void Error(const std::string& topic, const std::string& msg) override + void Error(Topic topic, const std::string& msg) override { Log(Level::Error, topic, msg); } @@ -89,7 +118,7 @@ class MockLogger : public ::SilKit::Services::Logging::ILoggerInternal Log(Level::Critical, msg); } - void Critical(const std::string& topic, const std::string& msg) override + void Critical(Topic topic, const std::string& msg) override { Log(Level::Critical, topic, msg); } diff --git a/SilKit/source/services/logging/StructuredLoggingKeys.hpp b/SilKit/source/services/logging/StructuredLoggingKeys.hpp index bfa39cf23..784f821d8 100644 --- a/SilKit/source/services/logging/StructuredLoggingKeys.hpp +++ b/SilKit/source/services/logging/StructuredLoggingKeys.hpp @@ -45,7 +45,7 @@ constexpr std::string_view controllerFuncName{"ControllerFuncName"}; constexpr std::string_view mediaType{"MediaType"}; constexpr std::string_view network{"Network"}; constexpr std::string_view label{"Label"}; -constexpr std::string_view topic{"Topic"}; + } // namespace Keys } // namespace Logging diff --git a/SilKit/source/services/orchestration/SystemStateTracker.cpp b/SilKit/source/services/orchestration/SystemStateTracker.cpp index 4c2355e27..2027e07df 100644 --- a/SilKit/source/services/orchestration/SystemStateTracker.cpp +++ b/SilKit/source/services/orchestration/SystemStateTracker.cpp @@ -147,6 +147,7 @@ auto SystemStateTracker::UpdateParticipantStatus(const ParticipantStatus& newPar lm.SetKeyValue(Log::Keys::participantName, participantName); lm.FormatKeyValue(Log::Keys::oldParticipantState, "{}", oldParticipantState); lm.FormatKeyValue(Log::Keys::newParticipantState, "{}", newParticipantState); + lm.SetTopic(Log::Topic::SystemStateTracker); lm.Dispatch(); } @@ -164,6 +165,7 @@ auto SystemStateTracker::UpdateParticipantStatus(const ParticipantStatus& newPar lm.FormatKeyValue(Log::Keys::newParticipantState, "{}", newParticipantState); lm.SetKeyValue(Log::Keys::enterTime, FormatTimePoint(newParticipantStatus.enterTime)); lm.SetKeyValue(Log::Keys::enterReason, newParticipantStatus.enterReason); + lm.SetTopic(Log::Topic::SystemStateTracker); lm.Dispatch(); } // NB: Failing validation doesn't actually stop the participants state from being changed, it just logs the @@ -189,6 +191,7 @@ auto SystemStateTracker::UpdateParticipantStatus(const ParticipantStatus& newPar Log::LoggerMessage lm{_logger, Log::Level::Debug}; lm.SetMessage("The participant state has changed!"); lm.SetKeyValue(Log::Keys::participantName, participantName); + lm.SetTopic(Log::Topic::SystemStateTracker); lm.Dispatch(); } @@ -204,6 +207,7 @@ auto SystemStateTracker::UpdateParticipantStatus(const ParticipantStatus& newPar lm.SetKeyValue(Log::Keys::participantName, participantName); lm.FormatKeyValue(Log::Keys::oldParticipantState, "{}", oldSystemState); lm.FormatKeyValue(Log::Keys::newParticipantState, "{}", newSystemState); + lm.SetTopic(Log::Topic::SystemStateTracker); lm.Dispatch(); } @@ -216,6 +220,7 @@ auto SystemStateTracker::UpdateParticipantStatus(const ParticipantStatus& newPar lm.SetKeyValue(Log::Keys::participantName, participantName); lm.FormatKeyValue(Log::Keys::oldParticipantState, "{}", oldSystemState); lm.FormatKeyValue(Log::Keys::newParticipantState, "{}", newSystemState); + lm.SetTopic(Log::Topic::SystemStateTracker); lm.Dispatch(); } diff --git a/SilKit/source/services/orchestration/TimeSyncService.cpp b/SilKit/source/services/orchestration/TimeSyncService.cpp index d21b9888e..9f2ed5300 100644 --- a/SilKit/source/services/orchestration/TimeSyncService.cpp +++ b/SilKit/source/services/orchestration/TimeSyncService.cpp @@ -492,6 +492,7 @@ void TimeSyncService::ReceiveMsg(const IServiceEndpoint* from, const NextSimTask Logging::LoggerMessage lm{_logger, Logging::Level::Debug}; lm.SetMessage("Received NextSimTask from participant \'{}\' but TimeSyncPolicy is not yet configured"); lm.SetKeyValue(Logging::Keys::participantName, from->GetServiceDescriptor().GetParticipantName()); + lm.SetTopic(Logging::Topic::TimeSyncService); lm.Dispatch(); } } @@ -512,6 +513,7 @@ void TimeSyncService::ExecuteSimStep(std::chrono::nanoseconds timePoint, std::ch lm.FormatKeyValue(Logging::Keys::waitingTime, "{}", std::chrono::duration_cast(_waitTimeMonitor.CurrentDuration()).count()); lm.FormatKeyValue(Logging::Keys::virtualTimeNS, "{}", timePoint.count()); + lm.SetTopic(Logging::Topic::TimeSyncService); lm.Dispatch(); } @@ -555,6 +557,7 @@ void TimeSyncService::LogicalSimStepCompleted(std::chrono::durationGetParticipantName()); + lm.SetTopic(Logging::Topic::TimeSyncService); lm.Dispatch(); _participant->GetSystemController()->AbortSimulation(); @@ -785,6 +790,7 @@ void TimeSyncService::StartWallClockCouplingThread(std::chrono::nanoseconds star Logging::LoggerMessage lm{_participant->GetLoggerInternal(), Logging::Level::Warn}; lm.SetMessage("Simulation step was not completed in time to achieve wall clock coupling."); lm.SetKeyValue(Logging::Keys::participantName, _participant->GetParticipantName()); + lm.SetTopic(Logging::Topic::TimeSyncService); lm.Dispatch(); _wallClockReachedBeforeCompletion = true; From e4fe2adc8754b83e34a0810be70679ffb1d745ad Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Tue, 24 Mar 2026 14:34:46 +0100 Subject: [PATCH 03/23] fixup! Add topics in log message --- .../services/logging/LoggingDatatypes.hpp | 9 +- .../silkit/services/logging/string_utils.hpp | 37 ++- SilKit/source/config/Configuration.hpp | 5 +- .../ParticipantConfiguration.schema.json | 18 +- SilKit/source/config/YamlReader.cpp | 56 +++- SilKit/source/services/logging/Logger.cpp | 264 +++++++++--------- SilKit/source/services/logging/Logger.hpp | 23 +- .../source/services/logging/LoggerMessage.hpp | 2 +- 8 files changed, 246 insertions(+), 168 deletions(-) diff --git a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp index 88c74de2f..ea16cb09c 100644 --- a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp +++ b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp @@ -27,12 +27,15 @@ enum class Level : uint32_t */ enum class Topic : uint32_t { - User = 0, //!< User defind log message - TimeSyncService = 1, //!< Log message of the time sync service + None = 0, + User = 1, //!< User defind log message LifeCycle = 2, //!< Log message of the lifecycle SystemStateTracker = 3, MessageTracing = 4, - None = 0xffffffff + ServiceDiscovery = 5, + Asio = 6, + TimeSyncService = 7, //!< Log message of the time sync service + Invalid = 0xffffffff }; diff --git a/SilKit/include/silkit/services/logging/string_utils.hpp b/SilKit/include/silkit/services/logging/string_utils.hpp index aa7df02e9..606676839 100644 --- a/SilKit/include/silkit/services/logging/string_utils.hpp +++ b/SilKit/include/silkit/services/logging/string_utils.hpp @@ -101,25 +101,28 @@ std::ostream& operator<<(std::ostream& outStream, const Topic& topic) switch (topic) { case Topic::User: - outStream << "User"; + outStream << "user"; break; case Topic::TimeSyncService: - outStream << "TimeSyncService"; + outStream << "timesyncservice"; break; case Topic::LifeCycle: - outStream << "LifeCycle"; + outStream << "lifecycle"; break; case Topic::SystemStateTracker: - outStream << "SystemStateTracker"; + outStream << "systemstatetracker"; break; case Topic::MessageTracing: - outStream << "MessageTracing"; + outStream << "messagetracing"; + break; + case Topic::ServiceDiscovery: + outStream << "servicediscovery"; break; case Topic::None: - outStream << "None"; + outStream << "none"; break; default: - outStream << "Invalid Logging::Topic"; + outStream << "invalid"; } return outStream; } @@ -127,18 +130,22 @@ std::ostream& operator<<(std::ostream& outStream, const Topic& topic) inline Topic from_topic_string(const std::string& topicStr) { auto topic = SilKit::Util::LowerCase(topicStr); - if (topic == "User") + if (topic == "none") + return Topic::None; + if (topic == "user") return Topic::User; - if (topic == "TimeSyncService") + if (topic == "timesyncservice") return Topic::TimeSyncService; - if (topic == "LifeCycle") + if (topic == "lifecycle") return Topic::LifeCycle; - if (topic == "SystemStateTracker") + if (topic == "systemstatetracker") return Topic::SystemStateTracker; - if (topic == "None") - return Topic::None; - // default to Off - return Topic::None; + if (topic == "messagetracing") + return Topic::MessageTracing; + if (topic == "servicediscovery") + return Topic::ServiceDiscovery; + + return Topic::Invalid; } /* inline bool operator==(const Topic& lhs, const Topic& rhs) diff --git a/SilKit/source/config/Configuration.hpp b/SilKit/source/config/Configuration.hpp index b2f082f90..73b0c9839 100644 --- a/SilKit/source/config/Configuration.hpp +++ b/SilKit/source/config/Configuration.hpp @@ -81,15 +81,16 @@ struct Sink Type type{Type::Remote}; Services::Logging::Level level{Services::Logging::Level::Info}; std::string logName; + std::vector disabledTopics{}; + std::vector enabledTopics{}; }; -//! \brief Logger service +//! \brief Logger serviceoo struct Logging { bool logFromRemotes{false}; Services::Logging::Level flushLevel{Services::Logging::Level::Off}; std::vector sinks; - std::vector disabledTopics{Services::Logging::Topic::LifeCycle}; }; // ================================================================================ diff --git a/SilKit/source/config/ParticipantConfiguration.schema.json b/SilKit/source/config/ParticipantConfiguration.schema.json index 73ccafb54..8b0fcd4c1 100644 --- a/SilKit/source/config/ParticipantConfiguration.schema.json +++ b/SilKit/source/config/ParticipantConfiguration.schema.json @@ -472,14 +472,16 @@ "enum": [ "Simple", "Json" ] }, "DisabledTopics": { - "type": "string", - "enum": [ - "User", - "TimeSyncService", - "LifeCycle", - "SystemStateTracker", - "MessageTracing" - ] + "type": "array", + "items": { + "type": "string" + } + }, + "EnabledTopics": { + "type": "array", + "items": { + "type": "string" + } }, "Level": { "type": "string", diff --git a/SilKit/source/config/YamlReader.cpp b/SilKit/source/config/YamlReader.cpp index 6a796eb39..b52c71825 100644 --- a/SilKit/source/config/YamlReader.cpp +++ b/SilKit/source/config/YamlReader.cpp @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: MIT #include "YamlReader.hpp" - +#include "silkit/services/logging/string_utils.hpp" namespace VSilKit { void YamlReader::Read(SilKit::Services::MatchingLabel& value) @@ -190,12 +190,66 @@ void YamlReader::Read(SilKit::Config::Sink::Format& obj) } } + void YamlReader::Read(SilKit::Config::Sink& obj) { OptionalRead(obj.type, "Type"); OptionalRead(obj.level, "Level"); OptionalRead(obj.format, "Format"); + + /* auto readTopics = [](std::vector& topicList, + std::vector temp) -> bool + { + for (auto&& topic : temp) + { + SilKit::Services::Logging::Topic enumTopic = SilKit::Services::Logging::from_topic_string(topic); + if (enumTopic == SilKit::Services::Logging::Topic::Invalid) + { + return false; + } + topicList.push_back(enumTopic); + } + return true; + }; + std::vector temp{}; + OptionalRead(temp, "DisabledTopics"); + + if( !readTopics(obj.disabledTopics, temp)) + { + throw MakeConfigurationError("Unknown SilKit::Services::Logging::Topic: "); + } + + OptionalRead(temp, "EnabledTopics"); + if (!readTopics(obj.enabledTopics, temp)) + { + throw MakeConfigurationError("Unknown SilKit::Services::Logging::Topic: "); + }*/ + + std::vector temp{}; + OptionalRead(temp, "DisabledTopics"); + + for (auto&& topic : temp) + { + SilKit::Services::Logging::Topic enumTopic = SilKit::Services::Logging::from_topic_string(topic); + if (enumTopic == SilKit::Services::Logging::Topic::Invalid) + { + throw MakeConfigurationError("Unknown SilKit::Services::Logging::Topic: "); + } + obj.disabledTopics.push_back(enumTopic); + } + + OptionalRead(temp, "EnabledTopics"); + for (auto&& topic : temp) + { + SilKit::Services::Logging::Topic enumTopic = SilKit::Services::Logging::from_topic_string(topic); + if (enumTopic == SilKit::Services::Logging::Topic::Invalid) + { + throw MakeConfigurationError("Unknown SilKit::Services::Logging::Topic: "); + } + obj.enabledTopics.push_back(enumTopic); + } + if (obj.type == SilKit::Config::Sink::Type::File) { if (!HasKey("LogName")) diff --git a/SilKit/source/services/logging/Logger.cpp b/SilKit/source/services/logging/Logger.cpp index e5ca9a5ef..65f595868 100644 --- a/SilKit/source/services/logging/Logger.cpp +++ b/SilKit/source/services/logging/Logger.cpp @@ -271,20 +271,20 @@ Logger::Logger(const std::string& participantName, Config::Logging config) { if (sink.type == Config::Sink::Type::Remote) { - _loggerRemote = std::make_shared(sink.level, participantName); + _remoteLogger.emplace(std::make_shared(sink.level, participantName), sink); } else { // NB: logger gets dropped from registry immediately after creating so that two participant with the same // participantName won't lead to a spdlog exception because a logger with this name does already exist. - if (sink.format == Config::Sink::Format::Json && nullptr == _loggerJson) + if (sink.format == Config::Sink::Format::Json) { - _loggerJson = spdlog::create(participantName); + _spdlogLogger.emplace(spdlog::create(participantName), sink); spdlog::drop(participantName); } - if (sink.format == Config::Sink::Format::Simple && nullptr == _loggerSimple) + if (sink.format == Config::Sink::Format::Simple) { - _loggerSimple = spdlog::create(participantName); + _spdlogLogger.emplace(spdlog::create(participantName), sink); spdlog::drop(participantName); } } @@ -299,41 +299,19 @@ Logger::Logger(const std::string& participantName, Config::Logging config) // Defined JSON pattern for the logger output const std::string jsonpattern{R"({"ts":"%E","log":"%n","lvl":"%l", %v })"}; - for (auto sink : _config.sinks) + for (const auto& pair : _spdlogLogger) { - auto log_level = to_spdlog(sink.level); - if (sink.format == Config::Sink::Format::Json && sink.type != Config::Sink::Type::Remote) - { - if (log_level < _loggerJson->level()) - { - _loggerJson->set_level(log_level); - } - } - if (sink.format == Config::Sink::Format::Simple && sink.type != Config::Sink::Type::Remote) - { - if (log_level < _loggerSimple->level()) - { - _loggerSimple->set_level(log_level); - } - } - - switch (sink.type) - { - case Config::Sink::Type::Remote: - // The remote sink is instantiated and added later together with setting up - // all necessary connection logic to avoid segmentation errors if sth. goes wrong - break; + auto log_level = to_spdlog(Services::Logging::Level::Trace /* pair.second.level*/); + pair.first->set_level(log_level); - case Config::Sink::Type::Stdout: + if (pair.second.type == Config::Sink::Type::Stdout) { #if _WIN32 auto stdoutSink = std::make_shared(); - #else auto stdoutSink = std::make_shared(); #endif - - if (sink.format == Config::Sink::Format::Json && sink.type != Config::Sink::Type::Remote) + if (pair.second.format == Config::Sink::Format::Json) { using spdlog::details::make_unique; // for pre c++14 auto formatter = make_unique(); @@ -341,20 +319,19 @@ Logger::Logger(const std::string& participantName, Config::Logging config) formatter->set_pattern(jsonpattern); stdoutSink->set_formatter(std::move(formatter)); stdoutSink->set_level(log_level); - _loggerJson->sinks().emplace_back(std::move(stdoutSink)); + pair.first->sinks().emplace_back(std::move(stdoutSink)); } - else if (sink.type != Config::Sink::Type::Remote) + else // Simple format { stdoutSink->set_level(log_level); - _loggerSimple->sinks().emplace_back(std::move(stdoutSink)); + pair.first->sinks().emplace_back(std::move(stdoutSink)); } - break; } - case Config::Sink::Type::File: + else if (pair.second.type == Config::Sink::Type::File) { - if (sink.format == Config::Sink::Format::Json) + if (pair.second.format == Config::Sink::Format::Json) { - auto filename = fmt::format("{}_{}_{}.jsonl", sink.logName, + auto filename = fmt::format("{}_{}_{}.jsonl", pair.second.logName, SilKit::Util::PrintableString(participantName), logFileTimestamp); auto fileSink = std::make_shared(filename); using spdlog::details::make_unique; // for pre c++14 @@ -363,88 +340,112 @@ Logger::Logger(const std::string& participantName, Config::Logging config) formatter->set_pattern(jsonpattern); fileSink->set_formatter(std::move(formatter)); fileSink->set_level(log_level); - _loggerJson->sinks().push_back(fileSink); + pair.first->sinks().push_back(fileSink); } else { - auto filename = fmt::format("{}_{}_{}.txt", sink.logName, + auto filename = fmt::format("{}_{}_{}.txt", pair.second.logName, SilKit::Util::PrintableString(participantName), logFileTimestamp); auto fileSink = std::make_shared(filename); fileSink->set_level(log_level); - _loggerSimple->sinks().push_back(fileSink); + pair.first->sinks().push_back(fileSink); } } - } } - if (nullptr != _loggerSimple) - { - _loggerSimple->flush_on(to_spdlog(_config.flushLevel)); - } - if (nullptr != _loggerJson) + + for (const auto& pair : _spdlogLogger) { - _loggerJson->flush_on(to_spdlog(_config.flushLevel)); + pair.first->flush_on(to_spdlog(_config.flushLevel)); } } + + void Logger::ProcessLoggerMessage(const LoggerMessage& msg) { const auto now = log_clock::now(); - if (nullptr != _loggerJson) - { - JsonLogMessage myJsonMsg{msg.GetMsgString(), msg.GetKeyValues(), msg.GetTopic()}; - _loggerJson->log(now, spdlog::source_loc{}, to_spdlog(msg.GetLevel()), fmt::format("{}", myJsonMsg)); - } - if (nullptr != _loggerSimple) + for (const auto& pair : _spdlogLogger) { - SimpleLogMessage myMsg{msg.GetMsgString(), msg.GetKeyValues(), msg.GetTopic()}; - _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(msg.GetLevel()), fmt::format("{}", myMsg)); + if (!(pair.second.level <= msg.GetLevel())) + { + continue; + } + + if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, msg.GetTopic()))) + { + continue; + } + + if (pair.second.format == Config::Sink::Format::Json) + { + JsonLogMessage myJsonMsg{msg.GetMsgString(), msg.GetKeyValues(), msg.GetTopic()}; + pair.first->log(now, spdlog::source_loc{}, to_spdlog(msg.GetLevel()), fmt::format("{}", myJsonMsg)); + } + else + { + SimpleLogMessage myMsg{msg.GetMsgString(), msg.GetKeyValues(), msg.GetTopic()}; + pair.first->log(now, spdlog::source_loc{}, to_spdlog(msg.GetLevel()), fmt::format("{}", myMsg)); + } } - if (nullptr != _loggerRemote) + + for (const auto& pair : _remoteLogger) { - _loggerRemote->Log(now, msg); + if (!(pair.second.level <= msg.GetLevel())) + { + continue; + } + + if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, msg.GetTopic()))) + { + continue; + } + pair.first->Log(now, msg); } + } void Logger::LogReceivedMsg(const LogMsg& msg) { - if (nullptr != _loggerJson) + for (const auto& pair : _spdlogLogger) { - JsonLogMessage jsonMsg{msg.payload, msg.keyValues, msg.topic}; + if (pair.second.format == Config::Sink::Format::Json) + { + JsonLogMessage jsonMsg{msg.payload, msg.keyValues, msg.topic}; - auto fmt{fmt::format("{}", jsonMsg)}; - auto spdlog_msg = to_spdlog(msg, fmt); + auto fmt{fmt::format("{}", jsonMsg)}; + auto spdlog_msg = to_spdlog(msg, fmt); - for (auto&& sink : _loggerJson->sinks()) - { - if (to_spdlog(msg.level) < sink->level()) - continue; + for (auto&& sink : pair.first->sinks()) + { + if (to_spdlog(msg.level) < sink->level()) + continue; - sink->log(spdlog_msg); + sink->log(spdlog_msg); - if (_config.flushLevel <= msg.level) - sink->flush(); + if (_config.flushLevel <= msg.level) + sink->flush(); + } } - } - - if (nullptr != _loggerSimple) - { - SimpleLogMessage simpleMsg{msg.payload, msg.keyValues, msg.topic}; + else + { + SimpleLogMessage simpleMsg{msg.payload, msg.keyValues, msg.topic}; - auto fmt{fmt::format("{}", simpleMsg)}; - auto spdlog_msg = to_spdlog(msg, fmt); + auto fmt{fmt::format("{}", simpleMsg)}; + auto spdlog_msg = to_spdlog(msg, fmt); - for (auto&& sink : _loggerSimple->sinks()) - { - if (to_spdlog(msg.level) < sink->level()) - continue; + for (auto&& sink : pair.first->sinks()) + { + if (to_spdlog(msg.level) < sink->level()) + continue; - sink->log(spdlog_msg); + sink->log(spdlog_msg); - if (_config.flushLevel <= msg.level) - sink->flush(); + if (_config.flushLevel <= msg.level) + sink->flush(); + } } } } @@ -452,50 +453,51 @@ void Logger::LogReceivedMsg(const LogMsg& msg) void Logger::Log(Level level, const std::string& msg) { - // No topic, always log - const auto now = log_clock::now(); - if (nullptr != _loggerJson) - { - JsonString jsonString{msg, Topic::None}; - _loggerJson->log(now, spdlog::source_loc{}, to_spdlog(level), fmt::format("{}", jsonString)); - } - if (nullptr != _loggerSimple) - { - _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(level), msg); - } - if (nullptr != _loggerRemote) - { - _loggerRemote->Log(now, level, msg); - } + Log( level, Topic::None, msg ); } void Logger::Log(Level level, Topic topic, const std::string& msg) { - if (!IsTopicEnabled(topic)) - { - return; - } - const auto now = log_clock::now(); - if (nullptr != _loggerJson) - { - JsonString jsonString{msg, topic}; - _loggerJson->log(now, spdlog::source_loc{}, to_spdlog(level), fmt::format("{}", jsonString)); - } - if (nullptr != _loggerSimple) + const auto now = log_clock::now(); + + + for (const auto& pair : _spdlogLogger) { - // if (!(topic == Topic::None)) - // { - _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(level), fmt::format("[{}] {}", to_string(topic), msg)); - // } - // else - // { - // _loggerSimple->log(now, spdlog::source_loc{}, to_spdlog(level), msg); - // } + if (!(pair.second.level <= level)) + { + continue; + } + + if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, topic))) + { + continue; + } + + if (pair.second.format == Config::Sink::Format::Json) + { + JsonString jsonString{msg, topic}; + pair.first->log(now, spdlog::source_loc{}, to_spdlog(level), fmt::format("{}", jsonString)); + } + else + { + pair.first->log(now, spdlog::source_loc{}, to_spdlog(level), + fmt::format("[{}] {}", to_string(topic), msg)); + } } - if (nullptr != _loggerRemote) + + for (const auto& pair : _remoteLogger) { - _loggerRemote->Log(now, level, topic, msg); + if (!(pair.second.level <= level)) + { + continue; + } + + if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, topic))) + { + continue; + } + pair.first->Log(now, level, topic, msg); } } @@ -563,17 +565,17 @@ void Logger::Critical(Topic topic, const std::string& msg) void Logger::RegisterRemoteLogging(const LogMsgHandler& handler) { - if (nullptr != _loggerRemote) + for (const auto& pair : _remoteLogger) { - _loggerRemote->RegisterRemoteLogging(handler); + pair.first->RegisterRemoteLogging(handler); } } void Logger::DisableRemoteLogging() { - if (nullptr != _loggerRemote) + for (const auto& pair : _remoteLogger) { - _loggerRemote->DisableRemoteLogging(); + pair.first->DisableRemoteLogging(); } } @@ -581,19 +583,17 @@ Level Logger::GetLogLevel() const { auto lvl = to_spdlog(Level::Critical); - if (nullptr != _loggerSimple) - { - lvl = lvl < _loggerSimple->level() ? lvl : _loggerSimple->level(); - } - if (nullptr != _loggerJson) + for (const auto& pair : _spdlogLogger) { - lvl = lvl < _loggerJson->level() ? lvl : _loggerJson->level(); + lvl = lvl < pair.first->level() ? lvl : pair.first->level(); } - if (nullptr != _loggerRemote) + + for (const auto& pair : _remoteLogger) { - lvl = lvl < to_spdlog(_loggerRemote->level()) ? lvl : to_spdlog(_loggerRemote->level()); + lvl = lvl < to_spdlog(pair.first->level()) ? lvl : to_spdlog(pair.first->level()); } + return from_spdlog(lvl); } diff --git a/SilKit/source/services/logging/Logger.hpp b/SilKit/source/services/logging/Logger.hpp index 22ce2cbee..ef3069620 100755 --- a/SilKit/source/services/logging/Logger.hpp +++ b/SilKit/source/services/logging/Logger.hpp @@ -176,15 +176,26 @@ class Logger : public ILoggerInternal // Private members Config::Logging _config; - std::shared_ptr _loggerJson; - std::shared_ptr _loggerSimple; - std::shared_ptr _loggerRemote; - bool IsTopicEnabled(Topic topic) const + std::map, Config::Sink> _spdlogLogger; + std::map, Config::Sink> _remoteLogger; + + + bool IsTopicEnabled(const std::vector& enabledTopics, + const std::vector& disabledTopics, + const Topic msgTopic) const { - if (!_config.disabledTopics.empty()) + auto returnVal = true; + + if (!enabledTopics.empty()) + { + returnVal = std::find(enabledTopics.begin(), enabledTopics.end(), msgTopic) != enabledTopics.end(); + } + + if (returnVal && !disabledTopics.empty()) { - return std::find(_config.disabledTopics.begin(), _config.disabledTopics.end(), topic) == _config.disabledTopics.end(); + return std::find(disabledTopics.begin(), disabledTopics.end(), msgTopic) + == disabledTopics.end(); } return true; } diff --git a/SilKit/source/services/logging/LoggerMessage.hpp b/SilKit/source/services/logging/LoggerMessage.hpp index ac55a84cf..b2afd0380 100644 --- a/SilKit/source/services/logging/LoggerMessage.hpp +++ b/SilKit/source/services/logging/LoggerMessage.hpp @@ -140,7 +140,7 @@ class LoggerMessage private: ILoggerInternal* _logger; Level _level; - Topic _topic; + Topic _topic{Topic::None}; std::string _msg; std::vector> _keyValues; }; From 2ee3a48a1d2deb675e49c3b79e5724237fb708dd Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Wed, 25 Mar 2026 09:28:18 +0100 Subject: [PATCH 04/23] fixup! Add topics in log message --- SilKit/source/config/YamlReader.cpp | 2 +- SilKit/source/services/logging/Logger.cpp | 2 -- SilKit/source/services/logging/Logger.hpp | 15 ++++++++++----- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/SilKit/source/config/YamlReader.cpp b/SilKit/source/config/YamlReader.cpp index b52c71825..6236490d5 100644 --- a/SilKit/source/config/YamlReader.cpp +++ b/SilKit/source/config/YamlReader.cpp @@ -238,7 +238,7 @@ void YamlReader::Read(SilKit::Config::Sink& obj) } obj.disabledTopics.push_back(enumTopic); } - + temp.clear(); OptionalRead(temp, "EnabledTopics"); for (auto&& topic : temp) { diff --git a/SilKit/source/services/logging/Logger.cpp b/SilKit/source/services/logging/Logger.cpp index 65f595868..2fe0d1b4a 100644 --- a/SilKit/source/services/logging/Logger.cpp +++ b/SilKit/source/services/logging/Logger.cpp @@ -592,8 +592,6 @@ Level Logger::GetLogLevel() const { lvl = lvl < to_spdlog(pair.first->level()) ? lvl : to_spdlog(pair.first->level()); } - - return from_spdlog(lvl); } diff --git a/SilKit/source/services/logging/Logger.hpp b/SilKit/source/services/logging/Logger.hpp index ef3069620..06aa278a8 100755 --- a/SilKit/source/services/logging/Logger.hpp +++ b/SilKit/source/services/logging/Logger.hpp @@ -186,18 +186,23 @@ class Logger : public ILoggerInternal const Topic msgTopic) const { auto returnVal = true; + auto inEnabledTopics = false; + auto inDisabledTopics = false; if (!enabledTopics.empty()) { - returnVal = std::find(enabledTopics.begin(), enabledTopics.end(), msgTopic) != enabledTopics.end(); + inEnabledTopics = std::find(enabledTopics.begin(), enabledTopics.end(), msgTopic) != enabledTopics.end(); } - if (returnVal && !disabledTopics.empty()) + if (!disabledTopics.empty()) { - return std::find(disabledTopics.begin(), disabledTopics.end(), msgTopic) - == disabledTopics.end(); + inDisabledTopics = std::find(disabledTopics.begin(), disabledTopics.end(), msgTopic) + != disabledTopics.end(); } - return true; + + returnVal = !inDisabledTopics && (inEnabledTopics == !enabledTopics.empty()); + + return returnVal; } }; From 7e7ee9d35eacfc17c6e5be8b2018f52fdf3d138f Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Wed, 8 Apr 2026 13:51:55 +0200 Subject: [PATCH 05/23] Roll out the new internal logger interface --- .../services/logging/LoggingDatatypes.hpp | 19 ++- .../silkit/services/logging/string_utils.hpp | 14 +- .../internal/traits/SilKitLoggingTraits.hpp | 63 +++++++ .../core/participant/Participant_impl.hpp | 157 ++++++++++-------- .../services/logging/ILoggerInternal.hpp | 10 ++ SilKit/source/services/logging/Logger.hpp | 7 + .../source/services/logging/LoggerMessage.hpp | 88 ++++++++-- .../source/services/logging/LoggingSerdes.cpp | 8 +- SilKit/source/services/logging/MockLogger.hpp | 6 + .../logging/StructuredLoggingKeys.hpp | 3 + .../orchestration/SystemStateTracker.cpp | 70 ++++---- .../orchestration/TimeSyncService.cpp | 132 ++++++++------- 12 files changed, 377 insertions(+), 200 deletions(-) create mode 100644 SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp diff --git a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp index ea16cb09c..0ee0ce92b 100644 --- a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp +++ b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp @@ -27,15 +27,16 @@ enum class Level : uint32_t */ enum class Topic : uint32_t { - None = 0, - User = 1, //!< User defind log message - LifeCycle = 2, //!< Log message of the lifecycle - SystemStateTracker = 3, - MessageTracing = 4, - ServiceDiscovery = 5, - Asio = 6, - TimeSyncService = 7, //!< Log message of the time sync service - Invalid = 0xffffffff + None = 0, //!< Log message without topic + User = 1, //!< Log message of the SIL Kit user + LifeCycle = 2, //!< Log message of the lifecycle + SystemState = 3, //!< Log message of the system state + MessageTracing = 4, //!< Log message of the message tracing + ServiceDiscovery = 5, //!< Log message of the service discovery + Asio = 6, //!< Log message of the asio + TimeSyncService = 7, //!< Log message of the time sync service + Participant = 8, //!< Log message of the participant + Invalid = 0xffffffff //!< Invalid log message topic }; diff --git a/SilKit/include/silkit/services/logging/string_utils.hpp b/SilKit/include/silkit/services/logging/string_utils.hpp index 606676839..4988e9f47 100644 --- a/SilKit/include/silkit/services/logging/string_utils.hpp +++ b/SilKit/include/silkit/services/logging/string_utils.hpp @@ -109,8 +109,8 @@ std::ostream& operator<<(std::ostream& outStream, const Topic& topic) case Topic::LifeCycle: outStream << "lifecycle"; break; - case Topic::SystemStateTracker: - outStream << "systemstatetracker"; + case Topic::SystemState: + outStream << "systemstate"; break; case Topic::MessageTracing: outStream << "messagetracing"; @@ -118,6 +118,9 @@ std::ostream& operator<<(std::ostream& outStream, const Topic& topic) case Topic::ServiceDiscovery: outStream << "servicediscovery"; break; + case Topic::Participant: + outStream << "participant"; + break; case Topic::None: outStream << "none"; break; @@ -138,13 +141,14 @@ inline Topic from_topic_string(const std::string& topicStr) return Topic::TimeSyncService; if (topic == "lifecycle") return Topic::LifeCycle; - if (topic == "systemstatetracker") - return Topic::SystemStateTracker; + if (topic == "systemstate") + return Topic::SystemState; if (topic == "messagetracing") return Topic::MessageTracing; if (topic == "servicediscovery") return Topic::ServiceDiscovery; - + if (topic == "participant") + return Topic::Participant; return Topic::Invalid; } /* diff --git a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp new file mode 100644 index 000000000..e26326657 --- /dev/null +++ b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: 2022 Vector Informatik GmbH +// +// SPDX-License-Identifier: MIT + +#pragma once +#include "internal_fwd.hpp" +#include "silkit/services/logging/LoggingDatatypes.hpp" + + +namespace VSilKit { +class SystemStateTracker; +} + +namespace SilKit { +namespace Core { +class IParticipantInternal; +} +} + + +namespace SilKit { +namespace Core { + +// Trait template (default) +template +struct TopicTraits +{ + static constexpr const SilKit::Services::Logging::Topic Topic() + { + return SilKit::Services::Logging::Topic::None; + } +}; + + +// The final service traits +template +struct SilKitTopicTrait : TopicTraits +{ +}; + + + +#define DefineSilKitLoggingTrait_Topic(Component,TopicName) \ + template <> \ + struct TopicTraits \ + { \ + static constexpr const SilKit::Services::Logging::Topic Topic() \ + { \ + return TopicName; \ + } \ + } + +DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeSyncService, SilKit::Services::Logging::Topic::TimeSyncService); + +DefineSilKitLoggingTrait_Topic(SilKit::Core::IParticipantInternal, SilKit::Services::Logging::Topic::Participant); + +DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::SystemState, SilKit::Services::Logging::Topic::SystemState); +DefineSilKitLoggingTrait_Topic(VSilKit::SystemStateTracker, SilKit::Services::Logging::Topic::SystemState); + + + +} // namespace Core +} // namespace SilKit diff --git a/SilKit/source/core/participant/Participant_impl.hpp b/SilKit/source/core/participant/Participant_impl.hpp index 0010dcc57..3ed1c4ed7 100644 --- a/SilKit/source/core/participant/Participant_impl.hpp +++ b/SilKit/source/core/participant/Participant_impl.hpp @@ -101,12 +101,20 @@ Participant::Participant(Config::ParticipantConfiguration par dynamic_cast(*_metricsManager).SetLogger(*_logger); _connection.SetLoggerInternal(_logger.get()); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Creating participant") + .AddKeyValue(Logging::Keys::participantName, GetParticipantName()) + .AddKeyValue(Logging::Keys::registryUri, _participantConfig.middleware.registryUri) + .AddKeyValue(Logging::Keys::silKitVersion, Version::StringImpl()) + .Dispatch(); + /* Logging::LoggerMessage lm{_logger.get(), Logging::Level::Info}; lm.SetMessage("Creating participant"); lm.SetKeyValue(Logging::Keys::participantName, GetParticipantName()); lm.SetKeyValue(Logging::Keys::registryUri, _participantConfig.middleware.registryUri); lm.SetKeyValue(Logging::Keys::silKitVersion, Version::StringImpl()); - lm.Dispatch(); + lm.SetTopic(Logging::Topic::Participant); + lm.Dispatch();*/ } @@ -146,7 +154,10 @@ void Participant::OnSilKitSimulationJoined() { _replayScheduler = std::make_unique(_participantConfig, this); _replayScheduler->ConfigureTimeProvider(&_timeProvider); - _logger->Info("Replay Scheduler active."); + + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Replay Scheduler active.") + .Dispatch(); } CreateParticipantAttributeMetrics(); @@ -198,9 +209,10 @@ void Participant::SetupRemoteLogging() } else { - Logging::Warn(GetLogger(), - "Failed to setup remote logging. Participant {} will not send and receive remote logs.", - GetParticipantName()); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("Failed to setup remote logging. The participant will not send and receive remote logs.") + .AddKeyValue(Logging::Keys::participantName, GetParticipantName()) + .Dispatch(); } } @@ -305,13 +317,13 @@ auto Participant::CreateCanController(const std::string& cano controller->RegisterServiceDiscovery(); - Logging::LoggerMessage lm{_logger.get(), Logging::Level::Trace}; - lm.SetMessage("Created controller"); - lm.SetKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]); - lm.SetKeyValue(Logging::Keys::controllerName, controllerConfig.name); - lm.SetKeyValue(Logging::Keys::network, controllerConfig.network.value()); - lm.SetKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()); - lm.Dispatch(); + _logger->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Created controller") + .AddKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]) + .AddKeyValue(Logging::Keys::controllerName, controllerConfig.name) + .AddKeyValue(Logging::Keys::network, controllerConfig.network.value()) + .AddKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()) + .Dispatch(); if (_replayScheduler) { @@ -344,13 +356,13 @@ auto Participant::CreateEthernetController( controller->RegisterServiceDiscovery(); - Logging::LoggerMessage lm{_logger.get(), Logging::Level::Trace}; - lm.SetMessage("Created controller"); - lm.SetKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]); - lm.SetKeyValue(Logging::Keys::controllerName, controllerConfig.name); - lm.SetKeyValue(Logging::Keys::network, controllerConfig.network.value()); - lm.SetKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()); - lm.Dispatch(); + _logger->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Created controller") + .AddKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]) + .AddKeyValue(Logging::Keys::controllerName, controllerConfig.name) + .AddKeyValue(Logging::Keys::network, controllerConfig.network.value()) + .AddKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()) + .Dispatch(); if (_replayScheduler) { @@ -383,13 +395,13 @@ auto Participant::CreateFlexrayController( controller->RegisterServiceDiscovery(); - Logging::LoggerMessage lm{_logger.get(), Logging::Level::Trace}; - lm.SetMessage("Created controller"); - lm.SetKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]); - lm.SetKeyValue(Logging::Keys::controllerName, controllerConfig.name); - lm.SetKeyValue(Logging::Keys::network, controllerConfig.network.value()); - lm.SetKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()); - lm.Dispatch(); + _logger->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Created controller") + .AddKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]) + .AddKeyValue(Logging::Keys::controllerName, controllerConfig.name) + .AddKeyValue(Logging::Keys::network, controllerConfig.network.value()) + .AddKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()) + .Dispatch(); auto* traceSource = dynamic_cast(controller); if (traceSource) @@ -416,13 +428,13 @@ auto Participant::CreateLinController(const std::string& cano controller->RegisterServiceDiscovery(); - Logging::LoggerMessage lm{_logger.get(), Logging::Level::Trace}; - lm.SetMessage("Created controller"); - lm.SetKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]); - lm.SetKeyValue(Logging::Keys::controllerName, controllerConfig.name); - lm.SetKeyValue(Logging::Keys::network, controllerConfig.network.value()); - lm.SetKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()); - lm.Dispatch(); + _logger->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Created controller") + .AddKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]) + .AddKeyValue(Logging::Keys::controllerName, controllerConfig.name) + .AddKeyValue(Logging::Keys::network, controllerConfig.network.value()) + .AddKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()) + .Dispatch(); if (_replayScheduler) { @@ -528,16 +540,15 @@ auto Participant::CreateDataPublisher(const std::string& cano if (GetLogger()->GetLogLevel() <= Logging::Level::Trace) { - Logging::LoggerMessage lm{_logger.get(), Logging::Level::Trace}; - lm.SetMessage("Created controller"); - lm.SetKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]); - lm.SetKeyValue(Logging::Keys::controllerName, controllerConfig.name); - lm.SetKeyValue(Logging::Keys::pubSubTopic, configuredDataNodeSpec.Topic()); - lm.SetKeyValue(Logging::Keys::mediaType, configuredDataNodeSpec.MediaType()); - lm.SetKeyValue(Logging::Keys::network, network); - lm.SetKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()); - lm.SetKeyValue(configuredDataNodeSpec.Labels()); - lm.Dispatch(); + _logger->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Created controller") + .AddKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]) + .AddKeyValue(Logging::Keys::controllerName, controllerConfig.name) + .AddKeyValue(Logging::Keys::network, network) + .AddKeyValue(Logging::Keys::pubSubTopic, configuredDataNodeSpec.Topic()) + .AddKeyValue(Logging::Keys::mediaType, configuredDataNodeSpec.MediaType()) + .AddKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()) + .Dispatch(); } auto* traceSource = dynamic_cast(controller); @@ -597,16 +608,16 @@ auto Participant::CreateDataSubscriber( if (GetLogger()->GetLogLevel() <= Logging::Level::Trace) { - Logging::LoggerMessage lm{_logger.get(), Logging::Level::Trace}; - lm.SetMessage("Created controller"); - lm.SetKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]); - lm.SetKeyValue(Logging::Keys::controllerName, controllerConfig.name); - lm.SetKeyValue(Logging::Keys::pubSubTopic, configuredDataNodeSpec.Topic()); - lm.SetKeyValue(Logging::Keys::mediaType, configuredDataNodeSpec.MediaType()); - lm.SetKeyValue(Logging::Keys::network, network); - lm.SetKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()); - lm.SetKeyValue(configuredDataNodeSpec.Labels()); - lm.Dispatch(); + _logger->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Created controller") + .AddKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]) + .AddKeyValue(Logging::Keys::controllerName, controllerConfig.name) + .AddKeyValue(Logging::Keys::network, network) + .AddKeyValue(Logging::Keys::pubSubTopic, configuredDataNodeSpec.Topic()) + .AddKeyValue(Logging::Keys::mediaType, configuredDataNodeSpec.MediaType()) + .AddKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()) + .AddKeyValue(configuredDataNodeSpec.Labels()) + .Dispatch(); } auto* traceSource = dynamic_cast(controller); @@ -690,16 +701,16 @@ auto Participant::CreateRpcClient( if (GetLogger()->GetLogLevel() <= Logging::Level::Trace) { - Logging::LoggerMessage lm{_logger.get(), Logging::Level::Trace}; - lm.SetMessage("Created controller"); - lm.SetKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]); - lm.SetKeyValue(Logging::Keys::controllerName, controllerConfig.name); - lm.SetKeyValue(Logging::Keys::controllerFuncName, configuredRpcSpec.FunctionName()); - lm.SetKeyValue(Logging::Keys::mediaType, configuredRpcSpec.MediaType()); - lm.SetKeyValue(Logging::Keys::network, network); - lm.SetKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()); - lm.SetKeyValue(configuredRpcSpec.Labels()); - lm.Dispatch(); + _logger->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Created controller") + .AddKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]) + .AddKeyValue(Logging::Keys::controllerName, controllerConfig.name) + .AddKeyValue(Logging::Keys::controllerFuncName, configuredRpcSpec.FunctionName()) + .AddKeyValue(Logging::Keys::mediaType, configuredRpcSpec.MediaType()) + .AddKeyValue(Logging::Keys::network, network) + .AddKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()) + .AddKeyValue(configuredRpcSpec.Labels()) + .Dispatch(); } return controller; @@ -746,16 +757,16 @@ auto Participant::CreateRpcServer( if (GetLogger()->GetLogLevel() <= Logging::Level::Trace) { - Logging::LoggerMessage lm{_logger.get(), Logging::Level::Trace}; - lm.SetMessage("Created controller"); - lm.SetKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]); - lm.SetKeyValue(Logging::Keys::controllerName, controllerConfig.name); - lm.SetKeyValue(Logging::Keys::controllerFuncName, configuredRpcSpec.FunctionName()); - lm.SetKeyValue(Logging::Keys::mediaType, configuredRpcSpec.MediaType()); - lm.SetKeyValue(Logging::Keys::network, network); - lm.SetKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()); - lm.SetKeyValue(configuredRpcSpec.Labels()); - lm.Dispatch(); + _logger->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Created controller") + .AddKeyValue(Logging::Keys::controllerType, supplementalData[SilKit::Core::Discovery::controllerType]) + .AddKeyValue(Logging::Keys::controllerName, controllerConfig.name) + .AddKeyValue(Logging::Keys::controllerFuncName, configuredRpcSpec.FunctionName()) + .AddKeyValue(Logging::Keys::mediaType, configuredRpcSpec.MediaType()) + .AddKeyValue(Logging::Keys::network, network) + .AddKeyValue(Logging::Keys::serviceName, controller->GetServiceDescriptor().to_string()) + .AddKeyValue(configuredRpcSpec.Labels()) + .Dispatch(); } return controller; diff --git a/SilKit/source/services/logging/ILoggerInternal.hpp b/SilKit/source/services/logging/ILoggerInternal.hpp index c31f6aa8e..9f27052b6 100644 --- a/SilKit/source/services/logging/ILoggerInternal.hpp +++ b/SilKit/source/services/logging/ILoggerInternal.hpp @@ -11,6 +11,7 @@ #include "StructuredLoggingKeys.hpp" #include "SilKitFmtFormatters.hpp" #include "fmt/format.h" +#include "traits/SilKitLoggingTraits.hpp" namespace SilKit { namespace Services { @@ -23,6 +24,15 @@ struct ILoggerInternal : ILogger { virtual void ProcessLoggerMessage(const LoggerMessage& msg) = 0; virtual void LogReceivedMsg(const LogMsg& msg) = 0; + + template + LoggerMessage MakeMessage(Level level, ServiceT&) + { + using T = std::decay_t; + return MakeMessage(level, SilKit::Core::SilKitTopicTrait::Topic()); + } + + virtual LoggerMessage MakeMessage(Level level, Topic topic) = 0; }; diff --git a/SilKit/source/services/logging/Logger.hpp b/SilKit/source/services/logging/Logger.hpp index 06aa278a8..f8600a03f 100755 --- a/SilKit/source/services/logging/Logger.hpp +++ b/SilKit/source/services/logging/Logger.hpp @@ -164,8 +164,15 @@ class Logger : public ILoggerInternal void DisableRemoteLogging(); //void LogReceivedMsg(const LogMsg& msg); + auto GetLogLevel() const -> Level override; + LoggerMessage MakeMessage(Level level, Topic topic) override + { + return LoggerMessage(this, level, topic); + } + + // ILoggerInternal void ProcessLoggerMessage(const LoggerMessage& msg) override; diff --git a/SilKit/source/services/logging/LoggerMessage.hpp b/SilKit/source/services/logging/LoggerMessage.hpp index b2afd0380..de4cf7020 100644 --- a/SilKit/source/services/logging/LoggerMessage.hpp +++ b/SilKit/source/services/logging/LoggerMessage.hpp @@ -37,6 +37,13 @@ class LoggerMessage { } + LoggerMessage(ILoggerInternal* logger, Level level, Topic topic) + : _logger(logger) + , _level(level) + , _topic(topic) + { + } + LoggerMessage(ILoggerInternal* logger, const LogMsg& msg) : _logger(logger) , _level(msg.level) @@ -46,7 +53,6 @@ class LoggerMessage { } - template void FormatMessage(fmt::format_string fmt, Args&&... args) { @@ -56,56 +62,103 @@ class LoggerMessage } } - void SetMessage(std::string newMsg) + template + LoggerMessage& SetMessage(fmt::format_string fmt, Args&&... args) { if (_logger->GetLogLevel() <= _level) { - _msg = std::move(newMsg); + _msg = fmt::format(fmt, std::forward(args)...); } + return *this; } + auto SetTopic(Topic topic) -> LoggerMessage& + { + _topic = topic; + return *this; + } template - void FormatKeyValue(Key&& key, fmt::format_string fmt, Args&&... args) + LoggerMessage& AddKeyValue(Key&& key, Args&&... args) + { + FormatKeyValue(key, "{}", std::forward(args)...); + return *this; + } + + LoggerMessage& AddKeyValue(const Core::ServiceDescriptor& descriptor) { if (_logger->GetLogLevel() <= _level) { - auto&& formattedValue = fmt::format(fmt, std::forward(args)...); - _keyValues.emplace_back(std::forward(key), formattedValue); + for (const auto& pair : descriptor.to_keyValues()) + { + SetKeyValue(pair.first, pair.second); + } } + return *this; } - - void SetKeyValue(const std::vector& labels) + LoggerMessage& AddKeyValue(const std::vector& labels) { if (_logger->GetLogLevel() <= _level) { SetKeyValue(Keys::label, FormatLabelsForLogging(labels)); } + return *this; } - void SetKeyValue(const Core::ServiceDescriptor& descriptor) + template + LoggerMessage& SetKeyValue(Key&& key, Args&&... args) { if (_logger->GetLogLevel() <= _level) { - for (const auto& pair : descriptor.to_keyValues()) + for (auto& kv : _keyValues) { - SetKeyValue(pair.first, pair.second); + if (kv.first == key) + { + auto&& formattedValue = fmt::format("{}", std::forward(args)...); + kv.second = formattedValue; + return *this; + } } + return AddKeyValue(key, std::forward(args)...); } + return *this; } - template - void SetKeyValue(Key&& key, Value&& value) + + auto SetLevel(const Level level) -> LoggerMessage& + { + _level = level; + return *this; + } + + template + void FormatKeyValue(Key&& key, fmt::format_string fmt, Args&&... args) { if (_logger->GetLogLevel() <= _level) { - _keyValues.emplace_back(std::forward(key), std::forward(value)); + auto&& formattedValue = fmt::format(fmt, std::forward(args)...); + _keyValues.emplace_back(std::forward(key), formattedValue); } } - auto SetTopic(Topic topic) + + void SetKeyValue(const std::vector& labels) { - _topic = topic; + if (_logger->GetLogLevel() <= _level) + { + SetKeyValue(Keys::label, FormatLabelsForLogging(labels)); + } + } + + void SetKeyValue(const Core::ServiceDescriptor& descriptor) + { + if (_logger->GetLogLevel() <= _level) + { + for (const auto& pair : descriptor.to_keyValues()) + { + SetKeyValue(pair.first, pair.second); + } + } } @@ -129,12 +182,13 @@ class LoggerMessage return _msg; } - void Dispatch() + LoggerMessage Dispatch() { if (_logger->GetLogLevel() <= _level) { _logger->ProcessLoggerMessage(*this); } + return std::move(*this); } private: diff --git a/SilKit/source/services/logging/LoggingSerdes.cpp b/SilKit/source/services/logging/LoggingSerdes.cpp index 5d2a792ab..69d1e097b 100644 --- a/SilKit/source/services/logging/LoggingSerdes.cpp +++ b/SilKit/source/services/logging/LoggingSerdes.cpp @@ -24,16 +24,20 @@ inline MessageBuffer& operator>>(MessageBuffer& buffer, SourceLoc& sourceLoc) inline MessageBuffer& operator<<(MessageBuffer& buffer, const LogMsg& msg) { - buffer << msg.loggerName << msg.level << msg.topic << msg.time << msg.source << msg.payload << msg.keyValues; + buffer << msg.loggerName << msg.level << msg.time << msg.source << msg.payload << msg.keyValues << msg.topic; return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, LogMsg& msg) { - buffer >> msg.loggerName >> msg.level >> msg.topic >> msg.time >> msg.source >> msg.payload; + buffer >> msg.loggerName >> msg.level >> msg.time >> msg.source >> msg.payload; if (buffer.RemainingBytesLeft() > 0) { buffer >> msg.keyValues; } + if (buffer.RemainingBytesLeft() > 0) + { + buffer >> msg.topic; + } return buffer; } diff --git a/SilKit/source/services/logging/MockLogger.hpp b/SilKit/source/services/logging/MockLogger.hpp index 4b754d629..b7f77c824 100644 --- a/SilKit/source/services/logging/MockLogger.hpp +++ b/SilKit/source/services/logging/MockLogger.hpp @@ -57,6 +57,12 @@ class MockLogger : public ::SilKit::Services::Logging::ILoggerInternal // This is just for demonstration, actual test code will use EXPECT_CALL } + + LoggerMessage MakeMessage(Level level, Topic topic) + { + return LoggerMessage(this, level, topic); + } + public: MOCK_METHOD(void, Log, (Level level, const std::string& msg), (override)); MOCK_METHOD(void, Log, (Level level, Topic topic, const std::string& msg), (override)); diff --git a/SilKit/source/services/logging/StructuredLoggingKeys.hpp b/SilKit/source/services/logging/StructuredLoggingKeys.hpp index 784f821d8..87592b066 100644 --- a/SilKit/source/services/logging/StructuredLoggingKeys.hpp +++ b/SilKit/source/services/logging/StructuredLoggingKeys.hpp @@ -21,6 +21,9 @@ constexpr std::string_view raw{"Raw"}; constexpr std::string_view waitingTime{"WaitingTime"}; constexpr std::string_view executionTime{"ExecutionTime"}; +constexpr std::string_view animationFactor{"AnimationFactor"}; +constexpr std::string_view timeoutTime{"TimeoutTime"}; + constexpr std::string_view participantName{"ParticipantName"}; constexpr std::string_view registryUri{"RegistryUri"}; diff --git a/SilKit/source/services/orchestration/SystemStateTracker.cpp b/SilKit/source/services/orchestration/SystemStateTracker.cpp index 2027e07df..bc3a73e0f 100644 --- a/SilKit/source/services/orchestration/SystemStateTracker.cpp +++ b/SilKit/source/services/orchestration/SystemStateTracker.cpp @@ -142,13 +142,12 @@ auto SystemStateTracker::UpdateParticipantStatus(const ParticipantStatus& newPar if (_logger != nullptr) { - Log::LoggerMessage lm{_logger, Log::Level::Debug}; - lm.SetMessage("Updating participant status"); - lm.SetKeyValue(Log::Keys::participantName, participantName); - lm.FormatKeyValue(Log::Keys::oldParticipantState, "{}", oldParticipantState); - lm.FormatKeyValue(Log::Keys::newParticipantState, "{}", newParticipantState); - lm.SetTopic(Log::Topic::SystemStateTracker); - lm.Dispatch(); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Updating participant status") + .AddKeyValue(Log::Keys::participantName, participantName) + .AddKeyValue(Log::Keys::oldParticipantState, oldParticipantState) + .AddKeyValue(Log::Keys::newParticipantState, newParticipantState) + .Dispatch(); } // Check if transition from the old to the new participant state is valid @@ -158,15 +157,14 @@ auto SystemStateTracker::UpdateParticipantStatus(const ParticipantStatus& newPar { const auto logLevel = IsRequiredParticipant(participantName) ? Log::Level::Warn : Log::Level::Debug; - Log::LoggerMessage lm{_logger, logLevel}; - lm.SetMessage("SystemMonitor detected invalid ParticipantState transition!"); - lm.SetKeyValue(Log::Keys::participantName, participantName); - lm.FormatKeyValue(Log::Keys::oldParticipantState, "{}", oldParticipantState); - lm.FormatKeyValue(Log::Keys::newParticipantState, "{}", newParticipantState); - lm.SetKeyValue(Log::Keys::enterTime, FormatTimePoint(newParticipantStatus.enterTime)); - lm.SetKeyValue(Log::Keys::enterReason, newParticipantStatus.enterReason); - lm.SetTopic(Log::Topic::SystemStateTracker); - lm.Dispatch(); + _logger->MakeMessage(logLevel, *this) + .SetMessage("SystemMonitor detected invalid ParticipantState transition!") + .AddKeyValue(Log::Keys::participantName, participantName) + .AddKeyValue(Log::Keys::oldParticipantState, oldParticipantState) + .AddKeyValue(Log::Keys::newParticipantState, newParticipantState) + .AddKeyValue(Log::Keys::enterTime, FormatTimePoint(newParticipantStatus.enterTime)) + .AddKeyValue(Log::Keys::enterReason, newParticipantStatus.enterReason) + .Dispatch(); } // NB: Failing validation doesn't actually stop the participants state from being changed, it just logs the // invalid transition @@ -188,11 +186,10 @@ auto SystemStateTracker::UpdateParticipantStatus(const ParticipantStatus& newPar result.participantStateChanged = true; if (_logger != nullptr) { - Log::LoggerMessage lm{_logger, Log::Level::Debug}; - lm.SetMessage("The participant state has changed!"); - lm.SetKeyValue(Log::Keys::participantName, participantName); - lm.SetTopic(Log::Topic::SystemStateTracker); - lm.Dispatch(); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("The participant state has changed!") + .AddKeyValue(Log::Keys::participantName, participantName) + .Dispatch(); } if (IsRequiredParticipant(participantName)) @@ -202,26 +199,24 @@ auto SystemStateTracker::UpdateParticipantStatus(const ParticipantStatus& newPar if (_logger != nullptr) { - Log::LoggerMessage lm{_logger, Log::Level::Debug}; - lm.SetMessage("Computed new system state update!"); - lm.SetKeyValue(Log::Keys::participantName, participantName); - lm.FormatKeyValue(Log::Keys::oldParticipantState, "{}", oldSystemState); - lm.FormatKeyValue(Log::Keys::newParticipantState, "{}", newSystemState); - lm.SetTopic(Log::Topic::SystemStateTracker); - lm.Dispatch(); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Computed new system state update!") + .AddKeyValue(Log::Keys::participantName, participantName) + .AddKeyValue(Log::Keys::oldParticipantState, oldSystemState) + .AddKeyValue(Log::Keys::newParticipantState, newSystemState) + .Dispatch(); } if (oldSystemState != newSystemState) { if (_logger != nullptr) { - Log::LoggerMessage lm{_logger, Log::Level::Debug}; - lm.SetMessage("The system state has changed!"); - lm.SetKeyValue(Log::Keys::participantName, participantName); - lm.FormatKeyValue(Log::Keys::oldParticipantState, "{}", oldSystemState); - lm.FormatKeyValue(Log::Keys::newParticipantState, "{}", newSystemState); - lm.SetTopic(Log::Topic::SystemStateTracker); - lm.Dispatch(); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("The system state has changed!") + .AddKeyValue(Log::Keys::participantName, participantName) + .AddKeyValue(Log::Keys::oldParticipantState, oldSystemState) + .AddKeyValue(Log::Keys::newParticipantState, newSystemState) + .Dispatch(); } _systemState = newSystemState; @@ -463,7 +458,10 @@ auto SystemStateTracker::ComputeSystemState(ParticipantState newParticipantState newSystemState = SS::Error; break; default: - Log::Debug(_logger, "Unhandled participant state {}", newParticipantState); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Unhandled participant state") + .AddKeyValue(Log::Keys::newParticipantState, newParticipantState) + .Dispatch(); break; } diff --git a/SilKit/source/services/orchestration/TimeSyncService.cpp b/SilKit/source/services/orchestration/TimeSyncService.cpp index 9f2ed5300..c4ee4a355 100644 --- a/SilKit/source/services/orchestration/TimeSyncService.cpp +++ b/SilKit/source/services/orchestration/TimeSyncService.cpp @@ -306,12 +306,21 @@ TimeSyncService::TimeSyncService(Core::IParticipantInternal* participant, ITimeP _isCoupledToWallClock = _animationFactor != 0.0; if (_isCoupledToWallClock) { - Debug(_logger, "TimeSyncService: Coupled to the local wall clock with animation factor {}", _animationFactor); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("Coupled to the local wall clock with animation factor") + .AddKeyValue(Logging::Keys::animationFactor, _animationFactor) + .Dispatch(); } _watchDog.SetWarnHandler([logger = _logger](std::chrono::milliseconds timeout) { - Warn(logger, "SimStep did not finish within soft time limit. Timeout detected after {} ms", - std::chrono::duration_cast>(timeout).count()); + + logger->MakeMessage(Logging::Level::Warn, Logging::Topic::TimeSyncService) + .SetMessage("SimStep did not finish within soft time limit. Timeout detected after {} ms") + .AddKeyValue(Logging::Keys::timeoutTime, std::chrono::duration_cast>(timeout).count()) + .Dispatch(); + + /* Warn(logger, "SimStep did not finish within soft time limit. Timeout detected after {} ms", + std::chrono::duration_cast>(timeout).count());*/ }); _watchDog.SetErrorHandler([this](std::chrono::milliseconds timeout) { std::stringstream buffer; @@ -352,9 +361,10 @@ TimeSyncService::TimeSyncService(Core::IParticipantInternal* participant, ITimeP return; } - Debug(_participant->GetLogger(), - "TimeSyncService: Participant \'{}\' is added to the distributed time synchronization", - descriptorParticipantName); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("Participant is added to the distributed time synchronization") + .AddKeyValue(Logging::Keys::participantName, descriptorParticipantName) + .Dispatch(); _timeConfiguration.AddSynchronizedParticipant(descriptorParticipantName); @@ -364,19 +374,22 @@ TimeSyncService::TimeSyncService(Core::IParticipantInternal* participant, ITimeP // Resend our NextSimTask again because it is not assured that the late-joiner has seen our last update. // At this point, the late-joiner will receive it because its TimeSyncPolicy is configured when the // discovery arrives that triggered this handler. - Debug(_participant->GetLogger(), - "Participant \'{}\' is joining an already running simulation. Resending our " - "NextSimTask.", - descriptorParticipantName); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("Participant is joining an already running simulation. Resending our NextSimTask.") + .Dispatch(); if (GetTimeSyncPolicy()->IsExecutingSimStep()) { - Debug(_participant->GetLogger(), "Sending currently executing simulation step"); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("Sending currently executing simulation step") + .Dispatch(); SendMsg(_timeConfiguration.CurrentSimStep()); } else { - Debug(_participant->GetLogger(), "Sending next simulation step"); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("Sending next simulation step") + .Dispatch(); SendMsg(_timeConfiguration.NextSimStep()); } } @@ -386,10 +399,10 @@ TimeSyncService::TimeSyncService(Core::IParticipantInternal* participant, ITimeP // Other participant hopped off if (_timeConfiguration.RemoveSynchronizedParticipant(descriptorParticipantName)) { - Debug(_logger, - "TimeSyncService: Participant '{}' is no longer part of the " - "distributed time synchronization.", - descriptorParticipantName); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("TimeSyncService: Participant is no longer part of the distributed time synchronization.") + .AddKeyValue(Logging::Keys::participantName, descriptorParticipantName) + .Dispatch(); if (_timeSyncPolicy) { @@ -489,11 +502,10 @@ void TimeSyncService::ReceiveMsg(const IServiceEndpoint* from, const NextSimTask } else { - Logging::LoggerMessage lm{_logger, Logging::Level::Debug}; - lm.SetMessage("Received NextSimTask from participant \'{}\' but TimeSyncPolicy is not yet configured"); - lm.SetKeyValue(Logging::Keys::participantName, from->GetServiceDescriptor().GetParticipantName()); - lm.SetTopic(Logging::Topic::TimeSyncService); - lm.Dispatch(); + _logger->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Received NextSimTask from participant \'{}\' but TimeSyncPolicy is not yet configured") + .AddKeyValue(Logging::Keys::participantName, from->GetServiceDescriptor().GetParticipantName()) + .Dispatch(); } } @@ -507,15 +519,11 @@ void TimeSyncService::ExecuteSimStep(std::chrono::nanoseconds timePoint, std::ch const auto waitingDuration = _waitTimeMonitor.CurrentDuration(); const auto waitingDurationS = std::chrono::duration_cast(waitingDuration); - { - Logging::LoggerMessage lm{_logger, Logging::Level::Trace}; - lm.SetMessage("Starting next Simulation Step."); - lm.FormatKeyValue(Logging::Keys::waitingTime, "{}", - std::chrono::duration_cast(_waitTimeMonitor.CurrentDuration()).count()); - lm.FormatKeyValue(Logging::Keys::virtualTimeNS, "{}", timePoint.count()); - lm.SetTopic(Logging::Topic::TimeSyncService); - lm.Dispatch(); - } + _logger->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Starting next Simulation Step.") + .AddKeyValue(Logging::Keys::waitingTime, std::chrono::duration_cast(_waitTimeMonitor.CurrentDuration()).count()) + .AddKeyValue(Logging::Keys::virtualTimeNS, timePoint.count()) + .Dispatch(); if (_waitTimeMonitor.SampleCount() > 1) { @@ -553,12 +561,13 @@ void TimeSyncService::ExecuteSimStep(std::chrono::nanoseconds timePoint, std::ch void TimeSyncService::LogicalSimStepCompleted(std::chrono::duration logicalSimStepTimeMs) { _simStepCounterMetric->Add(1); - Logging::LoggerMessage lm{_logger, Logging::Level::Trace}; - lm.SetMessage("Finished Simulation Step."); - lm.FormatKeyValue(Logging::Keys::executionTime, "{}", logicalSimStepTimeMs.count()); - lm.FormatKeyValue(Logging::Keys::virtualTimeNS, "{}", Now().count()); - lm.SetTopic(Logging::Topic::TimeSyncService); - lm.Dispatch(); + + _logger->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Finished Simulation Step.") + .AddKeyValue(Logging::Keys::executionTime, logicalSimStepTimeMs.count()) + .AddKeyValue(Logging::Keys::virtualTimeNS, Now().count()) + .Dispatch(); + _waitTimeMonitor.StartMeasurement(); } @@ -566,14 +575,26 @@ void TimeSyncService::CompleteSimulationStep() { if (!GetTimeSyncPolicy()->IsExecutingSimStep()) { - Logging::LoggerMessage lm{_logger, Logging::Level::Debug}; + auto lm = _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("CompleteSimulationStep: calling _timeSyncPolicy->RequestNextStep") + .Dispatch(); + + lm.SetLevel(Logging::Level::Warn) + .SetMessage("CompleteSimulationStep() was called before the simulation step handler was invoked.") + .Dispatch(); + + + /* Logging::LoggerMessage lm{_logger, Logging::Level::Debug}; lm.SetMessage("CompleteSimulationStep: calling _timeSyncPolicy->RequestNextStep"); lm.Dispatch(); _logger->Warn("CompleteSimulationStep() was called before the simulation step handler was invoked."); + */ } else { - _logger->Debug("CompleteSimulationStep()"); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("CompleteSimulationStep()") + .Dispatch(); } _participant->ExecuteDeferred([this] { @@ -690,13 +711,12 @@ bool TimeSyncService::ParticipantHasAutonomousSynchronousCapability(const std::s { // We are a participant with autonomous lifecycle and virtual time sync. // The remote participant must support this, otherwise Hop-On / Hop-Off will fail. - Logging::LoggerMessage lm{_participant->GetLoggerInternal(), Logging::Level::Error}; - lm.SetMessage( - "This participant does not support simulations with participants that use an autonomous lifecycle " - "and virtual time synchronization. Please consider upgrading Participant. Aborting simulation..."); - lm.SetKeyValue(Logging::Keys::participantName, participantName); - lm.SetTopic(Logging::Topic::TimeSyncService); - lm.Dispatch(); + + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage( "This participant does not support simulations with participants that use an autonomous lifecycle " + "and virtual time synchronization. Please consider upgrading Participant. Aborting simulation...") + .AddKeyValue(Logging::Keys::participantName, participantName) + .Dispatch(); return false; } return true; @@ -708,14 +728,11 @@ bool TimeSyncService::AbortHopOnForCoordinatedParticipants() const { if (_lifecycleService->GetOperationMode() == OperationMode::Coordinated) { - Logging::LoggerMessage lm{_participant->GetLoggerInternal(), Logging::Level::Error}; - lm.SetMessage( - "This participant is running with a coordinated lifecycle and virtual time synchronization and wants " - "to join an already running simulation. This is not allowed, aborting simulation..."); - lm.SetKeyValue(Logging::Keys::participantName, _participant->GetParticipantName()); - lm.SetTopic(Logging::Topic::TimeSyncService); - lm.Dispatch(); - + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage("This participant is running with a coordinated lifecycle and virtual time synchronization and wants " + "to join an already running simulation. This is not allowed, aborting simulation...") + .AddKeyValue(Logging::Keys::participantName, _participant->GetParticipantName()) + .Dispatch(); _participant->GetSystemController()->AbortSimulation(); return true; } @@ -787,12 +804,11 @@ void TimeSyncService::StartWallClockCouplingThread(std::chrono::nanoseconds star if (GetTimeSyncPolicy()->IsExecutingSimStep()) { // AsyncSimStepHandler not completed? Execution is lagging behind. Don't send the NextSimStep now, but after completion. - Logging::LoggerMessage lm{_participant->GetLoggerInternal(), Logging::Level::Warn}; - lm.SetMessage("Simulation step was not completed in time to achieve wall clock coupling."); - lm.SetKeyValue(Logging::Keys::participantName, _participant->GetParticipantName()); - lm.SetTopic(Logging::Topic::TimeSyncService); - lm.Dispatch(); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("Simulation step was not completed in time to achieve wall clock coupling.") + .AddKeyValue(Logging::Keys::participantName, _participant->GetParticipantName()) + .Dispatch(); _wallClockReachedBeforeCompletion = true; } else From 289d66b787975b78683170c90690b3c9fed913d6 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Thu, 9 Apr 2026 14:54:41 +0200 Subject: [PATCH 06/23] 7e7ee9d35eacfc17c6e5be8b2018f52fdf3d138f --- .../silkit/services/logging/string_utils.hpp | 5 + .../internal/traits/SilKitLoggingTraits.hpp | 16 +- .../core/participant/Participant_impl.hpp | 34 +-- SilKit/source/core/vasio/VAsioConnection.cpp | 197 +++++++++++++----- .../services/logging/MessageTracing.hpp | 13 +- .../logging/StructuredLoggingKeys.hpp | 6 + .../source/services/logging/Test_Logger.cpp | 16 +- .../orchestration/TimeSyncService.cpp | 7 - 8 files changed, 200 insertions(+), 94 deletions(-) diff --git a/SilKit/include/silkit/services/logging/string_utils.hpp b/SilKit/include/silkit/services/logging/string_utils.hpp index 4988e9f47..844b5767f 100644 --- a/SilKit/include/silkit/services/logging/string_utils.hpp +++ b/SilKit/include/silkit/services/logging/string_utils.hpp @@ -121,6 +121,9 @@ std::ostream& operator<<(std::ostream& outStream, const Topic& topic) case Topic::Participant: outStream << "participant"; break; + case Topic::Asio: + outStream << "asio"; + break; case Topic::None: outStream << "none"; break; @@ -149,6 +152,8 @@ inline Topic from_topic_string(const std::string& topicStr) return Topic::ServiceDiscovery; if (topic == "participant") return Topic::Participant; + if (topic == "asio") + return Topic::Asio; return Topic::Invalid; } /* diff --git a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp index e26326657..b2250ef25 100644 --- a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp @@ -14,6 +14,10 @@ class SystemStateTracker; namespace SilKit { namespace Core { class IParticipantInternal; +class VAsioConnection; + +template +class Participant; } } @@ -50,9 +54,19 @@ struct SilKitTopicTrait : TopicTraits } \ } + +template +struct TopicTraits> +{ + static constexpr const SilKit::Services::Logging::Topic Topic() + { + return SilKit::Services::Logging::Topic::Participant; + } +}; + DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeSyncService, SilKit::Services::Logging::Topic::TimeSyncService); -DefineSilKitLoggingTrait_Topic(SilKit::Core::IParticipantInternal, SilKit::Services::Logging::Topic::Participant); +DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioConnection, SilKit::Services::Logging::Topic::Asio); DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::SystemState, SilKit::Services::Logging::Topic::SystemState); DefineSilKitLoggingTrait_Topic(VSilKit::SystemStateTracker, SilKit::Services::Logging::Topic::SystemState); diff --git a/SilKit/source/core/participant/Participant_impl.hpp b/SilKit/source/core/participant/Participant_impl.hpp index 3ed1c4ed7..b96c203e2 100644 --- a/SilKit/source/core/participant/Participant_impl.hpp +++ b/SilKit/source/core/participant/Participant_impl.hpp @@ -107,14 +107,6 @@ Participant::Participant(Config::ParticipantConfiguration par .AddKeyValue(Logging::Keys::registryUri, _participantConfig.middleware.registryUri) .AddKeyValue(Logging::Keys::silKitVersion, Version::StringImpl()) .Dispatch(); - /* - Logging::LoggerMessage lm{_logger.get(), Logging::Level::Info}; - lm.SetMessage("Creating participant"); - lm.SetKeyValue(Logging::Keys::participantName, GetParticipantName()); - lm.SetKeyValue(Logging::Keys::registryUri, _participantConfig.middleware.registryUri); - lm.SetKeyValue(Logging::Keys::silKitVersion, Version::StringImpl()); - lm.SetTopic(Logging::Topic::Participant); - lm.Dispatch();*/ } @@ -1751,7 +1743,9 @@ void Participant::AddTraceSinksToSourceInternal(ITraceMessage { if (config.useTraceSinks.empty()) { - Logging::Debug(GetLogger(), "Tracer on {}/{} not enabled, skipping", GetParticipantName(), config.name); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("Tracer on {}/{} not enabled, skipping", GetParticipantName(), config.name) + .Dispatch(); return; } auto findSinkByName = [this](const auto& name) { @@ -1764,8 +1758,9 @@ void Participant::AddTraceSinksToSourceInternal(ITraceMessage auto sinkIter = findSinkByName(sinkName); if (sinkIter == _traceSinks.end()) { - Logging::Warn(GetLogger(), "Tracing: the service '{}' refers to non-existing trace sink '{}'", config.name, - sinkName); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("Tracing: the service '{}' refers to non-existing trace sink '{}'", config.name, sinkName) + .Dispatch(); continue; } traceSource->AddSink((*sinkIter).get(), config.GetNetworkType()); @@ -1841,7 +1836,10 @@ void Participant::LogMismatchBetweenConfigAndPassedValue(cons << "Passed value: " << passedValue << std::endl << "Configured value: " << configuredValue << std::endl; - _logger->Info(ss.str()); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage(ss.str()) + .Dispatch(); + } template @@ -1857,7 +1855,9 @@ void Participant::LogMismatchBetweenConfigAndPassedValue(cons << "Passed value: " << fmt::format("{}", fmt::join(passedValue, ", ")) << std::endl << "Configured value: " << fmt::format("{}", fmt::join(configuredValue, ", ")) << std::endl; - _logger->Info(ss.str()); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage(ss.str()) + .Dispatch(); } template @@ -1940,7 +1940,9 @@ std::string Participant::GetServiceDescriptorString( { if (!_networkSimulatorInternal) { - Logging::Warn(GetLogger(), "GetServiceDescriptorString was queried, but no network simulator exists."); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("GetServiceDescriptorString was queried, but no network simulator exists.") + .Dispatch(); return ""; } return _networkSimulatorInternal->GetServiceDescriptorString(controllerDescriptor); @@ -1993,7 +1995,9 @@ auto Participant::GetOrCreateMetricsSender() -> VSilKit::IMet } else { - _logger->Debug("Refusing to create MetricsSender because no remote sinks are configured"); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("Refusing to create MetricsSender because no remote sinks are configured") + .Dispatch(); } } diff --git a/SilKit/source/core/vasio/VAsioConnection.cpp b/SilKit/source/core/vasio/VAsioConnection.cpp index 594ce5cac..e4ba74046 100644 --- a/SilKit/source/core/vasio/VAsioConnection.cpp +++ b/SilKit/source/core/vasio/VAsioConnection.cpp @@ -329,12 +329,20 @@ void VAsioConnection::OpenTcpAcceptors(const std::vector& acceptorE if (uri.Type() == Uri::UriType::Tcp && uri.Scheme() == "tcp") { - SilKit::Services::Logging::Debug(_logger, "Found TCP acceptor endpoint URI {} with host {} and port {}", - uriString, uri.Host(), uri.Port()); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Found TCP acceptor endpoint.") + .AddKeyValue(Log::Keys::uriString, uriString) + .AddKeyValue(Log::Keys::uriHost, uri.Host()) + .AddKeyValue(Log::Keys::uriPort, uri.Port()) + .Dispatch(); for (const auto& host : _ioContext->Resolve(uri.Host())) { - Services::Logging::Debug(_logger, "Accepting TCP connections on {}:{}", host, uri.Port()); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Accepting TCP connections on host") + .AddKeyValue(Log::Keys::uriHost, host) + .AddKeyValue(Log::Keys::uriPort, uri.Port()) + .Dispatch(); try { @@ -349,8 +357,12 @@ void VAsioConnection::OpenTcpAcceptors(const std::vector& acceptorE } catch (const std::exception& exception) { - Services::Logging::Error(_logger, "Unable to accept TCP connections on {}:{}: {}", host, uri.Port(), - exception.what()); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("Unable to accept TCP connections on") + .AddKeyValue(Log::Keys::uriHost, host) + .AddKeyValue(Log::Keys::uriPort, uri.Port()) + .AddKeyValue(Log::Keys::exception, exception.what()) + .Dispatch(); } metric->Add(fmt::format("{}:{}", host, uri.Port())); @@ -362,7 +374,10 @@ void VAsioConnection::OpenTcpAcceptors(const std::vector& acceptorE } else { - SilKit::Services::Logging::Warn(_logger, "OpenTcpAcceptors: Unused acceptor endpoint URI: {}", uriString); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("OpenTcpAcceptors: Unused acceptor endpoint URI") + .AddKeyValue(Log::Keys::uriHost, uriString) + .Dispatch(); } } } @@ -378,8 +393,11 @@ void VAsioConnection::OpenLocalAcceptors(const std::vector& accepto if (uri.Type() == Uri::UriType::Local && uri.Scheme() == "local") { - SilKit::Services::Logging::Debug(_logger, "Found local domain acceptor endpoint URI {} with path {}", - uriString, uri.Path()); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Found local domain acceptor endpoint URI") + .AddKeyValue(Log::Keys::uriHost, uriString) + .AddKeyValue(Log::Keys::uriPath, uri.Path()) + .Dispatch(); // file must not exist before we bind/listen on it (void)fs::remove(uri.Path()); @@ -397,8 +415,11 @@ void VAsioConnection::OpenLocalAcceptors(const std::vector& accepto } catch (const std::exception& exception) { - Services::Logging::Error(_logger, "Unable to accept local domain connections on '{}': {}", uri.Path(), - exception.what()); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("Unable to accept local domain connections on") + .AddKeyValue(Log::Keys::uriPath, uri.Path()) + .AddKeyValue(Log::Keys::exception, exception.what()) + .Dispatch(); } metric->Add(fmt::format("{}", uri.Path())); @@ -409,7 +430,10 @@ void VAsioConnection::OpenLocalAcceptors(const std::vector& accepto } else { - SilKit::Services::Logging::Warn(_logger, "OpenLocalAcceptors: Unused acceptor endpoint URI: {}", uriString); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("OpenLocalAcceptors: Unused acceptor endpoint URI") + .AddKeyValue(Log::Keys::uriString, uriString) + .Dispatch(); } } } @@ -436,7 +460,9 @@ void VAsioConnection::JoinSimulation(std::string connectUri) // Wait for a fixed amount of time for all handshakes to complete. WaitForAllReplies(GetParticipantHandshakeTimeout(_config)); - _logger->Debug("Connected to all known participants"); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Connected to all known participants") + .Dispatch(); } void VAsioConnection::OpenParticipantAcceptors(const std::string& connectUri) @@ -453,14 +479,18 @@ void VAsioConnection::OpenParticipantAcceptors(const std::string& connectUri) if (_acceptors.empty()) { - SilKit::Services::Logging::Error(_logger, "JoinSimulation: no acceptors available"); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("JoinSimulation: no acceptors available") + .Dispatch(); throw SilKitError{"JoinSimulation: no acceptors available"}; } } void VAsioConnection::ConnectParticipantToRegistryAndStartIoWorker(const std::string& connectUriString) { - _logger->Debug("Connecting to SIL Kit Registry"); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Connecting to SIL Kit Registry") + .Dispatch(); VAsioPeerInfo registryPeerInfo; registryPeerInfo.participantName = REGISTRY_PARTICIPANT_NAME; @@ -502,10 +532,28 @@ void VAsioConnection::ConnectParticipantToRegistryAndStartIoWorker(const std::st auto registryStream{registryStreamFuture.get()}; if (registryStream == nullptr) { - Services::Logging::Error(_logger, "Failed to connect to SIL Kit Registry (number of attempts: {})", - _config.middleware.connectAttempts); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("Failed to connect to SIL Kit Registry") + .AddKeyValue(Log::Keys::connectAttempts, _config.middleware.connectAttempts) + .Dispatch(); - Services::Logging::Info( + + auto lm = _logger->MakeMessage(Log::Level::Info, *this) + .SetMessage(" Make sure that the SIL Kit Registry is up and running and is listening on the following URIs: {}.",printUris(registryPeerInfo.acceptorUris)) + .Dispatch(); + lm.SetMessage(" If a registry is unable to open a listening socket it will only be reachable" + " via local domain sockets, which depend on the working directory" + " and the middleware configuration ('enableDomainSockets').") + .Dispatch(); + + lm.SetMessage(" Make sure that the hostname can be resolved and is reachable.") + .Dispatch(); + lm.SetMessage(" The SIL Kit Registry executable can be found in your SIL Kit installation folder:") + .Dispatch(); + lm.SetMessage(" INSTALL_DIR/bin/sil-kit-registry[.exe]").Dispatch(); + + + /* Services::Logging::Info( _logger, " Make sure that the SIL Kit Registry is up and running and is listening on the following URIs: {}.", printUris(registryPeerInfo.acceptorUris)); @@ -516,15 +564,19 @@ void VAsioConnection::ConnectParticipantToRegistryAndStartIoWorker(const std::st _logger->Info(" You can configure the SIL Kit Registry hostname and port via the SilKitConfig."); _logger->Info(" The SIL Kit Registry executable can be found in your SIL Kit installation folder:"); _logger->Info(" INSTALL_DIR/bin/sil-kit-registry[.exe]"); +*/ throw SilKitError{"ERROR: Failed to connect to SIL Kit Registry"}; } _registry = MakeVAsioPeer(std::move(registryStream)); _registry->SetInfo(registryPeerInfo); - SilKit::Services::Logging::Info(_logger, "Connected to registry at '{}' via '{}' ({})", - _registry->GetRemoteAddress(), _registry->GetLocalAddress(), - printUris(_registry->GetInfo().acceptorUris)); + _logger->MakeMessage(Log::Level::Info, *this) + .SetMessage("Connected to registry at '{}' via '{}' ({})", + _registry->GetRemoteAddress(), _registry->GetLocalAddress(), + printUris(_registry->GetInfo().acceptorUris)) + .Dispatch(); + _registry->StartAsyncRead(); @@ -533,7 +585,10 @@ void VAsioConnection::ConnectParticipantToRegistryAndStartIoWorker(const std::st void VAsioConnection::WaitForRegistryHandshakeToComplete(std::chrono::milliseconds timeout) { - SilKit::Services::Logging::Debug(_logger, "Waiting {}ms for the registry to reply", timeout.count()); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Waiting {}ms for the registry to reply", timeout.count()) + .AddKeyValue(Log::Keys::waitingTime, timeout.count()) + .Dispatch(); auto future{_registryHandshakeComplete.get_future()}; auto futureStatus{future.wait_for(timeout)}; @@ -545,7 +600,9 @@ void VAsioConnection::WaitForRegistryHandshakeToComplete(std::chrono::millisecon "with the same name ('{}') has already connected to the registry.", _participantName)}; - _logger->Error(errorMessage); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage(errorMessage) + .Dispatch(); throw SilKit::ProtocolError{errorMessage}; } @@ -557,7 +614,9 @@ void VAsioConnection::WaitForRegistryHandshakeToComplete(std::chrono::millisecon void VAsioConnection::ConnectToKnownParticipants() { - _logger->Debug("Connecting to known participants"); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Connecting to known participants") + .Dispatch(); _connectKnownParticipants.StartConnecting(); @@ -569,7 +628,10 @@ void VAsioConnection::ConnectToKnownParticipants() void VAsioConnection::WaitForAllReplies(std::chrono::milliseconds timeout) { - SilKit::Services::Logging::Debug(_logger, "Waiting {}ms for all known participants to reply", timeout.count()); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Waiting {}ms for all known participants to reply", timeout.count()) + .AddKeyValue(Log::Keys::waitingTime, timeout.count()) + .Dispatch(); auto future{_allKnownParticipantHandshakesComplete.get_future()}; auto futureStatus{future.wait_for(timeout)}; @@ -579,7 +641,10 @@ void VAsioConnection::WaitForAllReplies(std::chrono::milliseconds timeout) std::string errorMessage{fmt::format("Timeout while waiting for replies from known participants: {}", _connectKnownParticipants.Describe())}; - _logger->Error(errorMessage); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage(errorMessage) + .Dispatch(); + throw SilKit::ProtocolError{errorMessage}; } @@ -593,12 +658,15 @@ void VAsioConnection::WaitForAllReplies(std::chrono::milliseconds timeout) void VAsioConnection::LogAndPrintNetworkIncompatibility(const RegistryMsgHeader& other, const std::string& otherParticipantName) { - const auto errorMsg = fmt::format("Network incompatibility between this version range ({})" + const auto errorMessage = fmt::format("Network incompatibility between this version range ({})" " and connecting participant '{}' ({})", MapVersionToRelease(MakeRegistryMsgHeader(_version)), otherParticipantName, MapVersionToRelease(other)); - _logger->Critical(errorMsg); - std::cerr << "ERROR: " << errorMsg << std::endl; + _logger->MakeMessage(Log::Level::Critical, *this) + .SetMessage(errorMessage) + .Dispatch(); + + std::cerr << "ERROR: " << errorMessage << std::endl; } void VAsioConnection::SendParticipantAnnouncement(IVAsioPeer* peer) @@ -607,16 +675,18 @@ void VAsioConnection::SendParticipantAnnouncement(IVAsioPeer* peer) for (const auto& uri : myPeerInfo.acceptorUris) { - Services::Logging::Trace(_logger, "SendParticipantAnnouncement: Peer '{}' ('{}'): Acceptor Uri: {}", - peer->GetInfo().participantName, peer->GetSimulationName(), uri); + _logger->MakeMessage(Log::Level::Trace, *this) + .SetMessage("SendParticipantAnnouncement: Peer '{}' ('{}'): Acceptor Uri: {}", + peer->GetInfo().participantName, peer->GetSimulationName(), uri) + .Dispatch(); } if (myPeerInfo.acceptorUris.empty()) { - const auto message = "SendParticipantAnnouncement: Cannot send announcement: All acceptors " + const auto errorMessage = "SendParticipantAnnouncement: Cannot send announcement: All acceptors " "(both Local-Domain and TCP) are missing"; - SilKit::Services::Logging::Error(_logger, message); - throw SilKitError{message}; + std::cerr << "ERROR: " << errorMessage << std::endl; + throw SilKitError{errorMessage}; } ParticipantAnnouncement announcement; @@ -625,8 +695,11 @@ void VAsioConnection::SendParticipantAnnouncement(IVAsioPeer* peer) announcement.peerInfo = std::move(myPeerInfo); announcement.simulationName = _simulationName; - Services::Logging::Debug(_logger, "Sending participant announcement to '{}' ('{}')", - peer->GetInfo().participantName, peer->GetSimulationName()); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Sending participant announcement to '{}' ('{}')", peer->GetInfo().participantName, + peer->GetSimulationName()) + .Dispatch(); + peer->SendSilKitMsg(SerializedMessage{announcement}); } @@ -660,10 +733,11 @@ void VAsioConnection::ReceiveParticipantAnnouncement(IVAsioPeer* from, Serialize buffer.SetProtocolVersion(from->GetProtocolVersion()); auto announcement = buffer.Deserialize(); - Services::Logging::Debug(_logger, - "Received participant announcement from {}, protocol version {}.{}, simulation name '{}'", - announcement.peerInfo.participantName, announcement.messageHeader.versionHigh, - announcement.messageHeader.versionLow, announcement.simulationName); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Received participant announcement from {}, protocol version {}.{}, simulation name '{}'", + announcement.peerInfo.participantName, announcement.messageHeader.versionHigh, + announcement.messageHeader.versionLow, announcement.simulationName) + .Dispatch(); if (!_allowAnySimulationName && announcement.simulationName != _simulationName) { @@ -723,16 +797,20 @@ void VAsioConnection::SendParticipantAnnouncementReply(IVAsioPeer* peer) std::transform(_vasioReceivers.begin(), _vasioReceivers.end(), std::back_inserter(reply.subscribers), [](const auto& subscriber) { return subscriber->GetDescriptor(); }); - Services::Logging::Debug(_logger, "Sending ParticipantAnnouncementReply to '{}' ('{}') with protocol version {}", - peer->GetInfo().participantName, peer->GetSimulationName(), - ExtractProtocolVersion(reply.remoteHeader)); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Sending ParticipantAnnouncementReply to '{}' ('{}') with protocol version {}", + peer->GetInfo().participantName, peer->GetSimulationName(), + ExtractProtocolVersion(reply.remoteHeader)) + .Dispatch(); peer->SendSilKitMsg(SerializedMessage{peer->GetProtocolVersion(), reply}); if (const auto proxyPeer = dynamic_cast(peer); proxyPeer != nullptr) { - Log::Warn(_logger, "Connected to {:?} ({:?}) using {:?} as a proxy", proxyPeer->GetInfo().participantName, - proxyPeer->GetSimulationName(), proxyPeer->GetPeer()->GetInfo().participantName); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Connected to {:?} ({:?}) using {:?} as a proxy", proxyPeer->GetInfo().participantName, + proxyPeer->GetSimulationName(), proxyPeer->GetPeer()->GetInfo().participantName) + .Dispatch(); } } @@ -746,9 +824,11 @@ void VAsioConnection::SendFailedParticipantAnnouncementReply(IVAsioPeer* peer, P reply.status = ParticipantAnnouncementReply::Status::Failed; reply.diagnostic = std::move(diagnostic); - Services::Logging::Debug( - _logger, "Sending failed ParticipantAnnouncementReply to '{}' ('{}') with protocol version {}", - peer->GetInfo().participantName, peer->GetSimulationName(), ExtractProtocolVersion(reply.remoteHeader)); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Sending failed ParticipantAnnouncementReply to '{}' ('{}') with protocol version {}", + peer->GetInfo().participantName, peer->GetSimulationName(), + ExtractProtocolVersion(reply.remoteHeader)) + .Dispatch(); peer->SendSilKitMsg(SerializedMessage{peer->GetProtocolVersion(), reply}); } @@ -771,7 +851,9 @@ void VAsioConnection::ReceiveParticipantAnnouncementReply(IVAsioPeer* from, Seri // provide a non-empty default string for the diagnostic message reply.diagnostic.empty() ? "(no diagnostic message was delivered)" : reply.diagnostic.c_str()); - _logger->Warn(message); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage(message) + .Dispatch(); // tear down the participant if we are talking to the registry if (from->GetInfo().participantId == REGISTRY_PARTICIPANT_ID) @@ -795,8 +877,10 @@ void VAsioConnection::ReceiveParticipantAnnouncementReply(IVAsioPeer* from, Seri TryAddRemoteSubscriber(from, subscriber); } - Services::Logging::Debug(_logger, "Received participant announcement reply from '{}' ('{}') protocol version {}", - from->GetInfo().participantName, from->GetSimulationName(), remoteVersion); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Received participant announcement reply from '{}' ('{}') protocol version {}", + from->GetInfo().participantName, from->GetSimulationName(), remoteVersion) + .Dispatch(); if (from->GetInfo().participantId == REGISTRY_PARTICIPANT_ID) { @@ -810,8 +894,10 @@ void VAsioConnection::ReceiveParticipantAnnouncementReply(IVAsioPeer* from, Seri if (const auto proxyPeer = dynamic_cast(from); proxyPeer != nullptr) { - Log::Warn(_logger, "Connected to {:?} ({:?}) using {:?} as a proxy", proxyPeer->GetInfo().participantName, - proxyPeer->GetSimulationName(), proxyPeer->GetPeer()->GetInfo().participantName); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Connected to {:?} ({:?}) using {:?} as a proxy", proxyPeer->GetInfo().participantName, + proxyPeer->GetSimulationName(), proxyPeer->GetPeer()->GetInfo().participantName) + .Dispatch(); } } @@ -821,9 +907,10 @@ void VAsioConnection::ReceiveKnownParticpants(IVAsioPeer* peer, SerializedMessag auto msg = buffer.Deserialize(); - Services::Logging::Debug(_logger, "Received known participants list from '{}' ('{}') protocol {}.{}", - peer->GetInfo().participantName, peer->GetSimulationName(), msg.messageHeader.versionHigh, - msg.messageHeader.versionLow); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Received known participants list from '{}' ('{}') protocol {}.{}", peer->GetInfo().participantName, + peer->GetSimulationName(), msg.messageHeader.versionHigh, msg.messageHeader.versionLow) + .Dispatch(); // After receiving a ParticipantAnnouncement the Registry will send a KnownParticipants message // check if we support its version here diff --git a/SilKit/source/services/logging/MessageTracing.hpp b/SilKit/source/services/logging/MessageTracing.hpp index 89bcb0551..3ca38f11c 100644 --- a/SilKit/source/services/logging/MessageTracing.hpp +++ b/SilKit/source/services/logging/MessageTracing.hpp @@ -35,11 +35,11 @@ void TraceMessageCommon(Logging::ILoggerInternal* logger, const char* messageStr { if (logger->GetLogLevel() == Logging::Level::Trace) { - Logging::LoggerMessage lm{logger, Logging::Level::Trace}; - lm.SetMessage(messageString); - lm.SetKeyValue(addr->GetServiceDescriptor()); - lm.FormatKeyValue(Logging::Keys::msg, "{}", msg); - + auto lm = logger->MakeMessage(Logging::Level::Trace, Logging::Topic::MessageTracing) + .SetMessage(messageString) + .AddKeyValue(addr->GetServiceDescriptor()) + .AddKeyValue(Logging::Keys::msg, msg); + if (!keyString.empty() && !valueString.empty()) { lm.SetKeyValue(keyString, valueString); @@ -47,7 +47,7 @@ void TraceMessageCommon(Logging::ILoggerInternal* logger, const char* messageStr if constexpr (Core::HasTimestamp::value) { - lm.FormatKeyValue(Logging::Keys::virtualTimeNS, "{}", msg.timestamp.count()); + lm.AddKeyValue(Logging::Keys::virtualTimeNS, "{}", msg.timestamp.count()); } // Turn the Raw-logging into a trait when we have enough types that implement it @@ -55,7 +55,6 @@ void TraceMessageCommon(Logging::ILoggerInternal* logger, const char* messageStr { lm.SetKeyValue(Logging::Keys::raw, SilKit::Config::SerializeAsJson(msg)); } - lm.SetTopic(Logging::Topic::MessageTracing); lm.Dispatch(); } } diff --git a/SilKit/source/services/logging/StructuredLoggingKeys.hpp b/SilKit/source/services/logging/StructuredLoggingKeys.hpp index 87592b066..f8402c46f 100644 --- a/SilKit/source/services/logging/StructuredLoggingKeys.hpp +++ b/SilKit/source/services/logging/StructuredLoggingKeys.hpp @@ -49,6 +49,12 @@ constexpr std::string_view mediaType{"MediaType"}; constexpr std::string_view network{"Network"}; constexpr std::string_view label{"Label"}; +constexpr std::string_view uriString{"UriString"}; +constexpr std::string_view uriHost{"UriHost"}; +constexpr std::string_view uriPort{"UriPort"}; +constexpr std::string_view uriPath{"UriPath"}; +constexpr std::string_view exception{"Exception"}; +constexpr std::string_view connectAttempts{"ConnectAttempts"}; } // namespace Keys } // namespace Logging diff --git a/SilKit/source/services/logging/Test_Logger.cpp b/SilKit/source/services/logging/Test_Logger.cpp index 48e891de9..9820d2e21 100644 --- a/SilKit/source/services/logging/Test_Logger.cpp +++ b/SilKit/source/services/logging/Test_Logger.cpp @@ -187,15 +187,13 @@ TEST(Test_Logger, send_loggermessage_from_logger) SendMsg_LogMsg(&logMsgSender, ALogMsgWith(loggerName, Level::Critical, payload, keyValue))) .Times(1); - LoggerMessage lm{&logger, Level::Debug}; - lm.SetMessage(payload); - lm.SetKeyValue(key, value); - lm.Dispatch(); - - LoggerMessage lm2{&logger, Level::Critical}; - lm2.SetMessage(payload); - lm2.SetKeyValue(key, value); - lm2.Dispatch(); + auto lm = logger.MakeMessage(Level::Debug, Topic::None) + .SetMessage(payload) + .AddKeyValue(key, value) + .Dispatch(); + + lm.SetLevel(Level::Critical) + .Dispatch(); } } // anonymous namespace diff --git a/SilKit/source/services/orchestration/TimeSyncService.cpp b/SilKit/source/services/orchestration/TimeSyncService.cpp index c4ee4a355..4fd4ce632 100644 --- a/SilKit/source/services/orchestration/TimeSyncService.cpp +++ b/SilKit/source/services/orchestration/TimeSyncService.cpp @@ -582,13 +582,6 @@ void TimeSyncService::CompleteSimulationStep() lm.SetLevel(Logging::Level::Warn) .SetMessage("CompleteSimulationStep() was called before the simulation step handler was invoked.") .Dispatch(); - - - /* Logging::LoggerMessage lm{_logger, Logging::Level::Debug}; - lm.SetMessage("CompleteSimulationStep: calling _timeSyncPolicy->RequestNextStep"); - lm.Dispatch(); - _logger->Warn("CompleteSimulationStep() was called before the simulation step handler was invoked."); - */ } else { From 29f3bf6651d789dd86698f91c7f9c1d01a086b31 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Mon, 13 Apr 2026 12:52:51 +0200 Subject: [PATCH 07/23] fixup! Roll out the new internal logger interface --- SilKit/source/core/vasio/VAsioConnection.cpp | 345 +++++++++++------- .../logging/StructuredLoggingKeys.hpp | 9 + 2 files changed, 224 insertions(+), 130 deletions(-) diff --git a/SilKit/source/core/vasio/VAsioConnection.cpp b/SilKit/source/core/vasio/VAsioConnection.cpp index e4ba74046..a0624837d 100644 --- a/SilKit/source/core/vasio/VAsioConnection.cpp +++ b/SilKit/source/core/vasio/VAsioConnection.cpp @@ -552,19 +552,6 @@ void VAsioConnection::ConnectParticipantToRegistryAndStartIoWorker(const std::st .Dispatch(); lm.SetMessage(" INSTALL_DIR/bin/sil-kit-registry[.exe]").Dispatch(); - - /* Services::Logging::Info( - _logger, - " Make sure that the SIL Kit Registry is up and running and is listening on the following URIs: {}.", - printUris(registryPeerInfo.acceptorUris)); - _logger->Info(" If a registry is unable to open a listening socket it will only be reachable" - " via local domain sockets, which depend on the working directory" - " and the middleware configuration ('enableDomainSockets')."); - _logger->Info(" Make sure that the hostname can be resolved and is reachable."); - _logger->Info(" You can configure the SIL Kit Registry hostname and port via the SilKitConfig."); - _logger->Info(" The SIL Kit Registry executable can be found in your SIL Kit installation folder:"); - _logger->Info(" INSTALL_DIR/bin/sil-kit-registry[.exe]"); -*/ throw SilKitError{"ERROR: Failed to connect to SIL Kit Registry"}; } @@ -798,9 +785,9 @@ void VAsioConnection::SendParticipantAnnouncementReply(IVAsioPeer* peer) [](const auto& subscriber) { return subscriber->GetDescriptor(); }); _logger->MakeMessage(Log::Level::Debug, *this) - .SetMessage("Sending ParticipantAnnouncementReply to '{}' ('{}') with protocol version {}", - peer->GetInfo().participantName, peer->GetSimulationName(), - ExtractProtocolVersion(reply.remoteHeader)) + .SetMessage("Sending ParticipantAnnouncementReply to '{}' ('{}')", + peer->GetInfo().participantName, peer->GetSimulationName()) + .AddKeyValue(Log::Keys::protocolVersion, ExtractProtocolVersion(reply.remoteHeader)) .Dispatch(); peer->SendSilKitMsg(SerializedMessage{peer->GetProtocolVersion(), reply}); @@ -825,9 +812,9 @@ void VAsioConnection::SendFailedParticipantAnnouncementReply(IVAsioPeer* peer, P reply.diagnostic = std::move(diagnostic); _logger->MakeMessage(Log::Level::Debug, *this) - .SetMessage("Sending failed ParticipantAnnouncementReply to '{}' ('{}') with protocol version {}", - peer->GetInfo().participantName, peer->GetSimulationName(), - ExtractProtocolVersion(reply.remoteHeader)) + .SetMessage("Sending failed ParticipantAnnouncementReply to '{}' ('{}')", + peer->GetInfo().participantName, peer->GetSimulationName()) + .AddKeyValue(Log::Keys::protocolVersion, ExtractProtocolVersion(reply.remoteHeader)) .Dispatch(); peer->SendSilKitMsg(SerializedMessage{peer->GetProtocolVersion(), reply}); @@ -844,15 +831,14 @@ void VAsioConnection::ReceiveParticipantAnnouncementReply(IVAsioPeer* from, Seri { const auto message = fmt::format( "SIL Kit Connection Handshake: Received failed ParticipantAnnouncementReply from '{}' ('{}') with " - "protocol version {} and diagnostic message: {}", + "diagnostic message: {}", from->GetInfo().participantName, from->GetSimulationName(), - // extract the version delivered in the reply ( - ExtractProtocolVersion(reply.remoteHeader), // provide a non-empty default string for the diagnostic message reply.diagnostic.empty() ? "(no diagnostic message was delivered)" : reply.diagnostic.c_str()); _logger->MakeMessage(Log::Level::Warn, *this) .SetMessage(message) + .AddKeyValue(Log::Keys::protocolVersion, ExtractProtocolVersion(reply.remoteHeader)) // extract the version delivered in the reply .Dispatch(); // tear down the participant if we are talking to the registry @@ -878,8 +864,9 @@ void VAsioConnection::ReceiveParticipantAnnouncementReply(IVAsioPeer* from, Seri } _logger->MakeMessage(Log::Level::Debug, *this) - .SetMessage("Received participant announcement reply from '{}' ('{}') protocol version {}", - from->GetInfo().participantName, from->GetSimulationName(), remoteVersion) + .SetMessage("Received participant announcement reply from '{}' ('{}')", + from->GetInfo().participantName, from->GetSimulationName()) + .AddKeyValue(Log::Keys::protocolVersion, remoteVersion) .Dispatch(); if (from->GetInfo().participantId == REGISTRY_PARTICIPANT_ID) @@ -908,8 +895,9 @@ void VAsioConnection::ReceiveKnownParticpants(IVAsioPeer* peer, SerializedMessag auto msg = buffer.Deserialize(); _logger->MakeMessage(Log::Level::Debug, *this) - .SetMessage("Received known participants list from '{}' ('{}') protocol {}.{}", peer->GetInfo().participantName, - peer->GetSimulationName(), msg.messageHeader.versionHigh, msg.messageHeader.versionLow) + .SetMessage("Received known participants list from '{}' ('{}')", peer->GetInfo().participantName, + peer->GetSimulationName()) + .AddKeyValue(Log::Keys::protocolVersion, "{}.{}", msg.messageHeader.versionHigh, msg.messageHeader.versionLow) .Dispatch(); // After receiving a ParticipantAnnouncement the Registry will send a KnownParticipants message @@ -950,16 +938,20 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest(IVAsioPeer* peer, S } else { - Log::Warn(_logger, - "Received RemoteParticipantConnectRequest from peer '{}' ('{}' at '{}') with unsupported protocol " - "version {}.{}", - peer->GetInfo().participantName, peer->GetSimulationName(), peer->GetRemoteAddress(), - registryMsgHeader.versionHigh, registryMsgHeader.versionLow); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Received RemoteParticipantConnectRequest from peer '{}' ('{}' at '{}') with unsupported protocol " + "version", + peer->GetInfo().participantName, peer->GetSimulationName(), peer->GetRemoteAddress()) + .AddKeyValue(Log::Keys::protocolVersion, "{}.{}", registryMsgHeader.versionHigh, + registryMsgHeader.versionLow) + .Dispatch(); // ignore the request if it is sent via the registry (we cannot deserialize it anyway) if (peer->GetInfo().participantId == REGISTRY_PARTICIPANT_ID) { - Log::Debug(_logger, "Dropping invalid RemoteParticipantConnectRequest from registry"); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Dropping invalid RemoteParticipantConnectRequest from registry") + .Dispatch(); return; } @@ -973,10 +965,12 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest(IVAsioPeer* peer, S if (!_capabilities.HasRequestParticipantConnectionCapability()) { - SilKit::Services::Logging::Warn(_logger, - "Ignoring RemoteParticipantConnectRequest because feature is disabled via " - "configuration: origin {}, target {}", - msg.requestOrigin.participantName, msg.requestTarget.participantName); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Ignoring RemoteParticipantConnectRequest because feature is disabled via " + "configuration") + .AddKeyValue(Log::Keys::requestOrigin, msg.requestOrigin.participantName) + .AddKeyValue(Log::Keys::requestTarget, msg.requestTarget.participantName) + .Dispatch(); return; } @@ -1000,9 +994,11 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Registry(IVAsioPeer if (msg.status == RemoteParticipantConnectRequest::ANNOUNCEMENT) { - SilKit::Services::Logging::Error(_logger, - "Ignoring RemoteParticipantConnectRequest announcement (origin={}, target={})", - msg.requestOrigin.participantName, msg.requestTarget.participantName); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("Ignoring RemoteParticipantConnectRequest announcement") + .AddKeyValue(Log::Keys::requestOrigin, msg.requestOrigin.participantName) + .AddKeyValue(Log::Keys::requestTarget, msg.requestTarget.participantName) + .Dispatch(); return; } @@ -1033,9 +1029,12 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Registry(IVAsioPeer if (destination == nullptr) { - SilKit::Services::Logging::Error( - _logger, "Ignoring invalid RemoteParticipantConnectRequest (origin={}, target={}, status={})", - msg.requestOrigin.participantName, msg.requestTarget.participantName, static_cast(msg.status)); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("Ignoring invalid RemoteParticipantConnectRequest") + .AddKeyValue(Log::Keys::requestOrigin, msg.requestOrigin.participantName) + .AddKeyValue(Log::Keys::requestTarget, msg.requestTarget.participantName) + .AddKeyValue(Log::Keys::status, static_cast(msg.status)) + .Dispatch(); return; } @@ -1056,9 +1055,11 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Participant(IVAsioP { if (msg.status == RemoteParticipantConnectRequest::REQUEST) { - SilKit::Services::Logging::Debug( - _logger, "Received RemoteParticipantConnectRequest::REQUEST (request origin {}, request target {})", - msg.requestOrigin.participantName, msg.requestTarget.participantName); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Received RemoteParticipantConnectRequest::REQUEST") + .AddKeyValue(Log::Keys::requestOrigin, msg.requestOrigin.participantName) + .AddKeyValue(Log::Keys::requestTarget, msg.requestTarget.participantName) + .Dispatch(); // XXX check if already connected to origin @@ -1079,10 +1080,11 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Participant(IVAsioP { if (msg.status == RemoteParticipantConnectRequest::ANNOUNCEMENT) { - SilKit::Services::Logging::Debug( - _logger, - "Received RemoteParticipantConnectRequest::ANNOUNCEMENT (request origin {}, request target {})", - msg.requestOrigin.participantName, msg.requestTarget.participantName); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Received RemoteParticipantConnectRequest::ANNOUNCEMENT") + .AddKeyValue(Log::Keys::requestOrigin, msg.requestOrigin.participantName) + .AddKeyValue(Log::Keys::requestTarget, msg.requestTarget.participantName) + .Dispatch(); // The remote participant informs us that this is a remote-connection and we should start the // participant-participant handshake (i.e., send the ParticipantAnnouncement). @@ -1098,9 +1100,11 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Participant(IVAsioP if (msg.status == RemoteParticipantConnectRequest::CONNECTING) { - SilKit::Services::Logging::Debug( - _logger, "Received RemoteParticipantConnectRequest::CONNECTING (request origin {}, request target {})", - msg.requestOrigin.participantName, msg.requestTarget.participantName); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Received RemoteParticipantConnectRequest::CONNECTING") + .AddKeyValue(Log::Keys::requestOrigin, msg.requestOrigin.participantName) + .AddKeyValue(Log::Keys::requestTarget, msg.requestTarget.participantName) + .Dispatch(); // The remote participant informs us that it received the REQUEST and is starting to connect to us. _connectKnownParticipants.HandlePeerEvent( @@ -1112,10 +1116,11 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Participant(IVAsioP if (msg.status == RemoteParticipantConnectRequest::FAILED_TO_CONNECT) { - SilKit::Services::Logging::Debug( - _logger, - "Received RemoteParticipantConnectRequest::FAILED_TO_CONNECT (request origin {}, request target {})", - msg.requestOrigin.participantName, msg.requestTarget.participantName); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Received RemoteParticipantConnectRequest::FAILED_TO_CONNECT") + .AddKeyValue(Log::Keys::requestOrigin, msg.requestOrigin.participantName) + .AddKeyValue(Log::Keys::requestTarget, msg.requestTarget.participantName) + .Dispatch(); _connectKnownParticipants.HandlePeerEvent( msg.requestTarget.participantName, @@ -1125,9 +1130,12 @@ void VAsioConnection::ReceiveRemoteParticipantConnectRequest_Participant(IVAsioP } } - SilKit::Services::Logging::Error( - _logger, "Ignoring invalid RemoteParticipantConnectRequest (origin={}, target={}, status={})", - msg.requestOrigin.participantName, msg.requestTarget.participantName, static_cast(msg.status)); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("Ignoring invalid RemoteParticipantConnectRequest") + .AddKeyValue(Log::Keys::requestOrigin, msg.requestOrigin.participantName) + .AddKeyValue(Log::Keys::requestTarget, msg.requestTarget.participantName) + .AddKeyValue(Log::Keys::status, static_cast(msg.status)) + .Dispatch(); } @@ -1212,9 +1220,12 @@ void VAsioConnection::StartIoWorker() _ioContext->Run(); return; } - catch (const std::exception& error) + catch (const std::exception& exception) { - Services::Logging::Error(_logger, "SilKit-IOWorker: Something went wrong: {}", error.what()); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("SilKit-IOWorker: Something went wrong") + .AddKeyValue(Log::Keys::exception, exception.what()) + .Dispatch(); } } }}; @@ -1233,7 +1244,9 @@ void VAsioConnection::AcceptLocalConnections(const std::string& uniqueId) acceptor->SetListener(*this); acceptor->AsyncAccept({}); - Services::Logging::Debug(_logger, "SIL Kit is listening on {}", acceptor->GetLocalEndpoint()); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("SIL Kit is listening on {}", acceptor->GetLocalEndpoint()) + .Dispatch(); { std::unique_lock lock{_acceptorsMutex}; @@ -1242,8 +1255,10 @@ void VAsioConnection::AcceptLocalConnections(const std::string& uniqueId) } catch (const std::exception& exception) { - Services::Logging::Error(_logger, "SIL Kit failed to listening on {}: {}", localEndpoint.path(), - exception.what()); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("SIL Kit failed to listening on {}", localEndpoint.path()) + .AddKeyValue(Log::Keys::exception, exception.what()) + .Dispatch(); throw; } } @@ -1260,8 +1275,10 @@ auto VAsioConnection::AcceptTcpConnectionsOn(const std::string& hostName, if (resolverResults.empty()) { - Services::Logging::Error(_logger, "AcceptTcpConnectionsOn: Unable to resolve hostname\"{}:{}\"", hostName, - port); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("AcceptTcpConnectionsOn: Unable to resolve hostname\"{}:{}\"", hostName, + port) + .Dispatch(); throw SilKit::StateError{"Unable to resolve hostname and service."}; } @@ -1273,8 +1290,10 @@ auto VAsioConnection::AcceptTcpConnectionsOn(const std::string& hostName, endpoint = selectBestEndpointFromResolverResults(endpoints); - Services::Logging::Debug(_logger, "Accepting connections at {}:{} @{}", endpoint.address().to_string(), - endpoint.port(), (endpoint.address().is_v4() ? "TCPv4" : "TCPv6")); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Accepting connections at {}:{} @{}", endpoint.address().to_string(), + endpoint.port(), (endpoint.address().is_v4() ? "TCPv4" : "TCPv6")) + .Dispatch(); } try @@ -1285,7 +1304,9 @@ auto VAsioConnection::AcceptTcpConnectionsOn(const std::string& hostName, auto localEndpointUri{Uri::Parse(acceptor->GetLocalEndpoint())}; - Services::Logging::Debug(_logger, "SIL Kit is listening on {}", localEndpointUri.EncodedString()); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("SIL Kit is listening on {}", localEndpointUri.EncodedString()) + .Dispatch(); { std::unique_lock lock{_acceptorsMutex}; @@ -1296,8 +1317,11 @@ auto VAsioConnection::AcceptTcpConnectionsOn(const std::string& hostName, } catch (const std::exception& exception) { - Services::Logging::Error(_logger, "SIL Kit failed to listening on {}:{}: {}", endpoint.address().to_string(), - endpoint.port(), exception.what()); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("SIL Kit failed to listening on {}:{}", endpoint.address().to_string(), + endpoint.port()) + .AddKeyValue(Log::Keys::exception, exception.what()) + .Dispatch(); throw; } } @@ -1455,7 +1479,9 @@ void VAsioConnection::OnSocketData(IVAsioPeer* from, SerializedMessage&& buffer) switch (messageKind) { case VAsioMsgKind::Invalid: - _logger->Warn("Received message with VAsioMsgKind::Invalid"); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Received message with VAsioMsgKind::Invalid") + .Dispatch(); break; case VAsioMsgKind::SubscriptionAnnouncement: return ReceiveSubscriptionAnnouncement(from, std::move(buffer)); @@ -1478,10 +1504,13 @@ void VAsioConnection::ReceiveProxyMessage(IVAsioPeer* from, SerializedMessage&& if (proxyMessageHeader.version != 0) { static SilKit::Services::Logging::LogOnceFlag onceFlag; - SilKit::Services::Logging::Warn( - _logger, onceFlag, - "Ignoring VAsioMsgKind::SilKitProxyMessage because message version is not supported: version {}", - proxyMessageHeader.version); + if (!onceFlag.WasCalled()) + { + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Ignoring VAsioMsgKind::SilKitProxyMessage because message version is not supported: version {}", + proxyMessageHeader.version) + .Dispatch(); + } return; } @@ -1490,19 +1519,25 @@ void VAsioConnection::ReceiveProxyMessage(IVAsioPeer* from, SerializedMessage&& if (!_capabilities.HasProxyMessageCapability()) { static SilKit::Services::Logging::LogOnceFlag onceFlag; - SilKit::Services::Logging::Warn( - _logger, onceFlag, - "Ignoring VAsioMsgKind::SilKitProxyMessage because feature is disabled via configuration: From {}, To {}", - proxyMessage.source, proxyMessage.destination); + if (!onceFlag.WasCalled()) + { + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Ignoring VAsioMsgKind::SilKitProxyMessage because feature is disabled via configuration") + .AddKeyValue(Log::Keys::from, proxyMessage.source) + .AddKeyValue(Log::Keys::to, proxyMessage.destination) + .Dispatch(); + } return; } const auto& fromSimulationName{from->GetSimulationName()}; - SilKit::Services::Logging::Trace(_logger, - "Received message with VAsioMsgKind::SilKitProxyMessage: From {} ({}), To {}", - proxyMessage.source, fromSimulationName, proxyMessage.destination); - + _logger->MakeMessage(Log::Level::Trace, *this) + .SetMessage("Received message with VAsioMsgKind::SilKitProxyMessage") + .AddKeyValue(Log::Keys::from, proxyMessage.source) + .AddKeyValue(Log::Keys::to, proxyMessage.destination) + .AddKeyValue(Log::Keys::fromSimulationName, fromSimulationName) + .Dispatch(); const bool fromIsSource = from->GetInfo().participantName == proxyMessage.source; if (fromIsSource) @@ -1510,8 +1545,12 @@ void VAsioConnection::ReceiveProxyMessage(IVAsioPeer* from, SerializedMessage&& auto peer{FindPeerByName(fromSimulationName, proxyMessage.destination)}; if (peer == nullptr) { - SilKit::Services::Logging::Error(_logger, "Unable to deliver proxy message from {} to {} in simulation {}", - proxyMessage.source, proxyMessage.destination, fromSimulationName); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("Unable to deliver proxy message") + .AddKeyValue(Log::Keys::from, proxyMessage.source) + .AddKeyValue(Log::Keys::to, proxyMessage.destination) + .AddKeyValue(Log::Keys::fromSimulationName, fromSimulationName) + .Dispatch(); return; } @@ -1526,8 +1565,13 @@ void VAsioConnection::ReceiveProxyMessage(IVAsioPeer* from, SerializedMessage&& if (inserted) { - Log::Warn(_logger, "Acting as proxy between {:?} ({:?}) and {:?} ({:?})", proxyMessage.source, - fromSimulationName, proxyMessage.destination, fromSimulationName); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Acting as proxy between {:?} ({:?}) and {:?} ({:?})", proxyMessage.source, + fromSimulationName, proxyMessage.destination, fromSimulationName) + .AddKeyValue(Log::Keys::from, proxyMessage.source) + .AddKeyValue(Log::Keys::to, proxyMessage.destination) + .AddKeyValue(Log::Keys::fromSimulationName, fromSimulationName) + .Dispatch(); } return; @@ -1540,7 +1584,10 @@ void VAsioConnection::ReceiveProxyMessage(IVAsioPeer* from, SerializedMessage&& if (peer == nullptr) { - SilKit::Services::Logging::Debug(_logger, "Creating VAsioProxyPeer ({})", proxyMessage.source); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Creating VAsioProxyPeer ({})", proxyMessage.source) + .AddKeyValue(Log::Keys::from, proxyMessage.source) + .Dispatch(); auto proxyPeer = std::make_unique(this, _participantName, VAsioPeerInfo{}, from, _logger); peer = proxyPeer.get(); @@ -1590,10 +1637,11 @@ void VAsioConnection::ReceiveSubscriptionAnnouncement(IVAsioPeer* from, Serializ auto myMessageVersion = getVersionForSerdes(subscriber.msgTypeName, subscriber.version); if (myMessageVersion == 0) { - Services::Logging::Warn(_logger, - "Received SubscriptionAnnouncement from {} for message type {}" + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Received SubscriptionAnnouncement from {} for message type {}" " for an unknown subscriber version {}", - from->GetInfo().participantName, subscriber.msgTypeName, subscriber.version); + from->GetInfo().participantName, subscriber.msgTypeName, subscriber.version) + .Dispatch(); } else { @@ -1614,8 +1662,10 @@ void VAsioConnection::ReceiveSubscriptionAcknowledge(IVAsioPeer* from, Serialize if (ack.status != SubscriptionAcknowledge::Status::Success) { - Services::Logging::Error(_logger, "Failed to subscribe [{}] {} from {}", ack.subscriber.networkName, - ack.subscriber.msgTypeName, from->GetInfo().participantName); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("Failed to subscribe [{}] {} from {}", ack.subscriber.networkName, + ack.subscriber.msgTypeName, from->GetInfo().participantName) + .Dispatch(); } // We remove the pending subscription in any case as there will not follow a new, successful acknowledge from that peer @@ -1675,14 +1725,18 @@ bool VAsioConnection::TryAddRemoteSubscriber(IVAsioPeer* from, const VAsioMsgSub if (wasAdded) { - Services::Logging::Debug(_logger, "Messages of type '{}' on link '{}' will be sent to participant '{}'", - subscriber.msgTypeName, subscriber.networkName, from->GetInfo().participantName); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Messages of type '{}' on link '{}' will be sent to participant '{}'", + + subscriber.msgTypeName, subscriber.networkName, from->GetInfo().participantName) + .Dispatch(); } else { - Services::Logging::Warn( - _logger, "Participant '{}' could not be registered as receiver for messages of type '{}' on link '{}'", - from->GetInfo().participantName, subscriber.msgTypeName, subscriber.networkName); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Participant '{}' could not be registered as receiver for messages of type '{}' on link '{}'", + from->GetInfo().participantName, subscriber.msgTypeName, subscriber.networkName) + .Dispatch(); } return wasAdded; @@ -1693,7 +1747,9 @@ void VAsioConnection::ReceiveRawSilKitMessage(IVAsioPeer* from, SerializedMessag auto receiverIdx = static_cast(buffer.GetRemoteIndex()); //ExtractEndpointId(buffer); if (receiverIdx >= _vasioReceivers.size()) { - Services::Logging::Warn(_logger, "Ignoring RawSilKitMessage for unknown receiverIdx={}", receiverIdx); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Ignoring RawSilKitMessage for unknown receiverIdx={}", receiverIdx) + .Dispatch(); return; } @@ -1741,8 +1797,10 @@ void VAsioConnection::ReceiveRegistryMessage(IVAsioPeer* from, SerializedMessage if (PreambleIsPresent(from->GetProtocolVersion(), buffer) && header.preamble != REGISTRY_MESSAGE_HEADER_PREAMBLE_VALUE) { - Services::Logging::Warn(_logger, "Ignoring registry message from '{}' with invalid preamble {}", - from->GetInfo().participantName, header.preamble); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Ignoring registry message from '{}' with invalid preamble {}", + from->GetInfo().participantName, header.preamble) + .Dispatch(); return; } @@ -1750,7 +1808,9 @@ void VAsioConnection::ReceiveRegistryMessage(IVAsioPeer* from, SerializedMessage switch (kind) { case RegistryMessageKind::Invalid: - _logger->Warn("Received message with RegistryMessageKind::Invalid"); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Received message with RegistryMessageKind::Invalid") + .Dispatch(); return; case RegistryMessageKind::ParticipantAnnouncement: return ReceiveParticipantAnnouncement(from, std::move(buffer)); @@ -1866,7 +1926,9 @@ bool VAsioConnection::ParticipantHasCapability(const std::string& participantNam const auto peer{FindPeerByName(_simulationName, participantName)}; if (peer == nullptr) { - SilKit::Services::Logging::Warn(_logger, "ParticipantHasCapability: Participant '{}' unknown", participantName); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("ParticipantHasCapability: Participant '{}' unknown", participantName) + .Dispatch(); return false; } @@ -1953,8 +2015,10 @@ void VAsioConnection::OnAsyncAcceptSuccess(IAcceptor& acceptor, std::unique_ptr< { SILKIT_TRACE_METHOD_(_logger, "({})", static_cast(&acceptor)); - Services::Logging::Debug(_logger, "New connection from [local={}, remote={}]", stream->GetLocalEndpoint(), - stream->GetRemoteEndpoint()); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("New connection from [local={}, remote={}]", stream->GetLocalEndpoint(), + stream->GetRemoteEndpoint()) + .Dispatch(); try { @@ -1963,7 +2027,10 @@ void VAsioConnection::OnAsyncAcceptSuccess(IAcceptor& acceptor, std::unique_ptr< } catch (const std::exception& exception) { - Services::Logging::Error(_logger, "SIL Kit cannot create listener socket: {}", exception.what()); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("SIL Kit cannot create listener socket") + .AddKeyValue(Log::Keys::exception, exception.what()) + .Dispatch(); throw; } @@ -1995,7 +2062,9 @@ void VAsioConnection::OnAsyncAcceptFailure(IAcceptor& acceptor) void VAsioConnection::OnConnectKnownParticipantsFailure(ConnectKnownParticipants& connectKnownParticipants) { auto message{fmt::format("Failed to connect to known participants: {}", connectKnownParticipants.Describe())}; - _logger->Error(message); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage(message) + .Dispatch(); try { @@ -2016,7 +2085,9 @@ void VAsioConnection::OnConnectKnownParticipantsFailure(ConnectKnownParticipants void VAsioConnection::OnConnectKnownParticipantsWaitingForAllReplies(ConnectKnownParticipants&) { - Log::Debug(_logger, "Waiting for completion of all handshakes with all known participants"); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Waiting for completion of all handshakes with all known participants") + .Dispatch(); try { @@ -2029,7 +2100,9 @@ void VAsioConnection::OnConnectKnownParticipantsWaitingForAllReplies(ConnectKnow void VAsioConnection::OnConnectKnownParticipantsAllRepliesReceived(ConnectKnownParticipants&) { - Log::Debug(_logger, "All handshakes with all known participants are complete"); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("All handshakes with all known participants are complete") + .Dispatch(); try { @@ -2076,14 +2149,17 @@ bool VAsioConnection::TryRemoteConnectRequest(const VAsioPeerInfo& peerInfo) { SILKIT_TRACE_METHOD_(_logger, "({})", peerInfo.participantName); - SilKit::Services::Logging::Debug(_logger, "Trying to request remote connection from {} via the registry", - peerInfo.participantName); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Trying to request remote connection from {} via the registry", + peerInfo.participantName) + .Dispatch(); if (!_capabilities.HasCapability(Capabilities::RequestParticipantConnection)) { - SilKit::Services::Logging::Warn( - _logger, "Cannot request remote connection from {}, because it is disabled in the configuration", - peerInfo.participantName); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Cannot request remote connection from {}, because it is disabled in the configuration", + peerInfo.participantName) + .Dispatch(); return false; } @@ -2093,21 +2169,27 @@ bool VAsioConnection::TryRemoteConnectRequest(const VAsioPeerInfo& peerInfo) const VAsioCapabilities peerCapabilities{peerInfo.capabilities}; if (!peerCapabilities.HasCapability(Capabilities::RequestParticipantConnection)) { - SilKit::Services::Logging::Warn(_logger, - "Cannot request remote connection from {}, because {} does not support it", - peerInfo.participantName, peerInfo.participantName); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Cannot request remote connection from {}, because {} does not support it", + peerInfo.participantName, peerInfo.participantName) + .Dispatch(); return false; } } - catch (const std::exception& error) + catch (const std::exception& exception) { - SilKit::Services::Logging::Error(_logger, "Failed to parse capabilities string: {}", error.what()); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("Failed to parse capabilities string") + .AddKeyValue(Log::Keys::exception, exception.what()) + .Dispatch(); return false; } catch (...) { - SilKit::Services::Logging::Error(_logger, "Failed to parse capabilities string: unknown error"); + _logger->MakeMessage(Log::Level::Error, *this) + .SetMessage("Failed to parse capabilities string: unknown error") + .Dispatch(); return false; } @@ -2128,8 +2210,10 @@ bool VAsioConnection::TryProxyConnect(const VAsioPeerInfo& peerInfo) { SILKIT_TRACE_METHOD_(_logger, "({})", peerInfo.participantName); - SilKit::Services::Logging::Debug(_logger, "Trying to use the registry as a proxy to communicate with {}", - peerInfo.participantName); + _logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Trying to use the registry as a proxy to communicate with {}", + peerInfo.participantName) + .Dispatch(); // NB: Cannot check the capabilities of the registry, since we do not receive the PeerInfo from the // registry over the network, but build it ourselves in VAsioConnection::JoinSimulation. @@ -2139,10 +2223,10 @@ bool VAsioConnection::TryProxyConnect(const VAsioPeerInfo& peerInfo) if (!_capabilities.HasProxyMessageCapability()) { - SilKit::Services::Logging::Warn( - _logger, - "Cannot use the registry as a proxy to communicate with {}, because it is disabled in the configuration", - peerInfo.participantName); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Cannot use the registry as a proxy to communicate with {}, because it is disabled in the configuration", + peerInfo.participantName) + .Dispatch(); return false; } @@ -2150,10 +2234,11 @@ bool VAsioConnection::TryProxyConnect(const VAsioPeerInfo& peerInfo) const VAsioCapabilities peerCapabilities{peerInfo.capabilities}; if (!peerCapabilities.HasCapability(Capabilities::ProxyMessage)) { - SilKit::Services::Logging::Warn(_logger, - "VAsioConnection: Cannot use the registry as a proxy to communicate with {}, " + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("VAsioConnection: Cannot use the registry as a proxy to communicate with {}, " "because {} does not support it", - peerInfo.participantName, peerInfo.participantName); + peerInfo.participantName, peerInfo.participantName) + .Dispatch(); return false; } diff --git a/SilKit/source/services/logging/StructuredLoggingKeys.hpp b/SilKit/source/services/logging/StructuredLoggingKeys.hpp index f8402c46f..c2c16e72a 100644 --- a/SilKit/source/services/logging/StructuredLoggingKeys.hpp +++ b/SilKit/source/services/logging/StructuredLoggingKeys.hpp @@ -18,6 +18,13 @@ constexpr std::string_view msg{"Msg"}; constexpr std::string_view from{"From"}; constexpr std::string_view to{"To"}; constexpr std::string_view raw{"Raw"}; +constexpr std::string_view fromSimulationName{"FromSimulationName"}; + +constexpr std::string_view protocolVersion{"ProtocolVersion"}; +constexpr std::string_view requestOrigin{"RequestOrigin"}; +constexpr std::string_view requestTarget{"RequestTarget"}; +constexpr std::string_view status{"Status"}; + constexpr std::string_view waitingTime{"WaitingTime"}; constexpr std::string_view executionTime{"ExecutionTime"}; @@ -54,6 +61,8 @@ constexpr std::string_view uriHost{"UriHost"}; constexpr std::string_view uriPort{"UriPort"}; constexpr std::string_view uriPath{"UriPath"}; constexpr std::string_view exception{"Exception"}; +constexpr std::string_view error{"Error"}; + constexpr std::string_view connectAttempts{"ConnectAttempts"}; } // namespace Keys From a0d24d7d08a73500ab0f861df33fd82b0d6fac74 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Mon, 13 Apr 2026 15:58:36 +0200 Subject: [PATCH 08/23] Upgrade logging in asio component --- .../internal/traits/SilKitLoggingTraits.hpp | 2 + SilKit/source/core/vasio/ConnectPeer.cpp | 23 +++++++---- SilKit/source/core/vasio/ConnectPeer.hpp | 4 +- SilKit/source/core/vasio/VAsioConnection.cpp | 2 +- SilKit/source/core/vasio/VAsioConnection.hpp | 15 +++++-- SilKit/source/core/vasio/VAsioPeer.cpp | 40 +++++++++++-------- SilKit/source/core/vasio/VAsioPeer.hpp | 4 +- SilKit/source/core/vasio/VAsioProxyPeer.cpp | 40 +++++++++++++------ SilKit/source/core/vasio/VAsioProxyPeer.hpp | 6 +-- SilKit/source/core/vasio/VAsioRegistry.cpp | 2 +- SilKit/source/core/vasio/VAsioRegistry.hpp | 2 +- SilKit/source/core/vasio/io/IIoContext.hpp | 2 +- .../core/vasio/io/impl/AsioAcceptor.hpp | 7 ++-- .../core/vasio/io/impl/AsioConnector.hpp | 9 +++-- .../io/impl/AsioGenericRawByteStream.cpp | 16 ++++---- .../io/impl/AsioGenericRawByteStream.hpp | 4 +- .../core/vasio/io/impl/AsioIoContext.cpp | 23 ++++++----- .../core/vasio/io/impl/AsioIoContext.hpp | 4 +- .../vasio/io/impl/SetAsioSocketOptions.cpp | 21 ++++++---- .../vasio/io/impl/SetAsioSocketOptions.hpp | 7 ++-- .../core/vasio/io/mock/MockIoContext.hpp | 4 +- 21 files changed, 146 insertions(+), 91 deletions(-) diff --git a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp index b2250ef25..68def0eaf 100644 --- a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp @@ -15,6 +15,7 @@ namespace SilKit { namespace Core { class IParticipantInternal; class VAsioConnection; +class VAsioPeer; template class Participant; @@ -67,6 +68,7 @@ struct TopicTraits> DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeSyncService, SilKit::Services::Logging::Topic::TimeSyncService); DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioConnection, SilKit::Services::Logging::Topic::Asio); +DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioPeer, SilKit::Services::Logging::Topic::Asio); DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::SystemState, SilKit::Services::Logging::Topic::SystemState); DefineSilKitLoggingTrait_Topic(VSilKit::SystemStateTracker, SilKit::Services::Logging::Topic::SystemState); diff --git a/SilKit/source/core/vasio/ConnectPeer.cpp b/SilKit/source/core/vasio/ConnectPeer.cpp index e609b7701..fb23c8747 100644 --- a/SilKit/source/core/vasio/ConnectPeer.cpp +++ b/SilKit/source/core/vasio/ConnectPeer.cpp @@ -29,7 +29,7 @@ namespace Log = SilKit::Services::Logging; namespace VSilKit { -ConnectPeer::ConnectPeer(IIoContext* ioContext, SilKit::Services::Logging::ILogger* logger, +ConnectPeer::ConnectPeer(IIoContext* ioContext, SilKit::Services::Logging::ILoggerInternal* logger, const SilKit::Core::VAsioPeerInfo& peerInfo, bool enableDomainSockets) : _ioContext{ioContext} , _logger{logger} @@ -192,8 +192,9 @@ void ConnectPeer::TryNextUri() const auto& uri{_uris[_uriIndex]}; _uriIndex += 1; - Log::Debug(_logger, "Trying to connect to {} on {}", _peerInfo.participantName, uri.EncodedString()); - + _logger->MakeMessage(SilKit::Services::Logging::Level::Debug, *this) + .SetMessage("Trying to connect to {} on {}", _peerInfo.participantName, uri.EncodedString()) + .Dispatch(); try { switch (uri.Type()) @@ -205,7 +206,9 @@ void ConnectPeer::TryNextUri() case Uri::UriType::Local: if (!_enableDomainSockets) { - Log::Debug(_logger, "Unable to connect via local-domain because it is disabled via configuration"); + _logger->MakeMessage(SilKit::Services::Logging::Level::Debug, *this) + .SetMessage("Unable to connect via local-domain because it is disabled via configuration") + .Dispatch(); } else { @@ -214,7 +217,9 @@ void ConnectPeer::TryNextUri() break; default: - Log::Warn(_logger, "Invalid uri type {}", static_cast>(uri.Type())); + _logger->MakeMessage(SilKit::Services::Logging::Level::Warn, *this) + .SetMessage("Invalid uri type {}", static_cast>(uri.Type())) + .Dispatch(); break; } @@ -227,12 +232,16 @@ void ConnectPeer::TryNextUri() catch (const std::exception& exception) { _connector.reset(); - Log::Warn(_logger, "Failed to start connecting to '{}': {}", uri.EncodedString(), exception.what()); + _logger->MakeMessage(SilKit::Services::Logging::Level::Warn, *this) + .SetMessage("Failed to start connecting to '{}': {}", uri.EncodedString(), exception.what()) + .Dispatch(); } catch (...) { _connector.reset(); - Log::Warn(_logger, "Failed to start connecting to '{}'", uri.EncodedString()); + _logger->MakeMessage(SilKit::Services::Logging::Level::Warn, *this) + .SetMessage("Failed to start connecting to '{}'", uri.EncodedString()) + .Dispatch(); } if (_connector == nullptr) diff --git a/SilKit/source/core/vasio/ConnectPeer.hpp b/SilKit/source/core/vasio/ConnectPeer.hpp index 2e7728f4e..36bed196e 100644 --- a/SilKit/source/core/vasio/ConnectPeer.hpp +++ b/SilKit/source/core/vasio/ConnectPeer.hpp @@ -38,7 +38,7 @@ class ConnectPeer using Uri = SilKit::Core::Uri; IIoContext* _ioContext{nullptr}; - SilKit::Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; SilKit::Core::VAsioPeerInfo _peerInfo; bool _enableDomainSockets{false}; @@ -53,7 +53,7 @@ class ConnectPeer std::unique_ptr _connector; public: - ConnectPeer(IIoContext* ioContext, SilKit::Services::Logging::ILogger* logger, + ConnectPeer(IIoContext* ioContext, SilKit::Services::Logging::ILoggerInternal* logger, const SilKit::Core::VAsioPeerInfo& peerInfo, bool enableDomainSockets); ~ConnectPeer() override; diff --git a/SilKit/source/core/vasio/VAsioConnection.cpp b/SilKit/source/core/vasio/VAsioConnection.cpp index a0624837d..d22429c1b 100644 --- a/SilKit/source/core/vasio/VAsioConnection.cpp +++ b/SilKit/source/core/vasio/VAsioConnection.cpp @@ -838,7 +838,7 @@ void VAsioConnection::ReceiveParticipantAnnouncementReply(IVAsioPeer* from, Seri _logger->MakeMessage(Log::Level::Warn, *this) .SetMessage(message) - .AddKeyValue(Log::Keys::protocolVersion, ExtractProtocolVersion(reply.remoteHeader)) // extract the version delivered in the reply + .AddKeyValue(Log::Keys::protocolVersion, ExtractProtocolVersion(reply.remoteHeader)) // extract the version delivered in the reply .Dispatch(); // tear down the participant if we are talking to the registry diff --git a/SilKit/source/core/vasio/VAsioConnection.hpp b/SilKit/source/core/vasio/VAsioConnection.hpp index 3dda909df..dc1922a92 100644 --- a/SilKit/source/core/vasio/VAsioConnection.hpp +++ b/SilKit/source/core/vasio/VAsioConnection.hpp @@ -120,11 +120,18 @@ class VAsioConnection if (!SilKitServiceTraits::UseAsyncRegistration()) { - Trace(_logger, "SIL Kit waiting for subscription acknowledges for SilKitService {}.", - typeid(*service).name()); + + _logger->MakeMessage(Services::Logging::Level::Trace, *this) + .SetMessage("SIL Kit waiting for subscription acknowledges for SilKitService") + .AddKeyValue(Services::Logging::Keys::serviceName, typeid(*service).name()) + .Dispatch(); + allAcked.wait(); - Trace(_logger, "SIL Kit received all subscription acknowledges for SilKitService {}.", - typeid(*service).name()); + + _logger->MakeMessage(Services::Logging::Level::Trace, *this) + .SetMessage("SIL Kit received all subscription acknowledges for SilKitService") + .AddKeyValue(Services::Logging::Keys::serviceName, typeid(*service).name()) + .Dispatch(); } } diff --git a/SilKit/source/core/vasio/VAsioPeer.cpp b/SilKit/source/core/vasio/VAsioPeer.cpp index a41388386..6da1d6c81 100644 --- a/SilKit/source/core/vasio/VAsioPeer.cpp +++ b/SilKit/source/core/vasio/VAsioPeer.cpp @@ -31,7 +31,7 @@ namespace SilKit { namespace Core { VAsioPeer::VAsioPeer(IVAsioPeerListener* listener, IIoContext* ioContext, std::unique_ptr stream, - Services::Logging::ILogger* logger, std::unique_ptr peerMetrics) + Services::Logging::ILoggerInternal* logger, std::unique_ptr peerMetrics) : _listener{listener} , _ioContext{ioContext} , _socket{std::move(stream)} @@ -152,10 +152,11 @@ void VAsioPeer::Aggregate(const std::vector& blob) // ensure that the aggregation buffer does not exceed a certain size if (_aggregatedMessages.size() > _aggregationBufferThreshold) { - Services::Logging::Debug(_logger, - "VAsioPeer: Automated flush of aggregation buffer has been triggered, since the " - "maximum buffer size of {}Byte has been exceeded.", - _aggregationBufferThreshold); + _logger->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("VAsioPeer: Automated flush of aggregation buffer has been triggered, since the " + "maximum buffer size of {}Byte has been exceeded.", + _aggregationBufferThreshold) + .Dispatch(); Flush(); } } @@ -198,9 +199,10 @@ void VAsioPeer::WriteSomeAsync() void VAsioPeer::Subscribe(VAsioMsgSubscriber subscriber) { - Services::Logging::Debug(_logger, - "VAsioTcpPeer: Subscribing to messages of type '{}' on link '{}' from participant '{}'", - subscriber.msgTypeName, subscriber.networkName, _info.participantName); + _logger->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("VAsioTcpPeer: Subscribing to messages of type '{}' on link '{}' from participant '{}'", + subscriber.msgTypeName, subscriber.networkName, _info.participantName) + .Dispatch(); SendSilKitMsg(SerializedMessage{subscriber}); } @@ -250,7 +252,9 @@ void VAsioPeer::DispatchBuffer() // validate the received size if (_currentMsgSize == 0 || _currentMsgSize > 1024 * 1024 * 1024) { - SilKit::Services::Logging::Error(_logger, "Received invalid Message Size: {}", _currentMsgSize.load()); + _logger->MakeMessage(Services::Logging::Level::Error, *this) + .SetMessage("Received invalid Message Size: {}", _currentMsgSize.load()) + .Dispatch(); Shutdown(); } @@ -334,13 +338,12 @@ void VAsioPeer::OnTimerExpired(ITimer& timer) if (!_aggregatedMessages.empty()) { - Services::Logging::Warn( - _logger, - "VAsioPeer: Automated flush of aggregation buffer has been triggered, since the " - "maximum allowed time step duration of {}milliseconds has been exceeded. Consider switching off the " - "message aggregation via the config option 'EnableMessageAggregation'.", - _flushTimeout.count()); - + _logger->MakeMessage(Services::Logging::Level::Warn, *this) + .SetMessage("VAsioPeer: Automated flush of aggregation buffer has been triggered, since the " + "maximum allowed time step duration of {}milliseconds has been exceeded. Consider switching off the " + "message aggregation via the config option 'EnableMessageAggregation'.", + _flushTimeout.count()) + .Dispatch(); Flush(); } } @@ -348,7 +351,10 @@ void VAsioPeer::OnTimerExpired(ITimer& timer) void VAsioPeer::EnableAggregation() { _useAggregation = true; - SilKit::Services::Logging::Debug(_logger, "VAsioPeer: Enable aggregation for peer {}", _info.participantName); + + _logger->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("VAsioPeer: Enable aggregation for peer {}", _info.participantName) + .Dispatch(); } void VAsioPeer::InitializeMetrics(VSilKit::IMetricsManager* manager) diff --git a/SilKit/source/core/vasio/VAsioPeer.hpp b/SilKit/source/core/vasio/VAsioPeer.hpp index 08687ba44..4c9ec6f31 100644 --- a/SilKit/source/core/vasio/VAsioPeer.hpp +++ b/SilKit/source/core/vasio/VAsioPeer.hpp @@ -48,7 +48,7 @@ class VAsioPeer VAsioPeer& operator=(VAsioPeer&& other) = delete; //implicitly deleted because of mutex VAsioPeer(IVAsioPeerListener* listener, IIoContext* ioContext, std::unique_ptr stream, - Services::Logging::ILogger* logger, std::unique_ptr metrics); + Services::Logging::ILoggerInternal* logger, std::unique_ptr metrics); ~VAsioPeer() override; @@ -111,7 +111,7 @@ class VAsioPeer VAsioPeerInfo _info; std::string _simulationName; - Services::Logging::ILogger* _logger; + Services::Logging::ILoggerInternal* _logger; std::atomic_bool _isShuttingDown{false}; diff --git a/SilKit/source/core/vasio/VAsioProxyPeer.cpp b/SilKit/source/core/vasio/VAsioProxyPeer.cpp index 29d09e3ab..6a2250bc4 100644 --- a/SilKit/source/core/vasio/VAsioProxyPeer.cpp +++ b/SilKit/source/core/vasio/VAsioProxyPeer.cpp @@ -17,15 +17,17 @@ namespace Core { VAsioProxyPeer::VAsioProxyPeer(IVAsioPeerListener* listener, std::string participantName, VAsioPeerInfo peerInfo, - IVAsioPeer* peer, SilKit::Services::Logging::ILogger* logger) + IVAsioPeer* peer, SilKit::Services::Logging::ILoggerInternal* logger) : _listener{listener} , _participantName{std::move(participantName)} , _peer{peer} , _peerInfo{std::move(peerInfo)} , _logger{logger} { - Log::Debug(_logger, "VAsioProxyPeer ({}): Created with proxy {}", _peerInfo.participantName, - _peer->GetInfo().participantName); + _logger->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("VAsioProxyPeer ({}): Created with proxy {}", _peerInfo.participantName, + _peer->GetInfo().participantName) + .Dispatch(); } // ================================================================================ @@ -39,7 +41,9 @@ void VAsioProxyPeer::SendSilKitMsg(SerializedMessage buffer) msg.destination = GetInfo().participantName; msg.payload = buffer.ReleaseStorage(); - Log::Trace(_logger, "VAsioProxyPeer ({}): SendSilKitMsg({})", _peerInfo.participantName, msg.payload.size()); + _logger->MakeMessage(Services::Logging::Level::Trace, *this) + .SetMessage("VAsioProxyPeer ({}): SendSilKitMsg({})", _peerInfo.participantName, msg.payload.size()) + .Dispatch(); // keep track of aggregation kind auto bufferProxy = SerializedMessage{msg}; @@ -50,8 +54,10 @@ void VAsioProxyPeer::SendSilKitMsg(SerializedMessage buffer) void VAsioProxyPeer::Subscribe(VAsioMsgSubscriber subscriber) { - Log::Debug(_logger, "VAsioProxyPeer: Subscribing to messages of type '{}' on link '{}' from participant '{}'", - subscriber.msgTypeName, subscriber.networkName, _peerInfo.participantName); + _logger->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("VAsioProxyPeer: Subscribing to messages of type '{}' on link '{}' from participant '{}'", + subscriber.msgTypeName, subscriber.networkName, _peerInfo.participantName) + .Dispatch(); SendSilKitMsg(SerializedMessage{subscriber}); } @@ -78,29 +84,39 @@ auto VAsioProxyPeer::GetLocalAddress() const -> std::string void VAsioProxyPeer::StartAsyncRead() { - Log::Debug(_logger, "VAsioProxyPeer ({}): StartAsyncRead: Ignored", _peerInfo.participantName); + _logger->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("VAsioProxyPeer ({}): StartAsyncRead: Ignored", _peerInfo.participantName) + .Dispatch(); } void VAsioProxyPeer::Shutdown() { - Log::Debug(_logger, "VAsioProxyPeer ({}): Shutdown: Ignored", _peerInfo.participantName); + _logger->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("VAsioProxyPeer ({}): Shutdown: Ignored", _peerInfo.participantName) + .Dispatch(); } void VAsioProxyPeer::EnableAggregation() { - Log::Debug(_logger, "VAsioProxyPeer ({}): EnableAggregation: Ignored", _peerInfo.participantName); + _logger->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("VAsioProxyPeer ({}): EnableAggregation: Ignored", _peerInfo.participantName) + .Dispatch(); } void VAsioProxyPeer::SetProtocolVersion(ProtocolVersion v) { - Log::Debug(_logger, "VAsioProxyPeer ({}): SetProtocolVersion: {}.{}", _peerInfo.participantName, v.major, v.minor); + _logger->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("VAsioProxyPeer ({}): SetProtocolVersion: {}.{}", _peerInfo.participantName, v.major, v.minor) + .Dispatch(); _protocolVersion = v; } auto VAsioProxyPeer::GetProtocolVersion() const -> ProtocolVersion { - Log::Trace(_logger, "VAsioProxyPeer ({}): GetProtocolVersion: {}.{}", _peerInfo.participantName, - _protocolVersion.major, _protocolVersion.minor); + _logger->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("VAsioProxyPeer ({}): GetProtocolVersion: {}.{}", _peerInfo.participantName, _protocolVersion.major, + _protocolVersion.minor) + .Dispatch(); return _protocolVersion; } diff --git a/SilKit/source/core/vasio/VAsioProxyPeer.hpp b/SilKit/source/core/vasio/VAsioProxyPeer.hpp index 6047722ab..58956aec8 100644 --- a/SilKit/source/core/vasio/VAsioProxyPeer.hpp +++ b/SilKit/source/core/vasio/VAsioProxyPeer.hpp @@ -11,7 +11,7 @@ namespace SilKit { namespace Services { namespace Logging { -class ILogger; +struct ILoggerInternal; } // namespace Logging } // namespace Services } // namespace SilKit @@ -27,7 +27,7 @@ class VAsioProxyPeer { public: VAsioProxyPeer(IVAsioPeerListener* listener, std::string participantName, VAsioPeerInfo peerInfo, IVAsioPeer* peer, - SilKit::Services::Logging::ILogger* logger); + SilKit::Services::Logging::ILoggerInternal* logger); public: // IVAsioPeer void SendSilKitMsg(SerializedMessage buffer) override; @@ -64,7 +64,7 @@ class VAsioProxyPeer IVAsioPeer* _peer; VAsioPeerInfo _peerInfo; ServiceDescriptor _serviceDescriptor; - SilKit::Services::Logging::ILogger* _logger; + SilKit::Services::Logging::ILoggerInternal* _logger; ProtocolVersion _protocolVersion; }; diff --git a/SilKit/source/core/vasio/VAsioRegistry.cpp b/SilKit/source/core/vasio/VAsioRegistry.cpp index c7ec399a5..54d1bffad 100644 --- a/SilKit/source/core/vasio/VAsioRegistry.cpp +++ b/SilKit/source/core/vasio/VAsioRegistry.cpp @@ -173,7 +173,7 @@ void VAsioRegistry::SetAllDisconnectedHandler(std::function handler) { _onAllParticipantsDisconnected = std::move(handler); } -auto VAsioRegistry::GetLogger() -> Services::Logging::ILogger* +auto VAsioRegistry::GetLogger() -> Services::Logging::ILoggerInternal* { return _logger.get(); } diff --git a/SilKit/source/core/vasio/VAsioRegistry.hpp b/SilKit/source/core/vasio/VAsioRegistry.hpp index c2b4333f7..7904f45d9 100644 --- a/SilKit/source/core/vasio/VAsioRegistry.hpp +++ b/SilKit/source/core/vasio/VAsioRegistry.hpp @@ -68,7 +68,7 @@ class VAsioRegistry void SetAllConnectedHandler(std::function handler) override; void SetAllDisconnectedHandler(std::function handler) override; - auto GetLogger() -> Services::Logging::ILogger* override; + auto GetLogger() -> Services::Logging::ILoggerInternal* override; private: // ---------------------------------------- diff --git a/SilKit/source/core/vasio/io/IIoContext.hpp b/SilKit/source/core/vasio/io/IIoContext.hpp index fa7895b9b..164dfd584 100644 --- a/SilKit/source/core/vasio/io/IIoContext.hpp +++ b/SilKit/source/core/vasio/io/IIoContext.hpp @@ -42,7 +42,7 @@ struct IIoContext virtual auto Resolve(const std::string& name) -> std::vector = 0; - virtual void SetLogger(SilKit::Services::Logging::ILogger& logger) = 0; + virtual void SetLogger(SilKit::Services::Logging::ILoggerInternal& logger) = 0; }; diff --git a/SilKit/source/core/vasio/io/impl/AsioAcceptor.hpp b/SilKit/source/core/vasio/io/impl/AsioAcceptor.hpp index 663171f87..a1404f7ff 100644 --- a/SilKit/source/core/vasio/io/impl/AsioAcceptor.hpp +++ b/SilKit/source/core/vasio/io/impl/AsioAcceptor.hpp @@ -18,6 +18,7 @@ #include "util/TracingMacros.hpp" #include "LoggerMessage.hpp" +#include "ILoggerInternal.hpp" #include @@ -63,11 +64,11 @@ class AsioAcceptor final : public IAcceptor AsioEndpointType _localEndpoint; - SilKit::Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; public: AsioAcceptor(const AsioSocketOptions& socketOptions, std::shared_ptr asioIoContext, - AsioAcceptorType acceptor, SilKit::Services::Logging::ILogger& logger); + AsioAcceptorType acceptor, SilKit::Services::Logging::ILoggerInternal& logger); ~AsioAcceptor() override; public: // IAcceptor @@ -84,7 +85,7 @@ class AsioAcceptor final : public IAcceptor template AsioAcceptor::AsioAcceptor(const AsioSocketOptions& socketOptions, std::shared_ptr asioIoContext, - AsioAcceptorType acceptor, SilKit::Services::Logging::ILogger& logger) + AsioAcceptorType acceptor, SilKit::Services::Logging::ILoggerInternal& logger) : _socketOptions{socketOptions} , _asioIoContext{std::move(asioIoContext)} , _acceptor{std::move(acceptor)} diff --git a/SilKit/source/core/vasio/io/impl/AsioConnector.hpp b/SilKit/source/core/vasio/io/impl/AsioConnector.hpp index 3204d9d22..ce1897044 100644 --- a/SilKit/source/core/vasio/io/impl/AsioConnector.hpp +++ b/SilKit/source/core/vasio/io/impl/AsioConnector.hpp @@ -66,7 +66,7 @@ class AsioConnector final : public IConnector asio::steady_timer _timeoutTimer; asio::cancellation_signal _timeoutCancelSignal; - SilKit::Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; public: Op(AsioConnector& connector, const AsioSocketOptions& asioSocketOptions, @@ -86,7 +86,7 @@ class AsioConnector final : public IConnector }; std::shared_ptr _asioIoContext; - SilKit::Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; IConnectorListener* _listener{nullptr}; @@ -94,7 +94,7 @@ class AsioConnector final : public IConnector public: AsioConnector(std::shared_ptr asioIoContext, const AsioSocketOptions& socketOptions, - const AsioEndpointType& remoteEndpoint, SilKit::Services::Logging::ILogger& logger); + const AsioEndpointType& remoteEndpoint, SilKit::Services::Logging::ILoggerInternal& logger); ~AsioConnector() override; public: // IAcceptor @@ -106,7 +106,8 @@ class AsioConnector final : public IConnector template AsioConnector::AsioConnector(std::shared_ptr asioIoContext, const AsioSocketOptions& socketOptions, - const AsioEndpointType& remoteEndpoint, SilKit::Services::Logging::ILogger& logger) + const AsioEndpointType& remoteEndpoint, + SilKit::Services::Logging::ILoggerInternal& logger) : _asioIoContext{std::move(asioIoContext)} , _logger{&logger} , _op{std::make_shared(*this, socketOptions, remoteEndpoint)} diff --git a/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp b/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp index f9fdf93b0..b13569549 100644 --- a/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp +++ b/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp @@ -57,7 +57,7 @@ namespace VSilKit { AsioGenericRawByteStream::AsioGenericRawByteStream(const AsioGenericRawByteStreamOptions& options, std::shared_ptr asioIoContext, AsioSocket socket, - SilKit::Services::Logging::ILogger& logger) + SilKit::Services::Logging::ILoggerInternal& logger) : _options{options} , _asioIoContext{std::move(asioIoContext)} , _socket{std::move(socket)} @@ -270,8 +270,10 @@ void AsioGenericRawByteStream::HandleShutdownOrError() _socket.close(errorCode); if (errorCode) { - Log::Warn(_logger, "AsioGenericRawByteStream::HandleShutdownOrError: socket close failed: {}", - errorCode.message()); + _logger->MakeMessage(Log::Level::Warn, Log::Topic::Asio) + .SetMessage("AsioGenericRawByteStream::HandleShutdownOrError: socket close failed: {}", + errorCode.message()) + .Dispatch(); } } @@ -304,10 +306,10 @@ void AsioGenericRawByteStream::EnableQuickAck() int e = setsockopt(_socket.native_handle(), IPPROTO_TCP, TCP_QUICKACK, (void*)&val, sizeof(val)); if (e != 0) { - Log::Warn( - _logger, - "AsioGenericRawByteStream({})::EnableQuickAck: failed to set Linux-specific socket option 'TCP_QUICKACK'", - static_cast(this)); + _logger->MakeMessage(Log::Level::Warn, Log::Topic::Asio) + .SetMessage("AsioGenericRawByteStream({})::EnableQuickAck: failed to set Linux-specific socket option " + "'TCP_QUICKACK'", static_cast(this)) + .Dispatch(); } } diff --git a/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.hpp b/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.hpp index 7246935fd..5c0e48461 100644 --- a/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.hpp +++ b/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.hpp @@ -50,12 +50,12 @@ class AsioGenericRawByteStream final : public IRawByteStream std::shared_ptr _asioIoContext; AsioSocket _socket; - SilKit::Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; public: AsioGenericRawByteStream(const AsioGenericRawByteStreamOptions& options, std::shared_ptr asioIoContext, AsioSocket socket, - SilKit::Services::Logging::ILogger& logger); + SilKit::Services::Logging::ILoggerInternal& logger); ~AsioGenericRawByteStream() override; public: // IRawByteStream diff --git a/SilKit/source/core/vasio/io/impl/AsioIoContext.cpp b/SilKit/source/core/vasio/io/impl/AsioIoContext.cpp index a00b5d8e2..b34416afb 100644 --- a/SilKit/source/core/vasio/io/impl/AsioIoContext.cpp +++ b/SilKit/source/core/vasio/io/impl/AsioIoContext.cpp @@ -46,12 +46,12 @@ void SetSocketPermissions(const EndpointT&) } template -void SetListenOptions(SilKit::Services::Logging::ILogger*, AcceptorT&) +void SetListenOptions(SilKit::Services::Logging::ILoggerInternal*, AcceptorT&) { } template -void SetConnectOptions(SilKit::Services::Logging::ILogger*, SocketT&) +void SetConnectOptions(SilKit::Services::Logging::ILoggerInternal*, SocketT&) { } @@ -70,7 +70,7 @@ void SetPlatformOptions(asio::ip::tcp::acceptor& acceptor) #if !defined(__MINGW32__) template <> -void SetListenOptions(SilKit::Services::Logging::ILogger* logger, asio::ip::tcp::acceptor& acceptor) +void SetListenOptions(SilKit::Services::Logging::ILoggerInternal* logger, asio::ip::tcp::acceptor& acceptor) { // This should improve loopback performance, and have no effect on remote TCP/IP int enabled = 1; @@ -81,13 +81,15 @@ void SetListenOptions(SilKit::Services::Logging::ILogger* logger, asio::ip::tcp: if (result == SOCKET_ERROR) { auto lastError = ::GetLastError(); - SilKit::Services::Logging::Warn( - logger, "SetListenOptions: Setting Loopback FastPath failed: WSA IOCtl last error: {}", lastError); + + logger->MakeMessage(SilKit::Services::Logging::Level::Warn, SilKit::Services::Logging::Topic::Asio) + .SetMessage("SetListenOptions: Setting Loopback FastPath failed: WSA IOCtl last error: {}", lastError) + .Dispatch(); } } template <> -void SetConnectOptions(SilKit::Services::Logging::ILogger* logger, asio::ip::tcp::socket& socket) +void SetConnectOptions(SilKit::Services::Logging::ILoggerInternal* logger, asio::ip::tcp::socket& socket) { // This should improve loopback performance, and have no effect on remote TCP/IP int enabled = 1; @@ -98,8 +100,9 @@ void SetConnectOptions(SilKit::Services::Logging::ILogger* logger, asio::ip::tcp if (result == SOCKET_ERROR) { auto lastError = ::GetLastError(); - SilKit::Services::Logging::Warn( - logger, "SetListenOptions: Setting Loopback FastPath failed: WSA IOCtl last error: {}", lastError); + logger->MakeMessage(SilKit::Services::Logging::Level::Warn, SilKit::Services::Logging::Topic::Asio) + .SetMessage("SetListenOptions: Setting Loopback FastPath failed: WSA IOCtl last error: {}", lastError) + .Dispatch(); } } @@ -202,7 +205,7 @@ static auto CleanIpAddress(const std::string& string) -> std::string } template -void OpenAcceptor(AsioAcceptorType& acceptor, AsioEndpointType endpoint, SilKit::Services::Logging::ILogger& logger) +void OpenAcceptor(AsioAcceptorType& acceptor, AsioEndpointType endpoint, SilKit::Services::Logging::ILoggerInternal& logger) { acceptor.open(endpoint.protocol()); SetPlatformOptions(acceptor); @@ -299,7 +302,7 @@ auto AsioIoContext::Resolve(const std::string& name) -> std::vector } -void AsioIoContext::SetLogger(SilKit::Services::Logging::ILogger& logger) +void AsioIoContext::SetLogger(SilKit::Services::Logging::ILoggerInternal& logger) { SILKIT_TRACE_METHOD_(&logger, "({})", static_cast(&logger)); _logger = &logger; diff --git a/SilKit/source/core/vasio/io/impl/AsioIoContext.hpp b/SilKit/source/core/vasio/io/impl/AsioIoContext.hpp index 5181090a3..fec287cd5 100644 --- a/SilKit/source/core/vasio/io/impl/AsioIoContext.hpp +++ b/SilKit/source/core/vasio/io/impl/AsioIoContext.hpp @@ -28,7 +28,7 @@ class AsioIoContext final : public IIoContext { AsioSocketOptions _socketOptions; std::shared_ptr _asioIoContext; - SilKit::Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; public: explicit AsioIoContext(const AsioSocketOptions& socketOptions); @@ -44,7 +44,7 @@ class AsioIoContext final : public IIoContext auto MakeLocalConnector(const std::string& path) -> std::unique_ptr override; auto MakeTimer() -> std::unique_ptr override; auto Resolve(const std::string& name) -> std::vector override; - void SetLogger(SilKit::Services::Logging::ILogger& logger) override; + void SetLogger(SilKit::Services::Logging::ILoggerInternal& logger) override; }; diff --git a/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.cpp b/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.cpp index 9f46da44d..64b75312c 100644 --- a/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.cpp +++ b/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.cpp @@ -15,7 +15,7 @@ namespace Log = SilKit::Services::Logging; namespace VSilKit { -void SetAsioSocketOptions(SilKit::Services::Logging::ILogger* logger, asio::ip::tcp::socket& socket, +void SetAsioSocketOptions(Log::ILoggerInternal* logger, asio::ip::tcp::socket& socket, const AsioSocketOptions& socketOptions, std::error_code& errorCode) { if (socketOptions.tcp.noDelay) @@ -23,7 +23,9 @@ void SetAsioSocketOptions(SilKit::Services::Logging::ILogger* logger, asio::ip:: socket.set_option(asio::ip::tcp::no_delay{true}, errorCode); if (errorCode) { - Log::Warn(logger, "SetAsioSocketOptions: failed to enable 'no delay' option"); + logger->MakeMessage(SilKit::Services::Logging::Level::Warn, SilKit::Services::Logging::Topic::Asio) + .SetMessage("SetAsioSocketOptions: failed to enable 'no delay' option") + .Dispatch(); return; } } @@ -33,8 +35,10 @@ void SetAsioSocketOptions(SilKit::Services::Logging::ILogger* logger, asio::ip:: socket.set_option(asio::socket_base::receive_buffer_size{socketOptions.tcp.receiveBufferSize}, errorCode); if (errorCode) { - Log::Warn(logger, "SetAsioSocketOptions: failed to set receive buffer size to {}: {}", - socketOptions.tcp.receiveBufferSize, errorCode.message()); + logger->MakeMessage(SilKit::Services::Logging::Level::Warn, SilKit::Services::Logging::Topic::Asio) + .SetMessage("SetAsioSocketOptions: failed to set receive buffer size to {}: {}", + socketOptions.tcp.receiveBufferSize, errorCode.message()) + .Dispatch(); return; } } @@ -44,15 +48,18 @@ void SetAsioSocketOptions(SilKit::Services::Logging::ILogger* logger, asio::ip:: socket.set_option(asio::socket_base::send_buffer_size{socketOptions.tcp.sendBufferSize}, errorCode); if (errorCode) { - Log::Warn(logger, "SetAsioSocketOptions: failed to set send buffer size to {}: {}", - socketOptions.tcp.sendBufferSize, errorCode.message()); + + logger->MakeMessage(SilKit::Services::Logging::Level::Warn, SilKit::Services::Logging::Topic::Asio) + .SetMessage("SetAsioSocketOptions: failed to set send buffer size to {}: {}", + socketOptions.tcp.sendBufferSize, errorCode.message()) + .Dispatch(); return; } } } -void SetAsioSocketOptions(SilKit::Services::Logging::ILogger*, asio::local::stream_protocol::socket&, +void SetAsioSocketOptions(SilKit::Services::Logging::ILoggerInternal*, asio::local::stream_protocol::socket&, const AsioSocketOptions&, std::error_code&) { // no local-domain specific options diff --git a/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.hpp b/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.hpp index 6798339fc..07adecd06 100644 --- a/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.hpp +++ b/SilKit/source/core/vasio/io/impl/SetAsioSocketOptions.hpp @@ -7,7 +7,7 @@ #include "AsioSocketOptions.hpp" -#include "silkit/services/logging/ILogger.hpp" +#include "ILoggerInternal.hpp" #include "asio.hpp" @@ -15,11 +15,12 @@ namespace VSilKit { -void SetAsioSocketOptions(SilKit::Services::Logging::ILogger* logger, asio::ip::tcp::socket& socket, +void SetAsioSocketOptions(SilKit::Services::Logging::ILoggerInternal* logger, asio::ip::tcp::socket& socket, const AsioSocketOptions& socketOptions, std::error_code& errorCode); -void SetAsioSocketOptions(SilKit::Services::Logging::ILogger* logger, asio::local::stream_protocol::socket& socket, +void SetAsioSocketOptions(SilKit::Services::Logging::ILoggerInternal* logger, + asio::local::stream_protocol::socket& socket, const AsioSocketOptions& socketOptions, std::error_code& errorCode); diff --git a/SilKit/source/core/vasio/io/mock/MockIoContext.hpp b/SilKit/source/core/vasio/io/mock/MockIoContext.hpp index 35c428458..03f0b4602 100644 --- a/SilKit/source/core/vasio/io/mock/MockIoContext.hpp +++ b/SilKit/source/core/vasio/io/mock/MockIoContext.hpp @@ -37,7 +37,7 @@ struct MockIoContext : IIoContext MOCK_METHOD(std::vector, Resolve, (const std::string&), (override)); - MOCK_METHOD(void, SetLogger, (SilKit::Services::Logging::ILogger&), (override)); + MOCK_METHOD(void, SetLogger, (SilKit::Services::Logging::ILoggerInternal&), (override)); }; @@ -90,7 +90,7 @@ struct MockIoContextWithExecutionQueue : IIoContext MOCK_METHOD(std::vector, Resolve, (const std::string&), (override)); - MOCK_METHOD(void, SetLogger, (SilKit::Services::Logging::ILogger&), (override)); + MOCK_METHOD(void, SetLogger, (SilKit::Services::Logging::ILoggerInternal&), (override)); }; From 0ff32f4f860f3190526f7071627db126660ca1e6 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Tue, 14 Apr 2026 13:22:02 +0200 Subject: [PATCH 09/23] fixup! Upgrade logging in asio component --- .../internal/traits/SilKitLoggingTraits.hpp | 20 ++++- SilKit/source/core/vasio/VAsioRegistry.cpp | 87 ++++++++++++------- 2 files changed, 72 insertions(+), 35 deletions(-) diff --git a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp index 68def0eaf..88fd30423 100644 --- a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp @@ -9,6 +9,7 @@ namespace VSilKit { class SystemStateTracker; +class ConnectPeer; } namespace SilKit { @@ -16,12 +17,18 @@ namespace Core { class IParticipantInternal; class VAsioConnection; class VAsioPeer; +class VAsioRegistry; template class Participant; -} -} +}} + +namespace SilKit { +namespace Services { +namespace Orchestration { +class TimeConfiguration; +}}} namespace SilKit { namespace Core { @@ -64,11 +71,16 @@ struct TopicTraits> return SilKit::Services::Logging::Topic::Participant; } }; +DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeSyncService, SilKit::Services::Logging::Topic::TimeSync); +DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeConfiguration,SilKit::Services::Logging::Topic::TimeSync); -DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeSyncService, SilKit::Services::Logging::Topic::TimeSyncService); - +DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioRegistry, SilKit::Services::Logging::Topic::Asio); DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioConnection, SilKit::Services::Logging::Topic::Asio); DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioPeer, SilKit::Services::Logging::Topic::Asio); +DefineSilKitLoggingTrait_Topic(VSilKit::ConnectPeer, SilKit::Services::Logging::Topic::Asio); + + +DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::LifecycleService, SilKit::Services::Logging::Topic::LifeCycle); DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::SystemState, SilKit::Services::Logging::Topic::SystemState); DefineSilKitLoggingTrait_Topic(VSilKit::SystemStateTracker, SilKit::Services::Logging::Topic::SystemState); diff --git a/SilKit/source/core/vasio/VAsioRegistry.cpp b/SilKit/source/core/vasio/VAsioRegistry.cpp index 54d1bffad..dfbdf3a7f 100644 --- a/SilKit/source/core/vasio/VAsioRegistry.cpp +++ b/SilKit/source/core/vasio/VAsioRegistry.cpp @@ -88,9 +88,10 @@ auto VAsioRegistry::StartListening(const std::string& listenUri) -> std::string } catch (const std::exception& e) { - Services::Logging::Error(GetLogger(), - "SIL Kit Registry failed to create listening socket {}:{} (uri: {}). Reason: {}", - uri.Host(), uri.Port(), uri.EncodedString(), e.what()); + GetLogger()->MakeMessage(Log::Level::Error, *this) + .SetMessage("SIL Kit Registry failed to create listening socket {}:{} (uri: {}). Reason: {}", + uri.Host(), uri.Port(), uri.EncodedString(), e.what()) + .Dispatch(); } if (enableDomainSockets) @@ -111,41 +112,48 @@ auto VAsioRegistry::StartListening(const std::string& listenUri) -> std::string } catch (const std::exception& e) { - Services::Logging::Warn(GetLogger(), "SIL Kit Registry failed to create local listening socket: {}", - e.what()); + GetLogger()->MakeMessage(Log::Level::Warn, *this) + .SetMessage("SIL Kit Registry failed to create local listening socket: {}", e.what()) + .Dispatch(); } } if (hasTcpSocket && hasDomainSocket) { - Services::Logging::Debug(GetLogger(), "SIL Kit Registry: Listening on both, TCP and Domain sockets"); + GetLogger()->MakeMessage(Log::Level::Debug, *this) + .SetMessage("SIL Kit Registry: Listening on both, TCP and Domain sockets") + .Dispatch(); } else if (hasTcpSocket && !hasDomainSocket) { if (enableDomainSockets) { - // There exist old versions of Windows that do not support domain sockets. Here only TCP/IP will be available. - _logger->Warn( - "This registry instance will only accept connections on TCP sockets. This might be caused by a second " - "registry running on this host, or using an operating system that does not support Domain sockets."); + GetLogger()->MakeMessage(Log::Level::Warn, *this) + .SetMessage("This registry instance will only accept connections on TCP sockets. This might be caused by a second " + "registry running on this host, or using an operating system that does not support Domain sockets.") + .Dispatch(); } else { - _logger->Warn("This registry instance will only accept connections on TCP sockets. Domain sockets were " - "explicitly disabled through the participant configuration."); + GetLogger()->MakeMessage(Log::Level::Warn, *this) + .SetMessage("This registry instance will only accept connections on TCP sockets. Domain sockets were " + "explicitly disabled through the participant configuration.") + .Dispatch(); } } else if (!hasTcpSocket && hasDomainSocket) { - // For scenarios where multiple instances run on the same host, binding on TCP/IP will result in an error. - // However, if we can accept local ipc connections we warn and continue. - _logger->Warn("This registry instance will only accept connections on local domain sockets. This might be " + GetLogger()->MakeMessage(Log::Level::Warn, *this) + .SetMessage("This registry instance will only accept connections on local domain sockets. This might be " "caused by a second registry running on this host, or another process was already bound to the " - "same port as this registry was attempting to use."); + "same port as this registry was attempting to use.") + .Dispatch(); } else { - Services::Logging::Error(GetLogger(), "SIL Kit Registry: Unable to listen on neither TCP, nor Domain sockets"); + GetLogger()->MakeMessage(Log::Level::Error, *this) + .SetMessage("SIL Kit Registry: Unable to listen on neither TCP, nor Domain sockets") + .Dispatch(); throw SilKit::StateError{"SIL Kit Registry: Unable to listen on neither TCP, nor Domain sockets"}; } @@ -213,7 +221,9 @@ void VAsioRegistry::OnParticipantAnnouncement(IVAsioPeer* peer, const Participan { const auto message = fmt::format("A participant with the same name '{}' already exists in the simulation {}", peerInfo.participantName, announcement.simulationName); - GetLogger()->Warn(message); + GetLogger()->MakeMessage(Log::Level::Warn, *this) + .SetMessage(message) + .Dispatch(); throw SilKitError{message}; } @@ -231,7 +241,9 @@ void VAsioRegistry::OnParticipantAnnouncement(IVAsioPeer* peer, const Participan if (AllParticipantsAreConnected()) { - _logger->Info("All participants are online"); + GetLogger()->MakeMessage(Log::Level::Info, *this) + .SetMessage("All participants are online") + .Dispatch(); if (_onAllParticipantsConnected) _onAllParticipantsConnected(); } @@ -239,9 +251,11 @@ void VAsioRegistry::OnParticipantAnnouncement(IVAsioPeer* peer, const Participan void VAsioRegistry::SendKnownParticipants(IVAsioPeer* peer, const std::string& simulationName) { - Services::Logging::Info(GetLogger(), "Sending known participant message to {}, protocol version {}.{}", + GetLogger()->MakeMessage(Log::Level::Info, *this) + .SetMessage("Sending known participant message to {}, protocol version {}.{}", peer->GetInfo().participantName, peer->GetProtocolVersion().major, - peer->GetProtocolVersion().minor); + peer->GetProtocolVersion().minor) + .Dispatch(); KnownParticipants knownParticipantsMsg; knownParticipantsMsg.messageHeader = MakeRegistryMsgHeader(peer->GetProtocolVersion()); @@ -267,8 +281,6 @@ void VAsioRegistry::SendKnownParticipants(IVAsioPeer* peer, const std::string& s void VAsioRegistry::OnPeerShutdown(IVAsioPeer* peer) { - namespace Log = SilKit::Services::Logging; - const auto& simulationName{peer->GetSimulationName()}; const auto& participantName{peer->GetInfo().participantName}; @@ -276,18 +288,24 @@ void VAsioRegistry::OnPeerShutdown(IVAsioPeer* peer) if (connectedParticipant == nullptr) { - Log::Debug(_logger.get(), "Peer '{}' has shut down, which had no participant information", participantName); + GetLogger()->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Peer '{}' has shut down, which had no participant information", participantName) + .Dispatch(); return; } if (connectedParticipant->peer != peer) { - Log::Debug(_logger.get(), "Duplicate peer '{}' has shut down, which had no participant information", - participantName); + GetLogger()->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Duplicate peer '{}' has shut down, which had no participant information", + participantName) + .Dispatch(); return; } - Log::Debug(_logger.get(), "Peer '{}' has shut down", participantName); + GetLogger()->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Peer '{}' has shut down", participantName) + .Dispatch(); if (_registryEventListener != nullptr) { @@ -303,7 +321,9 @@ void VAsioRegistry::OnPeerShutdown(IVAsioPeer* peer) if (_connectedParticipants.empty()) { - _logger->Info("All participants are shut down"); + GetLogger()->MakeMessage(Log::Level::Info, *this) + .SetMessage("All participants are shut down") + .Dispatch(); if (_onAllParticipantsDisconnected) _onAllParticipantsDisconnected(); } @@ -404,11 +424,16 @@ auto VAsioRegistry::GetServiceDescriptor() const -> const ServiceDescriptor& void VAsioRegistry::OnMetricsUpdate(const std::string& simulationName, const std::string& participantName, const VSilKit::MetricsUpdate& metricsUpdate) { - Log::Info(GetLogger(), "Participant {} updates {} metrics", participantName, metricsUpdate.metrics.size()); + GetLogger()->MakeMessage(Log::Level::Info, *this) + .SetMessage("Participant {} updates {} metrics", participantName, metricsUpdate.metrics.size()) + .Dispatch(); + for (const auto& data : metricsUpdate.metrics) { - Log::Info(GetLogger(), "Metric Update: {} {} {} {} ({})", data.name, data.kind, data.value, data.timestamp, - participantName); + GetLogger()->MakeMessage(Log::Level::Info, *this) + .SetMessage("Metric Update: {} {} {} {} ({})", data.name, data.kind, data.value, data.timestamp, + participantName) + .Dispatch(); } dynamic_cast(*_metricsProcessor) From f51e9796a1953cf9fcd483bff5e42c317b255a11 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Wed, 15 Apr 2026 14:21:18 +0200 Subject: [PATCH 10/23] Roll out the new internal logger interface --- .../services/logging/LoggingDatatypes.hpp | 21 ++--- .../silkit/services/logging/string_utils.hpp | 23 +++++- .../internal/traits/SilKitLoggingTraits.hpp | 49 +++++++++--- .../core/participant/Participant_impl.hpp | 11 ++- .../requests/procs/ParticipantReplies.cpp | 24 ++++-- .../core/vasio/ConnectKnownParticipants.cpp | 46 +++++++---- .../core/vasio/ConnectKnownParticipants.hpp | 4 +- SilKit/source/core/vasio/ConnectPeer.cpp | 8 +- .../core/vasio/RemoteConnectionManager.cpp | 14 ++-- .../services/logging/ILoggerInternal.hpp | 1 + .../orchestration/LifecycleManagement.cpp | 28 +++++-- .../orchestration/LifecycleManagement.hpp | 6 +- .../orchestration/LifecycleService.cpp | 79 +++++++++++++------ .../orchestration/LifecycleService.hpp | 2 +- .../services/orchestration/SystemMonitor.cpp | 33 +++++--- .../orchestration/TimeConfiguration.cpp | 32 +++++--- .../orchestration/TimeSyncService.cpp | 2 +- 17 files changed, 259 insertions(+), 124 deletions(-) diff --git a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp index 0ee0ce92b..16c7ecc33 100644 --- a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp +++ b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp @@ -27,15 +27,18 @@ enum class Level : uint32_t */ enum class Topic : uint32_t { - None = 0, //!< Log message without topic - User = 1, //!< Log message of the SIL Kit user - LifeCycle = 2, //!< Log message of the lifecycle - SystemState = 3, //!< Log message of the system state - MessageTracing = 4, //!< Log message of the message tracing - ServiceDiscovery = 5, //!< Log message of the service discovery - Asio = 6, //!< Log message of the asio - TimeSyncService = 7, //!< Log message of the time sync service - Participant = 8, //!< Log message of the participant + None = 0, //!< Log message without topic + User = 1, //!< Log message of the SIL Kit user + LifeCycle = 2, //!< Log message of the lifecycle + SystemState = 3, //!< Log message of the system state + MessageTracing = 4, //!< Log message of the message tracing + ServiceDiscovery = 5, //!< Log message of the service discovery + Asio = 6, //!< Log message of the asio + TimeSync = 7, //!< Log message of the time sync service + Participant = 8, //!< Log message of the participant + TimeConfig = 9, + RequestReply = 10, + SystemMonitor = 11, Invalid = 0xffffffff //!< Invalid log message topic }; diff --git a/SilKit/include/silkit/services/logging/string_utils.hpp b/SilKit/include/silkit/services/logging/string_utils.hpp index 844b5767f..628ffddf6 100644 --- a/SilKit/include/silkit/services/logging/string_utils.hpp +++ b/SilKit/include/silkit/services/logging/string_utils.hpp @@ -103,8 +103,8 @@ std::ostream& operator<<(std::ostream& outStream, const Topic& topic) case Topic::User: outStream << "user"; break; - case Topic::TimeSyncService: - outStream << "timesyncservice"; + case Topic::TimeSync: + outStream << "timesync"; break; case Topic::LifeCycle: outStream << "lifecycle"; @@ -124,6 +124,15 @@ std::ostream& operator<<(std::ostream& outStream, const Topic& topic) case Topic::Asio: outStream << "asio"; break; + case Topic::TimeConfig: + outStream << "timeconfig"; + break; + case Topic::RequestReply: + outStream << "requestreply"; + break; + case Topic::SystemMonitor: + outStream << "systemmonitor"; + break; case Topic::None: outStream << "none"; break; @@ -140,8 +149,8 @@ inline Topic from_topic_string(const std::string& topicStr) return Topic::None; if (topic == "user") return Topic::User; - if (topic == "timesyncservice") - return Topic::TimeSyncService; + if (topic == "timesync") + return Topic::TimeSync; if (topic == "lifecycle") return Topic::LifeCycle; if (topic == "systemstate") @@ -152,8 +161,14 @@ inline Topic from_topic_string(const std::string& topicStr) return Topic::ServiceDiscovery; if (topic == "participant") return Topic::Participant; + if (topic == "timeconfig") + return Topic::TimeConfig; if (topic == "asio") return Topic::Asio; + if (topic == "requestreply") + return Topic::RequestReply; + if (topic == "systemmonitor") + return Topic::SystemMonitor; return Topic::Invalid; } /* diff --git a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp index 88fd30423..8e09fcf7c 100644 --- a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp @@ -14,21 +14,39 @@ class ConnectPeer; namespace SilKit { namespace Core { + +namespace RequestReply { +class ParticipantReplies; +} + class IParticipantInternal; +class ConnectKnownParticipants; +class RemoteConnectionManager; class VAsioConnection; -class VAsioPeer; class VAsioRegistry; template class Participant; -}} + + +} +} namespace SilKit { namespace Services { namespace Orchestration { + +class TimeSyncService; class TimeConfiguration; -}}} +class SystemMonitor; +class LifecycleService; + +class LifecycleManagement; +} +} +} + namespace SilKit { namespace Core { @@ -43,7 +61,6 @@ struct TopicTraits } }; - // The final service traits template struct SilKitTopicTrait : TopicTraits @@ -62,6 +79,11 @@ struct SilKitTopicTrait : TopicTraits } \ } +DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeSyncService, SilKit::Services::Logging::Topic::TimeSync); +DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeConfiguration, SilKit::Services::Logging::Topic::TimeConfig); + +DefineSilKitLoggingTrait_Topic(SilKit::Core::IParticipantInternal, SilKit::Services::Logging::Topic::Participant); + template struct TopicTraits> @@ -71,18 +93,21 @@ struct TopicTraits> return SilKit::Services::Logging::Topic::Participant; } }; -DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeSyncService, SilKit::Services::Logging::Topic::TimeSync); -DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeConfiguration,SilKit::Services::Logging::Topic::TimeSync); - -DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioRegistry, SilKit::Services::Logging::Topic::Asio); -DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioConnection, SilKit::Services::Logging::Topic::Asio); -DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioPeer, SilKit::Services::Logging::Topic::Asio); -DefineSilKitLoggingTrait_Topic(VSilKit::ConnectPeer, SilKit::Services::Logging::Topic::Asio); +DefineSilKitLoggingTrait_Topic(SilKit::Core::RequestReply::ParticipantReplies, SilKit::Services::Logging::Topic::Participant); DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::LifecycleService, SilKit::Services::Logging::Topic::LifeCycle); +DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::LifecycleManagement, SilKit::Services::Logging::Topic::LifeCycle); + +DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::SystemMonitor, SilKit::Services::Logging::Topic::SystemState); + +DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioConnection, SilKit::Services::Logging::Topic::Asio); +DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioRegistry, SilKit::Services::Logging::Topic::Asio); +DefineSilKitLoggingTrait_Topic(SilKit::Core::ConnectKnownParticipants, SilKit::Services::Logging::Topic::Asio); +DefineSilKitLoggingTrait_Topic(SilKit::Core::RemoteConnectionManager, SilKit::Services::Logging::Topic::Asio); + +DefineSilKitLoggingTrait_Topic(VSilKit::ConnectPeer, SilKit::Services::Logging::Topic::Asio); -DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::SystemState, SilKit::Services::Logging::Topic::SystemState); DefineSilKitLoggingTrait_Topic(VSilKit::SystemStateTracker, SilKit::Services::Logging::Topic::SystemState); diff --git a/SilKit/source/core/participant/Participant_impl.hpp b/SilKit/source/core/participant/Participant_impl.hpp index b96c203e2..c04707a1b 100644 --- a/SilKit/source/core/participant/Participant_impl.hpp +++ b/SilKit/source/core/participant/Participant_impl.hpp @@ -627,8 +627,10 @@ auto Participant::CreateRpcServerInternal( const std::vector& clientLabels, Services::Rpc::RpcCallHandler handler, Services::Rpc::IRpcServer* parent) -> Services::Rpc::RpcServerInternal* { - Logging::Trace(GetLogger(), "Creating internal server for functionName={}, clientUUID={}", functionName, - clientUUID); + + GetLoggerInternal()->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Creating internal server for functionName={}, clientUUID={}", functionName, clientUUID) + .Dispatch(); SilKit::Config::RpcServer controllerConfig; // Use a unique name to avoid collisions of several RpcSevers on same functionName on one participant @@ -861,8 +863,9 @@ auto Participant::CreateLifecycleService( dynamic_cast(lifecycleService) ->SetLifecycleConfiguration(startConfiguration); - Logging::Trace(GetLogger(), "Created Lifecycle with operating mode {}", - FormatLifecycleConfigurationForLogging(startConfiguration)); + GetLoggerInternal()->MakeMessage(Logging::Level::Trace, *this) + .SetMessage("Created Lifecycle with operating mode {}", FormatLifecycleConfigurationForLogging(startConfiguration)) + .Dispatch(); return lifecycleService; } diff --git a/SilKit/source/core/requests/procs/ParticipantReplies.cpp b/SilKit/source/core/requests/procs/ParticipantReplies.cpp index b56f5ec78..56a346400 100644 --- a/SilKit/source/core/requests/procs/ParticipantReplies.cpp +++ b/SilKit/source/core/requests/procs/ParticipantReplies.cpp @@ -29,21 +29,27 @@ void ParticipantReplies::CallAfterAllParticipantsReplied(std::function c _participant->ExecuteDeferred([this, completionFunction = std::move(completionFunction)]() mutable { if (_barrierActive) { - Services::Logging::Debug(_participant->GetLogger(), - "Still waiting for replies from participants on a previous call, action when new " - "call is replied will not be executed. This might lead to unexpected behavior."); + _participant->GetLoggerInternal()->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("Still waiting for replies from participants on a previous call, action when new " + "call is replied will not be executed. This might lead to unexpected behavior.") + .Dispatch(); return; } auto remoteReceivers = _participant->GetParticipantNamesOfRemoteReceivers(_requestReplyServiceEndpoint, "REQUESTREPLYCALL"); _expectedParticipantsToSendCallReturns = std::set(remoteReceivers.begin(), remoteReceivers.end()); - Services::Logging::Debug(_participant->GetLogger(), "Request replies of {} participant(s).", - _expectedParticipantsToSendCallReturns.size()); + + _participant->GetLoggerInternal()->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("Request replies of {} participant(s).", + _expectedParticipantsToSendCallReturns.size()) + .Dispatch(); + if (_expectedParticipantsToSendCallReturns.empty()) { - Services::Logging::Debug(_participant->GetLogger(), - "Called CallAfterAllParticipantsReplied() with no other known participants."); + _participant->GetLoggerInternal()->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("Called CallAfterAllParticipantsReplied() with no other known participants.") + .Dispatch(); completionFunction(); return; } @@ -81,7 +87,9 @@ void ParticipantReplies::ReceiveCallReturn(std::string fromParticipant, Util::Uu { if (_completionFunction) { - Services::Logging::Debug(_participant->GetLogger(), "Request participant replies completed."); + _participant->GetLoggerInternal()->MakeMessage(Services::Logging::Level::Debug, *this) + .SetMessage("Request participant replies completed.") + .Dispatch(); _completionFunction(); } _barrierActive = false; diff --git a/SilKit/source/core/vasio/ConnectKnownParticipants.cpp b/SilKit/source/core/vasio/ConnectKnownParticipants.cpp index af28cfd34..fc817464b 100644 --- a/SilKit/source/core/vasio/ConnectKnownParticipants.cpp +++ b/SilKit/source/core/vasio/ConnectKnownParticipants.cpp @@ -44,7 +44,7 @@ ConnectKnownParticipants::ConnectKnownParticipants(IIoContext& ioContext, IConne } -void ConnectKnownParticipants::SetLogger(SilKit::Services::Logging::ILogger& logger) +void ConnectKnownParticipants::SetLogger(SilKit::Services::Logging::ILoggerInternal& logger) { SILKIT_ASSERT(_logger == nullptr); _logger = &logger; @@ -96,7 +96,11 @@ void ConnectKnownParticipants::HandlePeerEvent(const std::string& participantNam auto peer{FindPeerByName(participantName)}; if (peer == nullptr) { - Log::Warn(_logger, "Ignoring event '{}' for peer '{}'", event, participantName); + + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Ignoring event '{}' for peer '{}'", event, participantName) + .Dispatch(); + return; } @@ -267,9 +271,10 @@ void ConnectKnownParticipants::Peer::HandleEvent(PeerEvent event) { if (_peerStage != PeerStage::REMOTE_CONNECT_REQUESTED) { - Log::Warn(_manager->_logger, - "Ignoring unexpected remote participant connecting notification from peer '{}' in stage {}", - _info.participantName, _peerStage.load()); + _manager->_logger->MakeMessage(Log::Level::Warn, *_manager) + .SetMessage("Ignoring unexpected remote participant connecting notification from peer '{}' in stage {}", + _info.participantName, _peerStage.load()) + .Dispatch(); return; } @@ -282,10 +287,10 @@ void ConnectKnownParticipants::Peer::HandleEvent(PeerEvent event) { if (_peerStage != PeerStage::REMOTE_CONNECT_REQUESTED && _peerStage != PeerStage::REMOTE_IS_CONNECTING) { - Log::Warn( - _manager->_logger, - "Ignoring unexpected remote participant connection failure notification from peer '{}' in stage {}", - _info.participantName, _peerStage.load()); + _manager->_logger->MakeMessage(Log::Level::Warn, *_manager) + .SetMessage("Ignoring unexpected remote participant connection failure notification from peer '{}' in stage {}", + _info.participantName, _peerStage.load()) + .Dispatch(); return; } @@ -305,9 +310,10 @@ void ConnectKnownParticipants::Peer::HandleEvent(PeerEvent event) { if (_peerStage != PeerStage::REMOTE_CONNECT_REQUESTED && _peerStage != PeerStage::REMOTE_IS_CONNECTING) { - Log::Warn(_manager->_logger, - "Ignoring unexpected remote participant announcement from peer '{}' in stage {}", - _info.participantName, _peerStage.load()); + _manager->_logger->MakeMessage(Log::Level::Warn, *_manager) + .SetMessage("Ignoring unexpected remote participant announcement from peer '{}' in stage {}", + _info.participantName, _peerStage.load()) + .Dispatch(); return; } @@ -320,8 +326,10 @@ void ConnectKnownParticipants::Peer::HandleEvent(PeerEvent event) { if (_peerStage != PeerStage::WAITING_FOR_REPLY) { - Log::Warn(_manager->_logger, "Ignoring unexpected reply from peer '{}' in stage {}", _info.participantName, - _peerStage.load()); + _manager->_logger->MakeMessage(Log::Level::Warn, *_manager) + .SetMessage("Ignoring unexpected reply from peer '{}' in stage {}", _info.participantName, + _peerStage.load()) + .Dispatch(); return; } @@ -438,8 +446,10 @@ void ConnectKnownParticipants::Peer::OnTimerExpired(VSilKit::ITimer&) if (_peerStage != PeerStage::REMOTE_CONNECT_REQUESTED) { - Log::Debug(_manager->_logger, "Ignoring expired remote connection request timer for {} in stage {}", - _info.participantName, _peerStage.load()); + _manager->_logger->MakeMessage(Log::Level::Debug, *_manager) + .SetMessage("Ignoring expired remote connection request timer for {} in stage {}", + _info.participantName, _peerStage.load()) + .Dispatch(); return; } @@ -458,7 +468,9 @@ void ConnectKnownParticipants::Peer::HasFailed(const std::string& reason) { SILKIT_TRACE_METHOD_(_logger, "({})", reason); - Log::Error(_manager->_logger, "Failed to connect to '{}' {}", _info.participantName, reason); + _manager->_logger->MakeMessage(Log::Level::Error, *_manager) + .SetMessage("Failed to connect to '{}' {}", _info.participantName, reason) + .Dispatch(); _failureReason = " "; _failureReason.append(reason); diff --git a/SilKit/source/core/vasio/ConnectKnownParticipants.hpp b/SilKit/source/core/vasio/ConnectKnownParticipants.hpp index 11e481316..1ec1e0f44 100644 --- a/SilKit/source/core/vasio/ConnectKnownParticipants.hpp +++ b/SilKit/source/core/vasio/ConnectKnownParticipants.hpp @@ -122,7 +122,7 @@ class ConnectKnownParticipants IConnectKnownParticipantsListener* _listener{nullptr}; ConnectKnownParticipantsSettings _settings; - SilKit::Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; std::promise> _knownParticipants; std::atomic _connectStage{ConnectStage::INVALID}; @@ -135,7 +135,7 @@ class ConnectKnownParticipants IConnectKnownParticipantsListener& listener, const ConnectKnownParticipantsSettings& settings); - void SetLogger(SilKit::Services::Logging::ILogger& logger); + void SetLogger(SilKit::Services::Logging::ILoggerInternal& logger); void SetKnownParticipants(const std::vector& peerInfos); void StartConnecting(); diff --git a/SilKit/source/core/vasio/ConnectPeer.cpp b/SilKit/source/core/vasio/ConnectPeer.cpp index fb23c8747..5e4a12a08 100644 --- a/SilKit/source/core/vasio/ConnectPeer.cpp +++ b/SilKit/source/core/vasio/ConnectPeer.cpp @@ -127,11 +127,15 @@ void ConnectPeer::UpdateUris() } catch (const std::exception& exception) { - Log::Warn(_logger, "Error occurred while processing acceptor URI '{}': {}", str, exception.what()); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Error occurred while processing acceptor URI '{}': {}", str, exception.what()) + .Dispatch(); } catch (...) { - Log::Warn(_logger, "Error occurred while processing acceptor URI '{}'", str); + _logger->MakeMessage(Log::Level::Warn, *this) + .SetMessage("Error occurred while processing acceptor URI '{}'", str) + .Dispatch(); } } diff --git a/SilKit/source/core/vasio/RemoteConnectionManager.cpp b/SilKit/source/core/vasio/RemoteConnectionManager.cpp index c0ee22678..f38738524 100644 --- a/SilKit/source/core/vasio/RemoteConnectionManager.cpp +++ b/SilKit/source/core/vasio/RemoteConnectionManager.cpp @@ -69,9 +69,10 @@ void RemoteConnectionManager::Remove(const IConnectPeer& connectPeer) void RemoteConnectionManager::OnConnectPeerSuccess(IConnectPeer& connectPeer, VAsioPeerInfo peerInfo, std::unique_ptr stream) { - SilKit::Services::Logging::Debug(_vAsioConnection->_logger, - "Successfully connected to {} after receiving a remote connect request", - peerInfo.participantName); + _vAsioConnection->_logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Successfully connected to {} after receiving a remote connect request", + peerInfo.participantName) + .Dispatch(); Remove(connectPeer); @@ -83,9 +84,10 @@ void RemoteConnectionManager::OnConnectPeerSuccess(IConnectPeer& connectPeer, VA void RemoteConnectionManager::OnConnectPeerFailure(IConnectPeer& connectPeer, VAsioPeerInfo peerInfo) { - SilKit::Services::Logging::Debug(_vAsioConnection->_logger, - "Failed to connect to {} after receiving a remote connect request", - peerInfo.participantName); + _vAsioConnection->_logger->MakeMessage(Log::Level::Debug, *this) + .SetMessage("Failed to connect to {} after receiving a remote connect request", + peerInfo.participantName) + .Dispatch(); Remove(connectPeer); _vAsioConnection->OnRemoteConnectionFailure(std::move(peerInfo)); diff --git a/SilKit/source/services/logging/ILoggerInternal.hpp b/SilKit/source/services/logging/ILoggerInternal.hpp index 9f27052b6..07739e9fa 100644 --- a/SilKit/source/services/logging/ILoggerInternal.hpp +++ b/SilKit/source/services/logging/ILoggerInternal.hpp @@ -28,6 +28,7 @@ struct ILoggerInternal : ILogger template LoggerMessage MakeMessage(Level level, ServiceT&) { + // todo: handle if there is no trait specialization for a type using T = std::decay_t; return MakeMessage(level, SilKit::Core::SilKitTopicTrait::Topic()); } diff --git a/SilKit/source/services/orchestration/LifecycleManagement.cpp b/SilKit/source/services/orchestration/LifecycleManagement.cpp index 89c73e2eb..5bd87cb96 100644 --- a/SilKit/source/services/orchestration/LifecycleManagement.cpp +++ b/SilKit/source/services/orchestration/LifecycleManagement.cpp @@ -13,7 +13,7 @@ namespace SilKit { namespace Services { namespace Orchestration { -LifecycleManagement::LifecycleManagement(Core::IParticipantInternal* participant, Services::Logging::ILogger* logger, +LifecycleManagement::LifecycleManagement(Core::IParticipantInternal* participant, Services::Logging::ILoggerInternal* logger, LifecycleService* parentService) : _participant{participant} , _lifecycleService(parentService) @@ -125,7 +125,9 @@ void LifecycleManagement::AbortSimulation(std::string reason) _currentState->AbortSimulation(std::move(reason)); if (_currentState == GetErrorState()) { - GetLogger()->Warn("AbortSimulation caused a transition to an error state"); + GetLogger()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("AbortSimulation caused a transition to an error state") + .Dispatch(); } } @@ -153,7 +155,9 @@ CallbackResult LifecycleManagement::HandleCommunicationReady() { std::stringstream ss; ss << "Detected exception in callback:\n" << e.what(); - _logger->Warn(ss.str()); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(ss.str()) + .Dispatch(); return CallbackResult::Error; } } @@ -169,7 +173,9 @@ bool LifecycleManagement::HandleStarting() { std::stringstream ss; ss << "Detected exception in callback:\n" << e.what(); - _logger->Warn(ss.str()); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(ss.str()) + .Dispatch(); return false; } } @@ -185,7 +191,9 @@ bool LifecycleManagement::HandleStop() { std::stringstream ss; ss << "Detected exception in callback:\n" << e.what(); - _logger->Warn(ss.str()); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(ss.str()) + .Dispatch(); return false; } } @@ -201,7 +209,9 @@ bool LifecycleManagement::HandleShutdown() { std::stringstream ss; ss << "Detected exception in callback:\n" << e.what(); - _logger->Warn(ss.str()); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(ss.str()) + .Dispatch(); return false; } } @@ -223,7 +233,9 @@ bool LifecycleManagement::HandleAbort() { std::stringstream ss; ss << "Detected exception in callback:\n" << e.what(); - _logger->Warn(ss.str()); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(ss.str()) + .Dispatch(); return false; } } @@ -351,7 +363,7 @@ ILifecycleState* LifecycleManagement::GetShutdownState() return _shutDownState.get(); } -Services::Logging::ILogger* LifecycleManagement::GetLogger() +Services::Logging::ILoggerInternal* LifecycleManagement::GetLogger() { return _logger; } diff --git a/SilKit/source/services/orchestration/LifecycleManagement.hpp b/SilKit/source/services/orchestration/LifecycleManagement.hpp index d5f2a2800..7682adeb6 100644 --- a/SilKit/source/services/orchestration/LifecycleManagement.hpp +++ b/SilKit/source/services/orchestration/LifecycleManagement.hpp @@ -24,7 +24,7 @@ class LifecycleService; class LifecycleManagement { public: //CTors - LifecycleManagement(Core::IParticipantInternal* participant, Services::Logging::ILogger* logger, + LifecycleManagement(Core::IParticipantInternal* participant, Services::Logging::ILoggerInternal* logger, LifecycleService* parentService); // Triggered by Public API calls @@ -102,7 +102,7 @@ class LifecycleManagement OperationMode GetOperationMode() const; // Interface getters - Logging::ILogger* GetLogger(); + Logging::ILoggerInternal* GetLogger(); LifecycleService* GetService(); Core::IParticipantInternal* GetParticipant(); @@ -131,7 +131,7 @@ class LifecycleManagement ILifecycleState* _lastBeforeAbortingState{nullptr}; LifecycleService* _lifecycleService; - Services::Logging::ILogger* _logger; + Services::Logging::ILoggerInternal* _logger; std::recursive_mutex _mutex; }; diff --git a/SilKit/source/services/orchestration/LifecycleService.cpp b/SilKit/source/services/orchestration/LifecycleService.cpp index e946dc344..2f8169bb2 100644 --- a/SilKit/source/services/orchestration/LifecycleService.cpp +++ b/SilKit/source/services/orchestration/LifecycleService.cpp @@ -22,8 +22,8 @@ namespace Orchestration { LifecycleService::LifecycleService(Core::IParticipantInternal* participant) : _participant{participant} - , _logger{participant->GetLogger()} - , _lifecycleManager{participant, participant->GetLogger(), this} + , _logger{participant->GetLoggerInternal()} + , _lifecycleManager{participant, participant->GetLoggerInternal(), this} , _finalStatePromise{std::make_unique>()} , _finalStateFuture{_finalStatePromise->get_future()} { @@ -46,17 +46,23 @@ void LifecycleService::SetCommunicationReadyHandlerAsync(CommunicationReadyHandl void LifecycleService::CompleteCommunicationReadyHandlerAsync() { - _logger->Debug("LifecycleService::CompleteCommunicationReadyHandler: enter"); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("LifecycleService::CompleteCommunicationReadyHandler: enter") + .Dispatch(); // async handler is finished, now continue to the Running state without triggering the CommunicationReadyHandler again if (!_commReadyHandlerInvoked) { - _logger->Debug("LifecycleService::CompleteCommunicationReadyHandler was called without invoking the " - "CommunicationReadyHandler, ignoring."); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("LifecycleService::CompleteCommunicationReadyHandler was called without invoking the " + "CommunicationReadyHandler, ignoring.") + .Dispatch(); return; } if (_commReadyHandlerCompleted) { - _logger->Debug("LifecycleService::CompleteCommunicationReadyHandler has been called already, ignoring."); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("LifecycleService::CompleteCommunicationReadyHandler has been called already, ignoring.") + .Dispatch(); return; } _commReadyHandlerCompleted = true; @@ -91,7 +97,10 @@ auto LifecycleService::StartLifecycle() -> std::future { std::stringstream ss; ss << "Lifecycle of participant " << _participant->GetParticipantName() << " started"; - _logger->Debug(ss.str()); + + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage(ss.str()) + .Dispatch(); _isLifecycleStarted = true; @@ -103,8 +112,10 @@ auto LifecycleService::StartLifecycle() -> std::future if (_abortedBeforeLifecycleStart) { _participant->ExecuteDeferred([this] { - _logger->Warn( - "LifecycleService::StartLifecycle(...) was called after receiving SystemCommand::AbortSimulation;"); + + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("LifecycleService::StartLifecycle(...) was called after receiving SystemCommand::AbortSimulation;") + .Dispatch(); _lifecycleManager.AbortSimulation("Lifecycle was aborted by SystemCommand::AbortSimulation"); }); return std::move(_finalStateFuture); @@ -169,19 +180,24 @@ auto LifecycleService::StartLifecycle() -> std::future void LifecycleService::ReportError(std::string errorMsg) { _participant->ExecuteDeferred([errorMsg, this] { - _logger->Error(errorMsg); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage(errorMsg) + .Dispatch(); if (!_isLifecycleStarted) { - _logger->Warn( - "LifecycleService::ReportError() was called before LifecycleService::StartLifecycle() was called;" - "transition to ParticipantState::Error is ignored."); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage( "LifecycleService::ReportError() was called before LifecycleService::StartLifecycle() was called;" + "transition to ParticipantState::Error is ignored.") + .Dispatch(); return; } else if (State() == ParticipantState::Shutdown) { - _logger->Warn("LifecycleService::ReportError() was called in terminal state ParticipantState::Shutdown; " - "transition to ParticipantState::Error is ignored."); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("LifecycleService::ReportError() was called in terminal state ParticipantState::Shutdown; " + "transition to ParticipantState::Error is ignored.") + .Dispatch(); return; } @@ -305,7 +321,10 @@ void LifecycleService::AbortSimulation(std::string reason) { std::stringstream msg; msg << "Received SystemCommand::AbortSimulation before LifecycleService::StartLifecycle(...) was called."; - _logger->Warn(msg.str()); + + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(msg.str()) + .Dispatch(); // If StartLifecycle is called afterwards, this flag is checked to trigger the actual abort handling. _abortedBeforeLifecycleStart = true; return; @@ -345,7 +364,9 @@ void LifecycleService::SetFinalStatePromise() { try { - _logger->Debug("Setting the final state promise"); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("Setting the final state promise") + .Dispatch(); _finalStatePromise->set_value(State()); } catch (const std::future_error&) @@ -455,7 +476,9 @@ void LifecycleService::ChangeParticipantState(ParticipantState newState, std::st std::stringstream ss; ss << "New ParticipantState: " << newState << "; reason: " << status.enterReason; - _logger->Debug(ss.str()); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage(ss.str()) + .Dispatch(); // assign the current status under lock (copy) { @@ -487,8 +510,10 @@ void LifecycleService::NewSystemState(SystemState systemState) std::stringstream ss; ss << "Received new system state: " << systemState; - Logging::Debug(_logger, ss.str().c_str()); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage(ss.str().c_str()) + .Dispatch(); switch (systemState) { case SystemState::Invalid: @@ -505,13 +530,19 @@ void LifecycleService::NewSystemState(SystemState systemState) _lifecycleManager.ReadyToRun(ss.str()); break; case SystemState::Running: - _logger->Info("Simulation is now running"); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Simulation is now running") + .Dispatch(); break; case SystemState::Paused: - _logger->Info("Simulation is paused"); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Simulation is paused") + .Dispatch(); break; case SystemState::Stopping: - _logger->Info("Simulation is stopping"); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Simulation is stopping") + .Dispatch(); // Only allow external stop signal if we are actually running or paused if (_lifecycleManager.GetCurrentState() == _lifecycleManager.GetRunningState() || _lifecycleManager.GetCurrentState() == _lifecycleManager.GetPausedState()) @@ -524,7 +555,9 @@ void LifecycleService::NewSystemState(SystemState systemState) case SystemState::ShuttingDown: break; case SystemState::Shutdown: - _logger->Info("Simulation is shut down"); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Simulation is shut down") + .Dispatch(); break; case SystemState::Aborting: break; diff --git a/SilKit/source/services/orchestration/LifecycleService.hpp b/SilKit/source/services/orchestration/LifecycleService.hpp index fb75df174..20a07722e 100644 --- a/SilKit/source/services/orchestration/LifecycleService.hpp +++ b/SilKit/source/services/orchestration/LifecycleService.hpp @@ -129,7 +129,7 @@ class LifecycleService // private members Core::IParticipantInternal* _participant{nullptr}; Core::ServiceDescriptor _serviceDescriptor{}; - Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; TimeSyncService* _timeSyncService; diff --git a/SilKit/source/services/orchestration/SystemMonitor.cpp b/SilKit/source/services/orchestration/SystemMonitor.cpp index e4bb3b3fa..77c41610a 100644 --- a/SilKit/source/services/orchestration/SystemMonitor.cpp +++ b/SilKit/source/services/orchestration/SystemMonitor.cpp @@ -55,7 +55,9 @@ void SystemMonitor::RemoveSystemStateHandler(HandlerId handlerId) { if (!_systemStateHandlers.Remove(handlerId)) { - _logger->Warn("RemoveSystemStateHandler failed: Unknown HandlerId."); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveSystemStateHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -86,7 +88,9 @@ void SystemMonitor::RemoveParticipantStatusHandler(HandlerId handlerId) { if (!_participantStatusHandlers.Remove(handlerId)) { - _logger->Warn("RemoveParticipantStatusHandler failed: Unknown HandlerId."); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveParticipantStatusHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -181,9 +185,10 @@ void SystemMonitor::OnParticipantDisconnected(const ParticipantConnectionInforma if (participantState == Orchestration::ParticipantState::Shutdown) { - // If current known participant state is ParticipantState::Shutdown, we do not bother changing state - Logging::Info(_logger, "Participant \'{}\' has disconnected after gracefully shutting down", - participantName); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Participant \'{}\' has disconnected after gracefully shutting down", + participantName) + .Dispatch(); } else if (participantState != ParticipantState::Invalid) { @@ -200,20 +205,24 @@ void SystemMonitor::OnParticipantDisconnected(const ParticipantConnectionInforma ReceiveMsg(nullptr, status); - Logging::Error(_logger, "Participant \'{}\' has disconnected without gracefully shutting down.", - participantName); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage("Participant \'{}\' has disconnected without gracefully shutting down.", + participantName) + .Dispatch(); } } else if (participantName == VSilKit::REGISTRY_PARTICIPANT_NAME) { - Logging::Error(_logger, - "Connection to SIL Kit Registry was lost - no new participant connections can be established."); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage("Connection to SIL Kit Registry was lost - no new participant connections can be established.") + .Dispatch(); } else { - // This disconnecting participant is not the SIL Kit Registry and has no lifecycle. - Logging::Info(_logger, "Participant \'{}\' has disconnected.", - participantConnectionInformation.participantName); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Participant \'{}\' has disconnected.", + participantConnectionInformation.participantName) + .Dispatch(); } // Erase participant from connectedParticipant map diff --git a/SilKit/source/services/orchestration/TimeConfiguration.cpp b/SilKit/source/services/orchestration/TimeConfiguration.cpp index 98acf56c3..900bd4393 100644 --- a/SilKit/source/services/orchestration/TimeConfiguration.cpp +++ b/SilKit/source/services/orchestration/TimeConfiguration.cpp @@ -69,22 +69,27 @@ void TimeConfiguration::OnReceiveNextSimStep(const std::string& participantName, auto&& itOtherNextTask = _otherNextTasks.find(participantName); if (itOtherNextTask == _otherNextTasks.end()) { - Logging::Error(_logger, "Received NextSimTask from unknown participant {}", participantName); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage("Received NextSimTask from unknown participant {}", participantName) + .Dispatch(); return; } if (nextStep.timePoint < itOtherNextTask->second.timePoint) { - Logging::Error( - _logger, - "Chonology error: Received NextSimTask from participant \'{}\' with lower timePoint {} than last " - "known timePoint {}", - participantName, nextStep.timePoint.count(), itOtherNextTask->second.timePoint.count()); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage("Chonology error: Received NextSimTask from participant \'{}\' with lower timePoint {} than last " + "known timePoint {}", + participantName, nextStep.timePoint.count(), itOtherNextTask->second.timePoint.count()) + .Dispatch(); } _otherNextTasks.at(participantName) = std::move(nextStep); - Logging::Debug(_logger, "Updated _otherNextTasks for participant {} with time {}", participantName, - nextStep.timePoint.count()); + + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("Updated _otherNextTasks for participant {} with time {}", participantName, + nextStep.timePoint.count()) + .Dispatch(); } void TimeConfiguration::SynchronizedParticipantRemoved(const std::string& otherParticipantName) @@ -134,8 +139,10 @@ bool TimeConfiguration::OtherParticipantHasLowerTimepoint() const { if (_myNextTask.timePoint > otherTask.second.timePoint) { - Debug(_logger, "Not advancing because participant \'{}\' has lower timepoint {}", otherTask.first, - otherTask.second.timePoint.count()); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("Not advancing because participant \'{}\' has lower timepoint {}", otherTask.first, + otherTask.second.timePoint.count()) + .Dispatch(); return true; } } @@ -183,8 +190,9 @@ bool TimeConfiguration::IsHopOn() if (_hoppedOn) { _myNextTask.timePoint = minimalOtherTime; - Logging::Debug(_logger, "Simulation time already advanced. Starting at {}ns", - _myNextTask.timePoint.count()); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("Simulation time already advanced. Starting at {}ns", _myNextTask.timePoint.count()) + .Dispatch(); return true; } } diff --git a/SilKit/source/services/orchestration/TimeSyncService.cpp b/SilKit/source/services/orchestration/TimeSyncService.cpp index 4fd4ce632..e2b23484b 100644 --- a/SilKit/source/services/orchestration/TimeSyncService.cpp +++ b/SilKit/source/services/orchestration/TimeSyncService.cpp @@ -314,7 +314,7 @@ TimeSyncService::TimeSyncService(Core::IParticipantInternal* participant, ITimeP _watchDog.SetWarnHandler([logger = _logger](std::chrono::milliseconds timeout) { - logger->MakeMessage(Logging::Level::Warn, Logging::Topic::TimeSyncService) + logger->MakeMessage(Logging::Level::Warn, Logging::Topic::TimeSync) .SetMessage("SimStep did not finish within soft time limit. Timeout detected after {} ms") .AddKeyValue(Logging::Keys::timeoutTime, std::chrono::duration_cast>(timeout).count()) .Dispatch(); From 651a0512ac2710b94caadc751242da5319ea7344 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Thu, 16 Apr 2026 08:49:13 +0200 Subject: [PATCH 11/23] Roll out new logger interface in network controller --- .../services/logging/LoggingDatatypes.hpp | 1 + .../silkit/services/logging/string_utils.hpp | 5 + .../internal/traits/SilKitLoggingTraits.hpp | 23 ++- SilKit/source/services/can/CanController.cpp | 53 ++++-- SilKit/source/services/can/CanController.hpp | 2 +- .../services/ethernet/EthController.cpp | 56 ++++--- .../services/ethernet/EthController.hpp | 2 +- .../services/flexray/FlexrayController.cpp | 88 ++++++---- .../services/flexray/FlexrayController.hpp | 2 +- SilKit/source/services/lin/LinController.cpp | 157 +++++++++++++----- SilKit/source/services/lin/LinController.hpp | 6 +- 11 files changed, 268 insertions(+), 127 deletions(-) diff --git a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp index 16c7ecc33..378e79d07 100644 --- a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp +++ b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp @@ -39,6 +39,7 @@ enum class Topic : uint32_t TimeConfig = 9, RequestReply = 10, SystemMonitor = 11, + Controller = 12, Invalid = 0xffffffff //!< Invalid log message topic }; diff --git a/SilKit/include/silkit/services/logging/string_utils.hpp b/SilKit/include/silkit/services/logging/string_utils.hpp index 628ffddf6..41ab6947b 100644 --- a/SilKit/include/silkit/services/logging/string_utils.hpp +++ b/SilKit/include/silkit/services/logging/string_utils.hpp @@ -133,6 +133,9 @@ std::ostream& operator<<(std::ostream& outStream, const Topic& topic) case Topic::SystemMonitor: outStream << "systemmonitor"; break; + case Topic::Controller: + outStream << "controller"; + break; case Topic::None: outStream << "none"; break; @@ -169,6 +172,8 @@ inline Topic from_topic_string(const std::string& topicStr) return Topic::RequestReply; if (topic == "systemmonitor") return Topic::SystemMonitor; + if (topic == "controller") + return Topic::Controller; return Topic::Invalid; } /* diff --git a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp index 8e09fcf7c..bfc73efa3 100644 --- a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp @@ -35,8 +35,22 @@ class Participant; namespace SilKit { namespace Services { -namespace Orchestration { +namespace Lin { +class LinController; +} +namespace Can { +class CanController; +} +namespace Ethernet { +class EthController; +} +namespace Flexray{ +class FlexrayController; +} + + +namespace Orchestration { class TimeSyncService; class TimeConfiguration; class SystemMonitor; @@ -100,15 +114,18 @@ DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::LifecycleService DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::LifecycleManagement, SilKit::Services::Logging::Topic::LifeCycle); DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::SystemMonitor, SilKit::Services::Logging::Topic::SystemState); +DefineSilKitLoggingTrait_Topic(VSilKit::SystemStateTracker, SilKit::Services::Logging::Topic::SystemState); DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioConnection, SilKit::Services::Logging::Topic::Asio); DefineSilKitLoggingTrait_Topic(SilKit::Core::VAsioRegistry, SilKit::Services::Logging::Topic::Asio); DefineSilKitLoggingTrait_Topic(SilKit::Core::ConnectKnownParticipants, SilKit::Services::Logging::Topic::Asio); DefineSilKitLoggingTrait_Topic(SilKit::Core::RemoteConnectionManager, SilKit::Services::Logging::Topic::Asio); - DefineSilKitLoggingTrait_Topic(VSilKit::ConnectPeer, SilKit::Services::Logging::Topic::Asio); -DefineSilKitLoggingTrait_Topic(VSilKit::SystemStateTracker, SilKit::Services::Logging::Topic::SystemState); +DefineSilKitLoggingTrait_Topic(SilKit::Services::Lin::LinController, SilKit::Services::Logging::Topic::Controller); +DefineSilKitLoggingTrait_Topic(SilKit::Services::Can::CanController, SilKit::Services::Logging::Topic::Controller); +DefineSilKitLoggingTrait_Topic(SilKit::Services::Ethernet::EthController, SilKit::Services::Logging::Topic::Controller); +DefineSilKitLoggingTrait_Topic(SilKit::Services::Flexray::FlexrayController, SilKit::Services::Logging::Topic::Controller); diff --git a/SilKit/source/services/can/CanController.cpp b/SilKit/source/services/can/CanController.cpp index 3ef7411bc..a4f993bd6 100755 --- a/SilKit/source/services/can/CanController.cpp +++ b/SilKit/source/services/can/CanController.cpp @@ -8,6 +8,7 @@ #include "ServiceDatatypes.hpp" #include "CanController.hpp" #include "Tracing.hpp" +#include "LoggerMessage.hpp" namespace SilKit { namespace Services { @@ -19,7 +20,7 @@ CanController::CanController(Core::IParticipantInternal* participant, SilKit::Co , _config{std::move(config)} , _simulationBehavior{participant, this, timeProvider} , _replayActive{Tracing::IsValidReplayConfig(_config.replay)} - , _logger{participant->GetLogger()} + , _logger{participant->GetLoggerInternal()} { } @@ -38,11 +39,12 @@ void CanController::RegisterServiceDiscovery() if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated && IsRelevantNetwork(remoteServiceDescriptor)) { - Logging::Info(_logger, - "Controller '{}' is using the simulated network '{}' and will route all messages to " - "the network simulator '{}'", - _config.name, remoteServiceDescriptor.GetNetworkName(), - remoteServiceDescriptor.GetParticipantName()); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Controller '{}' is using the simulated network '{}' and will route all messages to " + "the network simulator '{}'", + _config.name, remoteServiceDescriptor.GetNetworkName(), + remoteServiceDescriptor.GetParticipantName()) + .Dispatch(); SetDetailedBehavior(remoteServiceDescriptor); } } @@ -51,10 +53,11 @@ void CanController::RegisterServiceDiscovery() if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved && IsRelevantNetwork(remoteServiceDescriptor)) { - Logging::Warn(_logger, - "The network simulator for controller '{}' left the simulation. The controller is no " + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("The network simulator for controller '{}' left the simulation. The controller is no " "longer simulated.", - _config.name); + _config.name) + .Dispatch(); SetTrivialBehavior(); } } @@ -148,8 +151,12 @@ void CanController::SendFrame(const CanFrame& frame, void* userContext) { // do not allow user messages from the public API. // ReplaySend will send all frames. - Logging::Debug(_logger, _logOnce, "CanController: Ignoring SendFrame API call due to Replay config on {}", - _config.name); + if (!_logOnce.WasCalled()) + { + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("CanController: Ignoring SendFrame API call due to Replay config on {}", _config.name) + .Dispatch(); + } return; } WireCanFrameEvent wireCanFrameEvent{}; @@ -172,8 +179,12 @@ void CanController::ReceiveMsg(const IServiceEndpoint* from, const WireCanFrameE if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Receive)) { - Logging::Debug(_logger, _logOnce, "CanController: Ignoring ReceiveMsg API call due to Replay config on {}", - _config.name); + if (!_logOnce.WasCalled()) + { + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("CanController: Ignoring ReceiveMsg API call due to Replay config on {}", _config.name) + .Dispatch(); + } return; } @@ -293,7 +304,9 @@ void CanController::RemoveFrameHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveFrameHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveFrameHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -306,7 +319,9 @@ void CanController::RemoveStateChangeHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveStateChangeHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveStateChangeHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -319,7 +334,9 @@ void CanController::RemoveErrorStateChangeHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveErrorStateChangeHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveErrorStateChangeHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -335,7 +352,9 @@ void CanController::RemoveFrameTransmitHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveFrameTransmitHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveFrameTransmitHandler failed: Unknown HandlerId.") + .Dispatch(); } } diff --git a/SilKit/source/services/can/CanController.hpp b/SilKit/source/services/can/CanController.hpp index 9374d164c..b95537a7a 100644 --- a/SilKit/source/services/can/CanController.hpp +++ b/SilKit/source/services/can/CanController.hpp @@ -167,7 +167,7 @@ class CanController Core::ServiceDescriptor _serviceDescriptor; Tracer _tracer; bool _replayActive{false}; - Services::Logging::ILogger* _logger; + Services::Logging::ILoggerInternal* _logger; Services::Logging::LogOnceFlag _logOnce; CanControllerState _controllerState = CanControllerState::Uninit; diff --git a/SilKit/source/services/ethernet/EthController.cpp b/SilKit/source/services/ethernet/EthController.cpp index cc401a095..22fe67f1d 100644 --- a/SilKit/source/services/ethernet/EthController.cpp +++ b/SilKit/source/services/ethernet/EthController.cpp @@ -8,7 +8,7 @@ #include "IServiceDiscovery.hpp" #include "ServiceDatatypes.hpp" #include "Tracing.hpp" - +#include "LoggerMessage.hpp" namespace SilKit { namespace Services { @@ -21,7 +21,7 @@ EthController::EthController(Core::IParticipantInternal* participant, Config::Et , _simulationBehavior{participant, this, timeProvider} , _timeProvider{timeProvider} , _replayActive{Tracing::IsValidReplayConfig(_config.replay)} - , _logger{participant->GetLogger()} + , _logger{participant->GetLoggerInternal()} { } @@ -40,11 +40,12 @@ void EthController::RegisterServiceDiscovery() if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated && IsRelevantNetwork(remoteServiceDescriptor)) { - Logging::Info(_logger, - "Controller '{}' is using the simulated network '{}' and will route all messages to " - "the network simulator '{}'", - _config.name, remoteServiceDescriptor.GetNetworkName(), - remoteServiceDescriptor.GetParticipantName()); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Controller '{}' is using the simulated network '{}' and will route all messages to " + "the network simulator '{}'", + _config.name, remoteServiceDescriptor.GetNetworkName(), + remoteServiceDescriptor.GetParticipantName()) + .Dispatch(); SetDetailedBehavior(remoteServiceDescriptor); } } @@ -53,10 +54,11 @@ void EthController::RegisterServiceDiscovery() if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved && IsRelevantNetwork(remoteServiceDescriptor)) { - Logging::Warn(_logger, - "The network simulator for controller '{}' left the simulation. The controller is no " - "longer simulated.", - _config.name); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("The network simulator for controller '{}' left the simulation. The controller is no " + "longer simulated.", + _config.name) + .Dispatch(); SetTrivialBehavior(); } } @@ -124,8 +126,12 @@ void EthController::SendFrame(EthernetFrame frame, void* userContext) { if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Send)) { - Logging::Debug(_logger, _logOnce, "EthController: Ignoring SendFrame API call due to Replay config on {}", - _config.name); + if (!_logOnce.WasCalled()) + { + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("EthController: Ignoring SendFrame API call due to Replay config on {}", _config.name) + .Dispatch(); + } return; } return SendFrameInternal(frame, userContext); @@ -153,8 +159,12 @@ void EthController::ReceiveMsg(const IServiceEndpoint* from, const WireEthernetF } if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Receive)) { - Logging::Debug(_logger, _logOnce, "EthController: Ignoring ReceiveMsg API call due to Replay config on {}", - _config.name); + if (!_logOnce.WasCalled()) + { + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("EthController: Ignoring ReceiveMsg API call due to Replay config on {}", _config.name) + .Dispatch(); + } return; } return ReceiveMsgInternal(from, msg); @@ -295,7 +305,9 @@ void EthController::RemoveFrameHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveFrameHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveFrameHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -316,7 +328,9 @@ void EthController::RemoveFrameTransmitHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveFrameTransmitHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveFrameTransmitHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -329,7 +343,9 @@ void EthController::RemoveStateChangeHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveStateChangeHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveStateChangeHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -342,7 +358,9 @@ void EthController::RemoveBitrateChangeHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveBitrateChangeHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveBitrateChangeHandler failed: Unknown HandlerId.") + .Dispatch(); } } diff --git a/SilKit/source/services/ethernet/EthController.hpp b/SilKit/source/services/ethernet/EthController.hpp index c717aa4a1..e7960f377 100644 --- a/SilKit/source/services/ethernet/EthController.hpp +++ b/SilKit/source/services/ethernet/EthController.hpp @@ -138,7 +138,7 @@ class EthController Orchestration::ITimeProvider* _timeProvider{nullptr}; Tracer _tracer; bool _replayActive{false}; - Services::Logging::ILogger* _logger; + Services::Logging::ILoggerInternal* _logger; Services::Logging::LogOnceFlag _logOnce; template diff --git a/SilKit/source/services/flexray/FlexrayController.cpp b/SilKit/source/services/flexray/FlexrayController.cpp index 050ebc561..dbe48f532 100644 --- a/SilKit/source/services/flexray/FlexrayController.cpp +++ b/SilKit/source/services/flexray/FlexrayController.cpp @@ -17,7 +17,7 @@ FlexrayController::FlexrayController(Core::IParticipantInternal* participant, Co Services::Orchestration::ITimeProvider* /*timeProvider*/) : _participant(participant) , _config{std::move(config)} - , _logger{participant->GetLogger()} + , _logger{participant->GetLoggerInternal()} { } @@ -37,12 +37,13 @@ void FlexrayController::RegisterServiceDiscovery() if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated && IsRelevantNetwork(remoteServiceDescriptor)) { - Logging::Info(_logger, - "Controller '{}' is using the simulated network '{}' and will route all messages to " - "the network simulator '{}'", - _config.name, remoteServiceDescriptor.GetNetworkName(), - remoteServiceDescriptor.GetParticipantName()); - SetDetailedBehavior(remoteServiceDescriptor); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Controller '{}' is using the simulated network '{}' and will route all messages to " + "the network simulator '{}'", + _config.name, remoteServiceDescriptor.GetNetworkName(), + remoteServiceDescriptor.GetParticipantName()) + .Dispatch(); + SetDetailedBehavior(remoteServiceDescriptor); } } else @@ -50,10 +51,11 @@ void FlexrayController::RegisterServiceDiscovery() if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceRemoved && IsRelevantNetwork(remoteServiceDescriptor)) { - Logging::Error(_logger, - "The network simulator for controller '{}' left the simulation. FlexRay controllers " - "require a running network simulator to operate.", - _config.name); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage("The network simulator for controller '{}' left the simulation. FlexRay controllers " + "require a running network simulator to operate.", + _config.name) + .Dispatch(); } } }); @@ -105,7 +107,9 @@ void FlexrayController::WarnOverride(const std::string& parameterName) ss << "Discarded user-defined configuration of " << parameterName << ", as it was already set in the predefined configuration."; - _participant->GetLogger()->Warn(ss.str()); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(ss.str()) + .Dispatch(); } void FlexrayController::Configure(const FlexrayControllerConfig& config) @@ -138,17 +142,17 @@ void FlexrayController::ReconfigureTxBuffer(uint16_t txBufferIdx, const FlexrayT { if (txBufferIdx >= _bufferConfigs.size()) { - Logging::Error(_participant->GetLogger(), - "FlexrayController::ReconfigureTxBuffer() was called with unconfigured txBufferIdx={}", - txBufferIdx); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage("FlexrayController::ReconfigureTxBuffer() was called with unconfigured txBufferIdx={}", txBufferIdx) + .Dispatch(); throw OutOfRangeError{"Unconfigured txBufferIdx!"}; } if (!IsTxBufferConfigsConfigurable()) { - Logging::Error(_participant->GetLogger(), - "ReconfigureTxBuffer() was called on a preconfigured txBuffer. This is not " - "allowed and the reconfiguration will be discarded."); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage("ReconfigureTxBuffer() was called on a preconfigured txBuffer. This is not allowed and the reconfiguration will be discarded.") + .Dispatch(); return; } @@ -162,9 +166,9 @@ void FlexrayController::UpdateTxBuffer(const FlexrayTxBufferUpdate& update) { if (update.txBufferIndex >= _bufferConfigs.size()) { - Logging::Error(_participant->GetLogger(), - "FlexrayController::UpdateTxBuffer() was called with unconfigured txBufferIndex={}", - update.txBufferIndex); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage("FlexrayController::UpdateTxBuffer() was called with unconfigured txBufferIndex={}", update.txBufferIndex) + .Dispatch(); throw OutOfRangeError{"Unconfigured txBufferIndex!"}; } @@ -177,17 +181,15 @@ void FlexrayController::UpdateTxBuffer(const FlexrayTxBufferUpdate& update) const auto maxLength = _config.clusterParameters->gPayloadLengthStatic * 2u; //FR words to bytes if (update.payload.size() > maxLength) { - Logging::Warn(_participant->GetLogger(), - "FlexrayController::UpdateTxBuffer() was called with FlexRayTxBufferUpdate.payload size" - " exceeding 2*gPayloadLengthStatic ({}). The payload will be truncated.", - maxLength); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("FlexrayController::UpdateTxBuffer() was called with FlexRayTxBufferUpdate.payload size exceeding 2*gPayloadLengthStatic ({}). The payload will be truncated.", maxLength) + .Dispatch(); } if (update.payload.size() < maxLength) { - Logging::Warn(_participant->GetLogger(), - "FlexrayController::UpdateTxBuffer() was called with FlexRayTxBufferUpdate.payload size" - " lower than 2*gPayloadLengthStatic ({}). The payload will be zero padded.", - maxLength); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("FlexrayController::UpdateTxBuffer() was called with FlexRayTxBufferUpdate.payload size lower than 2*gPayloadLengthStatic ({}). The payload will be zero padded.", maxLength) + .Dispatch(); } } } @@ -339,7 +341,9 @@ void FlexrayController::RemoveFrameHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - Logging::Warn(_participant->GetLogger(), "RemoveFrameHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveFrameHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -352,7 +356,9 @@ void FlexrayController::RemoveFrameTransmitHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - Logging::Warn(_participant->GetLogger(), "RemoveFrameTransmitHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveFrameTransmitHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -365,7 +371,9 @@ void FlexrayController::RemoveWakeupHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - Logging::Warn(_participant->GetLogger(), "RemoveWakeupHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveWakeupHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -378,7 +386,9 @@ void FlexrayController::RemovePocStatusHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - Logging::Warn(_participant->GetLogger(), "RemovePocStatusHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemovePocStatusHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -391,7 +401,9 @@ void FlexrayController::RemoveSymbolHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - Logging::Warn(_participant->GetLogger(), "RemoveSymbolHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveSymbolHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -404,7 +416,9 @@ void FlexrayController::RemoveSymbolTransmitHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - Logging::Warn(_participant->GetLogger(), "RemoveSymbolTransmitHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveSymbolTransmitHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -417,7 +431,9 @@ void FlexrayController::RemoveCycleStartHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - Logging::Warn(_participant->GetLogger(), "RemoveCycleStartHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveCycleStartHandler failed: Unknown HandlerId.") + .Dispatch(); } } diff --git a/SilKit/source/services/flexray/FlexrayController.hpp b/SilKit/source/services/flexray/FlexrayController.hpp index 9bc24e24b..f5b8ff381 100644 --- a/SilKit/source/services/flexray/FlexrayController.hpp +++ b/SilKit/source/services/flexray/FlexrayController.hpp @@ -152,7 +152,7 @@ class FlexrayController ::SilKit::Core::ServiceDescriptor _serviceDescriptor; std::vector _bufferConfigs; Tracer _tracer; - Services::Logging::ILogger* _logger; + Services::Logging::ILoggerInternal* _logger; bool _simulatedLinkDetected = false; Core::ServiceDescriptor _simulatedLink; diff --git a/SilKit/source/services/lin/LinController.cpp b/SilKit/source/services/lin/LinController.cpp index 67c980962..e90e61d25 100644 --- a/SilKit/source/services/lin/LinController.cpp +++ b/SilKit/source/services/lin/LinController.cpp @@ -46,7 +46,7 @@ LinController::LinController(Core::IParticipantInternal* participant, SilKit::Co Services::Orchestration::ITimeProvider* timeProvider) : _participant{participant} , _config{config} - , _logger{participant->GetLogger()} + , _logger{participant->GetLoggerInternal()} , _simulationBehavior{participant, this, timeProvider} , _timeProvider{timeProvider} , _replayActive{Tracing::IsValidReplayConfig(_config.replay)} @@ -69,11 +69,9 @@ void LinController::RegisterServiceDiscovery() if (discoveryType == Core::Discovery::ServiceDiscoveryEvent::Type::ServiceCreated && IsRelevantNetwork(remoteServiceDescriptor)) { - Logging::Info(_logger, - "Controller '{}' is using the simulated network '{}' and will route all messages to " - "the network simulator '{}'", - _config.name, remoteServiceDescriptor.GetNetworkName(), - remoteServiceDescriptor.GetParticipantName()); + _logger->MakeMessage(Logging::Level::Info, *this) + .SetMessage("Controller using simulated network") + .Dispatch(); SetDetailedBehavior(remoteServiceDescriptor); } } @@ -83,10 +81,9 @@ void LinController::RegisterServiceDiscovery() && IsRelevantNetwork(remoteServiceDescriptor)) { - Logging::Warn(_logger, - "The network simulator for controller '{}' left the simulation. The controller is no " - "longer simulated.", - _config.name); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("The network simulator left the simulation") + .Dispatch(); SetTrivialBehavior(); } } @@ -131,7 +128,9 @@ void LinController::ThrowIfUninitialized(const std::string& callingMethodName) c std::string errorMsg = callingMethodName + " must only be called when the controller is initialized! Check " "whether a call to LinController::Init is missing."; - _logger->Error(errorMsg); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage(errorMsg) + .Dispatch(); throw SilKit::StateError{errorMsg}; } } @@ -141,7 +140,9 @@ void LinController::ThrowIfNotMaster(const std::string& callingMethodName) const if (_controllerMode != LinControllerMode::Master) { std::string errorMsg = callingMethodName + " must only be called in master mode!"; - _logger->Error(errorMsg); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage(errorMsg) + .Dispatch(); throw SilKitError{errorMsg}; } } @@ -151,7 +152,9 @@ void LinController::ThrowIfDynamic(const std::string& callingMethodName) const if (_useDynamicResponse) { std::string errorMsg = callingMethodName + " can not be called if the node was initialized using InitDynamic!"; - _logger->Error(errorMsg); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage(errorMsg) + .Dispatch(); throw SilKitError{errorMsg}; } } @@ -161,7 +164,9 @@ void LinController::ThrowIfNotDynamic(const std::string& callingMethodName) cons if (_useDynamicResponse) { std::string errorMsg = callingMethodName + " can only be called if the node was initialized using InitDynamic!"; - _logger->Error(errorMsg); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage(errorMsg) + .Dispatch(); throw SilKitError{errorMsg}; } } @@ -173,7 +178,9 @@ void LinController::ThrowIfNotConfiguredTxUnconditional(LinId linId) std::string errorMsg = fmt::format("This node must be configured with LinFrameResponseMode::TxUnconditional to " "update the TxBuffer for ID {}", static_cast(linId)); - _logger->Error(errorMsg); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage(errorMsg) + .Dispatch(); throw SilKit::ConfigurationError{errorMsg}; } } @@ -183,7 +190,9 @@ void LinController::WarnOnWrongDataLength(const LinFrame& receivedFrame, const L std::string errorMsg = fmt::format("Mismatch between configured ({}) and received ({}) LinDataLength in LinFrame with ID {}", configuredFrame.dataLength, receivedFrame.dataLength, static_cast(receivedFrame.id)); - _logger->Warn(errorMsg); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(errorMsg) + .Dispatch(); } void LinController::WarnOnWrongChecksum(const LinFrame& receivedFrame, const LinFrame& configuredFrame) const @@ -191,7 +200,9 @@ void LinController::WarnOnWrongChecksum(const LinFrame& receivedFrame, const Lin std::string errorMsg = fmt::format( "Mismatch between configured ({}) and received ({}) LinChecksumModel in LinFrame with ID {}", configuredFrame.checksumModel, receivedFrame.checksumModel, static_cast(receivedFrame.id)); - _logger->Warn(errorMsg); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(errorMsg) + .Dispatch(); } void LinController::WarnOnReceptionWithInvalidDataLength(LinDataLength invalidDataLength, @@ -202,7 +213,9 @@ void LinController::WarnOnReceptionWithInvalidDataLength(LinDataLength invalidDa fmt::format("LinController received transmission with invalid payload length {} from {{{}, {}}}. This " "tranmission is ignored.", static_cast(invalidDataLength), fromParticipantName, fromServiceName); - _logger->Warn(errorMsg); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(errorMsg) + .Dispatch(); } void LinController::WarnOnReceptionWithInvalidLinId(LinId invalidLinId, const std::string& fromParticipantName, @@ -211,41 +224,53 @@ void LinController::WarnOnReceptionWithInvalidLinId(LinId invalidLinId, const st std::string errorMsg = fmt::format( "LinController received transmission with invalid LIN ID {} from {{{}, {}}}. This transmission is ignored.", static_cast(invalidLinId), fromParticipantName, fromServiceName); - _logger->Warn(errorMsg); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(errorMsg) + .Dispatch(); } void LinController::WarnOnReceptionWhileInactive() const { std::string errorMsg = fmt::format("Inactive LinController received a transmission. This transmission is ignored."); - _logger->Warn(errorMsg); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(errorMsg) + .Dispatch(); } void LinController::WarnOnUnneededStatusChange(LinControllerStatus status) const { std::string errorMsg = fmt::format("Invalid LinController status change: controller is already in {} mode.", status); - _logger->Warn(errorMsg); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(errorMsg) + .Dispatch(); } void LinController::WarnOnInvalidLinId(LinId invalidLinId, const std::string& callingMethodName) const { std::string errorMsg = fmt::format("Invalid ID={} in call to '{}'", static_cast(invalidLinId), callingMethodName); - _logger->Warn(errorMsg); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(errorMsg) + .Dispatch(); } void LinController::WarnOnUnusedResponseMode(const std::string& callingMethodName) const { std::string errorMsg = fmt::format("LinFrameResponseMode::Unused is not allowed in call to '{}'.", callingMethodName); - _logger->Warn(errorMsg); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(errorMsg) + .Dispatch(); } void LinController::WarnOnResponseModeReconfiguration(LinId id, LinFrameResponseMode currentResponseMode) const { std::string errorMsg = fmt::format("Can't set response mode for ID={}. Mode is already configured to {}.", id, currentResponseMode); - _logger->Warn(errorMsg); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(errorMsg) + .Dispatch(); } @@ -254,21 +279,27 @@ void LinController::WarnOnUnconfiguredSlaveResponse(LinId id) const std::string errorMsg = fmt::format("No slave has configured a response for ID={}. Use Init() or SetFrameResponse() " "on the slave node to configure responses.", id); - _logger->Warn(errorMsg); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(errorMsg) + .Dispatch(); } void LinController::WarnOnSendFrameSlaveResponseWithMasterTx(LinId id) const { std::string errorMsg = fmt::format("Master has already configured a response on ID={}. Ignoring this call to SendFrame()", id); - _logger->Warn(errorMsg); + _logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage(errorMsg) + .Dispatch(); } void LinController::ThrowOnSendAttemptWithUndefinedChecksum(const LinFrame& frame) const { std::string errorMsg = fmt::format("LinFrame with ID {} has an undefined checksum model.", static_cast(frame.id)); - _logger->Error(errorMsg); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage(errorMsg) + .Dispatch(); throw SilKit::StateError{errorMsg}; } @@ -276,21 +307,27 @@ void LinController::ThrowOnSendAttemptWithUndefinedDataLength(const LinFrame& fr { std::string errorMsg = fmt::format("LinFrame with ID {} has an undefined data length.", static_cast(frame.id)); - _logger->Error(errorMsg); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage(errorMsg) + .Dispatch(); throw SilKit::StateError{errorMsg}; } void LinController::ThrowOnErroneousInitialization() const { std::string errorMsg{"A LinController can't be initialized with LinControllerMode::Inactive!"}; - _logger->Error(errorMsg); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage(errorMsg) + .Dispatch(); throw SilKit::StateError{errorMsg}; } void LinController::ThrowOnDuplicateInitialization() const { std::string errorMsg{"LinController::Init() must only be called once!"}; - _logger->Error(errorMsg); + _logger->MakeMessage(Logging::Level::Error, *this) + .SetMessage(errorMsg) + .Dispatch(); throw SilKit::StateError{errorMsg}; } @@ -436,8 +473,12 @@ void LinController::SendFrame(LinFrame frame, LinFrameResponseType responseType) if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Send)) { - Logging::Debug(_logger, _logOnce, "LinController: Ignoring SendFrame API call due to Replay config on {}", - _config.name); + if (!_logOnce.WasCalled()) + { + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("LinController: Ignoring SendFrame API call due to Replay config on {}", _config.name) + .Dispatch(); + } return; } @@ -495,8 +536,12 @@ void LinController::SetFrameResponse(LinFrameResponse response) if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Send)) { - Logging::Debug(_logger, _logOnce, - "LinController: Ignoring SetFrameResponse API call due to Replay config on {}", _config.name); + if (!_logOnce.WasCalled()) + { + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("LinController: Ignoring SetFrameResponse API call due to Replay config on {}", _config.name) + .Dispatch(); + } return; } @@ -521,8 +566,12 @@ void LinController::GoToSleep() if (Tracing::IsReplayEnabledFor(_config.replay, Config::Replay::Direction::Send)) { - Logging::Debug(_logger, _logOnce, "LinController: Ignoring GoToSleep API call due to Replay config on {}", - _config.name); + if (!_logOnce.WasCalled()) + { + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("LinController: Ignoring GoToSleep API call due to Replay config on {}", _config.name) + .Dispatch(); + } return; } @@ -642,14 +691,16 @@ void LinController::HandleResponsesUpdate(const IServiceEndpoint* from, //------------------------ void LinController::LinNode::UpdateResponses(std::vector responsesToUpdate, - Services::Logging::ILogger* logger) + Services::Logging::ILoggerInternal* logger) { for (auto&& response : responsesToUpdate) { auto linId = response.frame.id; if (linId >= responses.size()) { - Logging::Warn(logger, "Ignoring LinFrameResponse update for invalid ID={}", static_cast(linId)); + logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("Ignoring LinFrameResponse update for invalid ID={}", static_cast(linId)) + .Dispatch(); continue; } responses[linId] = std::move(response); @@ -657,11 +708,13 @@ void LinController::LinNode::UpdateResponses(std::vector respo } void LinController::LinNode::UpdateTxBuffer(LinId linId, std::array data, - Services::Logging::ILogger* logger) + Services::Logging::ILoggerInternal* logger) { if (linId >= responses.size()) { - Logging::Warn(logger, "Ignoring LinFrameResponse update for invalid ID={}", static_cast(linId)); + logger->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("Ignoring LinFrameResponse update for invalid ID={}", static_cast(linId)) + .Dispatch(); return; } responses[linId].frame.data = data; @@ -849,7 +902,9 @@ void LinController::RemoveFrameStatusHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveFrameStatusHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveFrameStatusHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -862,7 +917,9 @@ void LinController::RemoveGoToSleepHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveGoToSleepHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveGoToSleepHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -881,7 +938,9 @@ void LinController::RemoveWakeupHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveWakeupHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveWakeupHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -889,7 +948,9 @@ void LinController::RemoveFrameHeaderHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveFrameHeaderHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveFrameHeaderHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -913,7 +974,9 @@ void LinController::RemoveLinSlaveConfigurationHandler(HandlerId handlerId) { if (!RemoveHandler(handlerId)) { - _participant->GetLogger()->Warn("RemoveLinSlaveConfigurationHandler failed: Unknown HandlerId."); + _participant->GetLoggerInternal()->MakeMessage(Logging::Level::Warn, *this) + .SetMessage("RemoveLinSlaveConfigurationHandler failed: Unknown HandlerId.") + .Dispatch(); } } @@ -950,7 +1013,9 @@ void LinController::ReplayMessage(const IReplayMessage* replayMessage) if (_controllerMode != LinControllerMode::Master) { - Logging::Debug(_logger, "ReplayMessage: skipping, because controller mode is {}", _controllerMode); + _logger->MakeMessage(Logging::Level::Debug, *this) + .SetMessage("ReplayMessage: skipping, because controller mode is {}", _controllerMode) + .Dispatch(); return; } // The LinFrame Response Updates ensures that all controllers have the same notion of the diff --git a/SilKit/source/services/lin/LinController.hpp b/SilKit/source/services/lin/LinController.hpp index 5313c2534..8e3ab88f7 100644 --- a/SilKit/source/services/lin/LinController.hpp +++ b/SilKit/source/services/lin/LinController.hpp @@ -129,8 +129,8 @@ class LinController WireLinControllerConfig::SimulationMode simulationMode{WireLinControllerConfig::SimulationMode::Default}; std::array responses; - void UpdateResponses(std::vector responsesToUpdate, Services::Logging::ILogger* logger); - void UpdateTxBuffer(LinId linId, std::array data, Services::Logging::ILogger* logger); + void UpdateResponses(std::vector responsesToUpdate, Services::Logging::ILoggerInternal* logger); + void UpdateTxBuffer(LinId linId, std::array data, Services::Logging::ILoggerInternal* logger); }; auto GetResponse(LinId id) -> std::pair; auto GetThisLinNode() -> LinNode&; @@ -209,7 +209,7 @@ class LinController Logging::LogOnceFlag _logOnce; Core::IParticipantInternal* _participant; Config::LinController _config; - Services::Logging::ILogger* _logger; + Services::Logging::ILoggerInternal* _logger; Tracer _tracer; SimBehavior _simulationBehavior; ::SilKit::Core::ServiceDescriptor _serviceDescriptor; From dfaadd8e51db822fc4a968390f1df6f45b9dc9b2 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Thu, 16 Apr 2026 09:32:50 +0200 Subject: [PATCH 12/23] Roll out new logger interface in tracing component --- .../services/logging/LoggingDatatypes.hpp | 1 + .../silkit/services/logging/string_utils.hpp | 5 ++ .../core/participant/Participant_impl.hpp | 2 +- .../SilKitExtensionImpl/CreateMdf4Tracing.cpp | 4 +- .../SilKitExtensionImpl/CreateMdf4Tracing.hpp | 6 +- SilKit/source/tracing/IReplay.hpp | 8 ++- SilKit/source/tracing/PcapReader.cpp | 22 ++++--- SilKit/source/tracing/PcapReader.hpp | 7 ++- SilKit/source/tracing/PcapReplay.cpp | 6 +- SilKit/source/tracing/PcapReplay.hpp | 4 +- SilKit/source/tracing/PcapSink.cpp | 15 +++-- SilKit/source/tracing/PcapSink.hpp | 5 +- SilKit/source/tracing/ReplayScheduler.cpp | 61 +++++++++++++------ SilKit/source/tracing/ReplayScheduler.hpp | 3 +- SilKit/source/tracing/Tracing.cpp | 14 ++--- SilKit/source/tracing/Tracing.hpp | 5 +- 16 files changed, 110 insertions(+), 58 deletions(-) diff --git a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp index 378e79d07..94b0f6c63 100644 --- a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp +++ b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp @@ -40,6 +40,7 @@ enum class Topic : uint32_t RequestReply = 10, SystemMonitor = 11, Controller = 12, + Tracing = 13, Invalid = 0xffffffff //!< Invalid log message topic }; diff --git a/SilKit/include/silkit/services/logging/string_utils.hpp b/SilKit/include/silkit/services/logging/string_utils.hpp index 41ab6947b..3a2478a50 100644 --- a/SilKit/include/silkit/services/logging/string_utils.hpp +++ b/SilKit/include/silkit/services/logging/string_utils.hpp @@ -136,6 +136,9 @@ std::ostream& operator<<(std::ostream& outStream, const Topic& topic) case Topic::Controller: outStream << "controller"; break; + case Topic::Tracing: + outStream << "tracing"; + break; case Topic::None: outStream << "none"; break; @@ -174,6 +177,8 @@ inline Topic from_topic_string(const std::string& topicStr) return Topic::SystemMonitor; if (topic == "controller") return Topic::Controller; + if (topic == "tracing") + return Topic::Tracing; return Topic::Invalid; } /* diff --git a/SilKit/source/core/participant/Participant_impl.hpp b/SilKit/source/core/participant/Participant_impl.hpp index c04707a1b..3a3ace927 100644 --- a/SilKit/source/core/participant/Participant_impl.hpp +++ b/SilKit/source/core/participant/Participant_impl.hpp @@ -133,7 +133,7 @@ void Participant::OnSilKitSimulationJoined() (void)GetRequestReplyService(); // Create the participants trace message sinks as declared in the configuration. - _traceSinks = Tracing::CreateTraceMessageSinks(GetLogger(), _participantConfig); + _traceSinks = Tracing::CreateTraceMessageSinks(GetLoggerInternal(), _participantConfig); // NB: Create the lifecycleService and timeSyncService (void)GetLifecycleService(); diff --git a/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.cpp b/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.cpp index 56d73a573..6e6c7bf51 100644 --- a/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.cpp +++ b/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.cpp @@ -19,7 +19,7 @@ namespace SilKit { -auto CreateMdf4Tracing(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILogger* logger, +auto CreateMdf4Tracing(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILoggerInternal* logger, const std::string& participantName, const std::string& sinkName) -> std::unique_ptr { @@ -27,7 +27,7 @@ auto CreateMdf4Tracing(Config::ParticipantConfiguration config, SilKit::Services return factory.Create(std::move(config), logger, participantName, sinkName); } -auto CreateMdf4Replay(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILogger* logger, +auto CreateMdf4Replay(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILoggerInternal* logger, const std::string& fileName) -> std::shared_ptr { auto& factory = SilKitExtensionLoader(logger, "SilKitExtension_Mdf", config.extensions); diff --git a/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.hpp b/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.hpp index d1a071729..59eab4a59 100644 --- a/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.hpp +++ b/SilKit/source/extensions/SilKitExtensionImpl/CreateMdf4Tracing.hpp @@ -6,7 +6,7 @@ #include -#include "silkit/services/logging/ILogger.hpp" +#include "ILoggerInternal.hpp" #include "ITraceMessageSink.hpp" #include "IReplay.hpp" @@ -15,7 +15,7 @@ namespace SilKit { -auto CreateMdf4Tracing(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILogger* logger, +auto CreateMdf4Tracing(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILoggerInternal* logger, const std::string& participantName, const std::string& sinkName) -> std::unique_ptr; @@ -23,7 +23,7 @@ auto CreateMdf4Tracing(Config::ParticipantConfiguration config, SilKit::Services // MDF4 Replay ////////////////////////////////////////////////////////////////////// -auto CreateMdf4Replay(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILogger* logger, +auto CreateMdf4Replay(Config::ParticipantConfiguration config, SilKit::Services::Logging::ILoggerInternal* logger, const std::string& fileName) -> std::shared_ptr; diff --git a/SilKit/source/tracing/IReplay.hpp b/SilKit/source/tracing/IReplay.hpp index fc65182ab..40c37aaad 100644 --- a/SilKit/source/tracing/IReplay.hpp +++ b/SilKit/source/tracing/IReplay.hpp @@ -21,6 +21,12 @@ namespace SilKit { +namespace Services { +namespace Logging { +struct ILoggerInternal; +} // namespace Logging +} // namespace Services + //forwards class IReplayMessage; class IReplayChannel; @@ -34,7 +40,7 @@ class IReplayDataProvider //!< Pass the config (containing search path hints), the actual file to open // and a logger to the extension. virtual auto OpenFile(const SilKit::Config::ParticipantConfiguration& config, const std::string& filePath, - SilKit::Services::Logging::ILogger* logger) -> std::shared_ptr = 0; + SilKit::Services::Logging::ILoggerInternal* logger) -> std::shared_ptr = 0; }; class IReplayFile diff --git a/SilKit/source/tracing/PcapReader.cpp b/SilKit/source/tracing/PcapReader.cpp index e602aed15..b02eb4190 100755 --- a/SilKit/source/tracing/PcapReader.cpp +++ b/SilKit/source/tracing/PcapReader.cpp @@ -9,6 +9,7 @@ #include "WireEthernetMessages.hpp" #include "Pcap.hpp" #include "Assert.hpp" +#include "LoggerMessage.hpp" namespace SilKit { namespace Tracing { @@ -71,13 +72,13 @@ auto PcapMessage::Type() const -> TraceMessageType // PcapReader ////////////////////////////////////////////////////////////////////// -PcapReader::PcapReader(std::istream* stream, SilKit::Services::Logging::ILogger* logger) +PcapReader::PcapReader(std::istream* stream, SilKit::Services::Logging::ILoggerInternal* logger) : _stream{stream} , _log{logger} { Reset(); } -PcapReader::PcapReader(const std::string& filePath, ILogger* logger) +PcapReader::PcapReader(const std::string& filePath, ILoggerInternal* logger) : _filePath{filePath} , _log{logger} { @@ -101,7 +102,9 @@ void PcapReader::Reset() { if (_filePath.empty() && _stream == nullptr) { - _log->Error("PcapReader::Reset(): no input file or stream pointer given!"); + _log->MakeMessage(Level::Error, Topic::Tracing) + .SetMessage("PcapReader::Reset(): no input file or stream pointer given!") + .Dispatch(); throw SilKitError("PcapReader::Reset(): no input file or stream pointer given!"); } @@ -114,7 +117,9 @@ void PcapReader::Reset() } if (!_file.good()) { - _log->Error("Cannot open file " + _filePath); + _log->MakeMessage(Level::Error, Topic::Tracing) + .SetMessage("Cannot open file {}", _filePath) + .Dispatch(); throw SilKitError("Cannot open file " + _filePath); } } @@ -175,7 +180,9 @@ bool PcapReader::Seek(size_t messageNumber) _stream->read(buf.data(), buf.size()); if (!_stream->good()) { - _log->Warn("PCAP file: " + _filePath + ": short read on packet header."); + _log->MakeMessage(Level::Warn, Topic::Tracing) + .SetMessage("PCAP file: {}: short read on packet header.", _filePath) + .Dispatch(); return false; } auto msg = std::make_shared(); @@ -187,8 +194,9 @@ bool PcapReader::Seek(size_t messageNumber) _stream->read(reinterpret_cast(msgBuf.data()), hdr->incl_len); if (!_stream->good()) { - _log->Warn("PCAP file: " + _filePath + ": Cannot read packet at offset " - + std::to_string(_stream->tellg())); + _log->MakeMessage(Level::Warn, Topic::Tracing) + .SetMessage("PCAP file: {}: Cannot read packet at offset {}", _filePath, std::to_string(_stream->tellg())) + .Dispatch(); return false; } msg->raw = std::move(msgBuf); diff --git a/SilKit/source/tracing/PcapReader.hpp b/SilKit/source/tracing/PcapReader.hpp index c55b0a701..eed1d4451 100755 --- a/SilKit/source/tracing/PcapReader.hpp +++ b/SilKit/source/tracing/PcapReader.hpp @@ -8,6 +8,7 @@ #include #include "IReplay.hpp" +#include "ILoggerInternal.hpp" namespace SilKit { namespace Tracing { @@ -16,9 +17,9 @@ class PcapReader final : public SilKit::IReplayChannelReader { public: // Constructors - PcapReader(const std::string& filePath, SilKit::Services::Logging::ILogger* logger); + PcapReader(const std::string& filePath, SilKit::Services::Logging::ILoggerInternal* logger); //This CTor is for testing purposes only: - PcapReader(std::istream* stream, SilKit::Services::Logging::ILogger* logger); + PcapReader(std::istream* stream, SilKit::Services::Logging::ILoggerInternal* logger); PcapReader(PcapReader& other); public: @@ -45,7 +46,7 @@ class PcapReader final : public SilKit::IReplayChannelReader std::map _metaInfos; std::shared_ptr _currentMessage; uint64_t _numMessages{0}; - SilKit::Services::Logging::ILogger* _log{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _log{nullptr}; std::chrono::nanoseconds _startTime{0}; std::chrono::nanoseconds _endTime{0}; }; diff --git a/SilKit/source/tracing/PcapReplay.cpp b/SilKit/source/tracing/PcapReplay.cpp index 6a0f9d551..6c65dc0d2 100644 --- a/SilKit/source/tracing/PcapReplay.cpp +++ b/SilKit/source/tracing/PcapReplay.cpp @@ -24,7 +24,7 @@ using namespace SilKit::Tracing; class ReplayPcapChannel : public SilKit::IReplayChannel { public: - ReplayPcapChannel(const std::string& filePath, ILogger* logger) + ReplayPcapChannel(const std::string& filePath, ILoggerInternal* logger) : _reader{filePath, logger} { } @@ -72,7 +72,7 @@ class ReplayPcapChannel : public SilKit::IReplayChannel class ReplayPcapFile : public SilKit::IReplayFile { public: - ReplayPcapFile(std::string filePath, SilKit::Services::Logging::ILogger* logger) + ReplayPcapFile(std::string filePath, SilKit::Services::Logging::ILoggerInternal* logger) : _filePath{std::move(filePath)} { auto channel = std::make_shared(_filePath, logger); @@ -113,7 +113,7 @@ namespace SilKit { namespace Tracing { auto PcapReplay::OpenFile(const SilKit::Config::ParticipantConfiguration&, const std::string& filePath, - SilKit::Services::Logging::ILogger* logger) -> std::shared_ptr + SilKit::Services::Logging::ILoggerInternal* logger) -> std::shared_ptr { return std::make_shared(filePath, logger); } diff --git a/SilKit/source/tracing/PcapReplay.hpp b/SilKit/source/tracing/PcapReplay.hpp index 7216a7aae..2ba566b14 100644 --- a/SilKit/source/tracing/PcapReplay.hpp +++ b/SilKit/source/tracing/PcapReplay.hpp @@ -6,7 +6,7 @@ #include -#include "silkit/services/logging/ILogger.hpp" +#include "ILoggerInternal.hpp" #include "IReplay.hpp" namespace SilKit { @@ -16,7 +16,7 @@ class PcapReplay : public IReplayDataProvider { public: auto OpenFile(const SilKit::Config::ParticipantConfiguration&, const std::string& filePath, - SilKit::Services::Logging::ILogger* logger) -> std::shared_ptr override; + SilKit::Services::Logging::ILoggerInternal* logger) -> std::shared_ptr override; }; } // namespace Tracing diff --git a/SilKit/source/tracing/PcapSink.cpp b/SilKit/source/tracing/PcapSink.cpp index 345bab9c7..149aad485 100644 --- a/SilKit/source/tracing/PcapSink.cpp +++ b/SilKit/source/tracing/PcapSink.cpp @@ -25,7 +25,7 @@ namespace { constexpr Pcap::GlobalHeader g_pcapGlobalHeader{}; } // namespace -PcapSink::PcapSink(Services::Logging::ILogger* logger, std::string name) +PcapSink::PcapSink(Services::Logging::ILoggerInternal* logger, std::string name) : _name{std::move(name)} , _logger{logger} { @@ -85,7 +85,9 @@ void PcapSink::Close() } catch (const SilKitError& err) { - Services::Logging::Warn(_logger, "Failed to close PCAP sink: {}", err.what()); + _logger->MakeMessage(Level::Warn, Topic::Tracing) + .SetMessage("Failed to close PCAP sink: {}", err.what()) + .Dispatch(); } _pipe.reset(); } @@ -126,11 +128,14 @@ void PcapSink::Trace(SilKit::Services::TransmitDirection /*unused*/, { if (!_headerWritten) { - Services::Logging::Info(_logger, "Sink {}: Waiting for a reader to connect to PCAP pipe {} ... ", _name, - _outputPath); + _logger->MakeMessage(Level::Info, Topic::Tracing) + .SetMessage("Sink {}: Waiting for a reader to connect to PCAP pipe {} ... ", _name, _outputPath) + .Dispatch(); ok &= _pipe->Write(reinterpret_cast(&g_pcapGlobalHeader), sizeof(g_pcapGlobalHeader)); - Services::Logging::Debug(_logger, "Sink {}: PCAP pipe: {} is connected successfully", _name, _outputPath); + _logger->MakeMessage(Level::Debug, Topic::Tracing) + .SetMessage("Sink {}: PCAP pipe: {} is connected successfully", _name, _outputPath) + .Dispatch(); _headerWritten = true; } diff --git a/SilKit/source/tracing/PcapSink.hpp b/SilKit/source/tracing/PcapSink.hpp index d4166be59..04f5a1aae 100755 --- a/SilKit/source/tracing/PcapSink.hpp +++ b/SilKit/source/tracing/PcapSink.hpp @@ -12,6 +12,7 @@ #include "EndpointAddress.hpp" #include "detail/NamedPipe.hpp" +#include "ILoggerInternal.hpp" namespace SilKit { namespace Tracing { @@ -23,7 +24,7 @@ class PcapSink : public ITraceMessageSink // Constructors and Destructor PcapSink() = delete; PcapSink(const PcapSink&) = delete; - PcapSink(Services::Logging::ILogger* logger, std::string name); + PcapSink(Services::Logging::ILoggerInternal* logger, std::string name); ~PcapSink() = default; // ---------------------------------------- @@ -49,7 +50,7 @@ class PcapSink : public ITraceMessageSink std::string _name; std::string _busName; std::string _outputPath; - Services::Logging::ILogger* _logger{nullptr}; + Services::Logging::ILoggerInternal* _logger{nullptr}; }; } // namespace Tracing diff --git a/SilKit/source/tracing/ReplayScheduler.cpp b/SilKit/source/tracing/ReplayScheduler.cpp index 542622636..24f48fb35 100644 --- a/SilKit/source/tracing/ReplayScheduler.cpp +++ b/SilKit/source/tracing/ReplayScheduler.cpp @@ -16,7 +16,7 @@ #include "IReplayDataController.hpp" #include "Tracing.hpp" #include "Assert.hpp" -#include "Logger.hpp" +#include "LoggerMessage.hpp" #include "string_utils.hpp" using namespace std::literals::chrono_literals; @@ -26,6 +26,8 @@ namespace Tracing { namespace { +using namespace SilKit::Services::Logging; + TraceMessageType ToTraceMessageType(Config::NetworkType networkType) { switch (networkType) @@ -221,7 +223,7 @@ std::string to_string(const Config::MdfChannel& mdf) } // Find the MDF channels associated with the given participant/controller names and types or an MdfChannel identification. -auto FindReplayChannel(SilKit::Services::Logging::ILogger* log, IReplayFile* replayFile, +auto FindReplayChannel(SilKit::Services::Logging::ILoggerInternal* log, IReplayFile* replayFile, const Config::Replay& replayConfig, const std::string& controllerName, const std::string& participantName, const std::string& networkName, const Config::NetworkType networkType) -> std::shared_ptr @@ -234,8 +236,10 @@ auto FindReplayChannel(SilKit::Services::Logging::ILogger* log, IReplayFile* rep if (replayFile->Type() == IReplayFile::FileType::PcapFile && channel->Type() == type) { // PCAP only has a single replay channel - Services::Logging::Info(log, "Replay: using channel '{}' from '{}' on {}", channel->Name(), - replayFile->FilePath(), controllerName); + log->MakeMessage(Level::Info, Topic::Tracing) + .SetMessage("Replay: using channel '{}' from '{}' on {}", channel->Name(), + replayFile->FilePath(), controllerName) + .Dispatch(); return channel; } @@ -252,14 +256,18 @@ auto FindReplayChannel(SilKit::Services::Logging::ILogger* log, IReplayFile* rep // SIL Kit builtin channel lookup if (channel->Type() != type) { - Services::Logging::Trace(log, "Replay: skipping channel '{}' of type {}", channel->Name(), - to_string(channel->Type())); + log->MakeMessage(Level::Trace, Topic::Tracing) + .SetMessage("Replay: skipping channel '{}' of type {}", channel->Name(), + to_string(channel->Type())) + .Dispatch(); continue; } if (MatchSilKitChannel(channel, networkName, participantName, controllerName)) { - Services::Logging::Debug(log, "Replay: found channel '{}' from file '{}' for type {}", channel->Name(), - replayFile->FilePath(), to_string(channel->Type())); + log->MakeMessage(Level::Debug, Topic::Tracing) + .SetMessage("Replay: found channel '{}' from file '{}' for type {}", channel->Name(), + replayFile->FilePath(), to_string(channel->Type())) + .Dispatch(); channelList.emplace_back(std::move(channel)); } } @@ -288,7 +296,7 @@ ReplayScheduler::ReplayScheduler(const Config::ParticipantConfiguration& partici Core::IParticipantInternal* participant) : _participant{participant} { - _log = _participant->GetLogger(); + _log = _participant->GetLoggerInternal(); CreateReplayFiles(participantConfiguration); } @@ -308,6 +316,8 @@ void ReplayScheduler::ConfigureController(const std::string& controllerName, IRe const Config::Replay& replayConfig, const std::string& networkName, const Config::NetworkType networkType) { + using namespace Services::Logging; + try { ReplayTask task{}; @@ -316,10 +326,10 @@ void ReplayScheduler::ConfigureController(const std::string& controllerName, IRe // controller has replaying active. if (!IsValidReplayConfig(replayConfig)) { - Services::Logging::Debug(_log, - "ReplayScheduler::ConfigureController: skipping controller {} because it has no " - "active Replay!", - controllerName); + _log->MakeMessage(Level::Debug, Topic::Tracing) + .SetMessage("ReplayScheduler::ConfigureController: skipping controller {} because it has no " + "active Replay!", controllerName) + .Dispatch(); return; } @@ -334,7 +344,9 @@ void ReplayScheduler::ConfigureController(const std::string& controllerName, IRe if (!replayChannel) { - Services::Logging::Warn(_log, "{}: could not find a replay channel!", controllerName); + _log->MakeMessage(Level::Warn, Topic::Tracing) + .SetMessage("{}: could not find a replay channel!", controllerName) + .Dispatch(); throw SilKitError("Could not find a replay channel"); } @@ -347,22 +359,30 @@ void ReplayScheduler::ConfigureController(const std::string& controllerName, IRe } catch (const SilKit::ConfigurationError& ex) { - _log->Error("ReplayScheduler: misconfiguration of controller " + controllerName + ": " + ex.what()); + _log->MakeMessage(Level::Error, Topic::Tracing) + .SetMessage("ReplayScheduler: misconfiguration of controller {}: {}", controllerName, ex.what()) + .Dispatch(); throw; } catch (const SilKitError& ex) { - _log->Warn("ReplayScheduler: Could not configure controller " + controllerName + ": " + ex.what()); + _log->MakeMessage(Level::Warn, Topic::Tracing) + .SetMessage("ReplayScheduler: Could not configure controller {}: {}", controllerName, ex.what()) + .Dispatch(); } } void ReplayScheduler::CreateReplayFiles(const Config::ParticipantConfiguration& participantConfiguration) { + using namespace Services::Logging; + // create trace sources (aka IReplayFile) _replayFiles = Tracing::CreateReplayFiles(_log, participantConfiguration); if (_replayFiles.empty()) { - _log->Error("ReplayScheduler: cannot open replay files."); + _log->MakeMessage(Level::Error, Topic::Tracing) + .SetMessage("ReplayScheduler: cannot open replay files.") + .Dispatch(); throw SilKitError("ReplayScheduler: cannot open replay files."); } } @@ -374,6 +394,8 @@ ReplayScheduler::~ReplayScheduler() void ReplayScheduler::ReplayMessages(std::chrono::nanoseconds now, std::chrono::nanoseconds duration) { + using namespace Services::Logging; + if (_isDone) { return; @@ -405,8 +427,9 @@ void ReplayScheduler::ReplayMessages(std::chrono::nanoseconds now, std::chrono:: auto msg = task.replayReader->Read(); if (!msg) { - Services::Logging::Trace(_log, "ReplayTask on channel '{}' returned invalid message @{}ns", task.name, - now.count()); + _log->MakeMessage(Level::Trace, Topic::Tracing) + .SetMessage("ReplayTask on channel '{}' returned invalid message @{}ns", task.name, now.count()) + .Dispatch(); task.doneReplaying = true; break; } diff --git a/SilKit/source/tracing/ReplayScheduler.hpp b/SilKit/source/tracing/ReplayScheduler.hpp index 1f4b376a6..5a7d1c472 100644 --- a/SilKit/source/tracing/ReplayScheduler.hpp +++ b/SilKit/source/tracing/ReplayScheduler.hpp @@ -13,6 +13,7 @@ #include "ITimeProvider.hpp" #include "IReplayDataController.hpp" #include "ISimulator.hpp" +#include "ILoggerInternal.hpp" namespace SilKit { namespace Tracing { @@ -50,7 +51,7 @@ class ReplayScheduler }; std::chrono::nanoseconds _startTime{std::chrono::nanoseconds::min()}; - Services::Logging::ILogger* _log{nullptr}; + Services::Logging::ILoggerInternal* _log{nullptr}; Core::IParticipantInternal* _participant{nullptr}; Services::Orchestration::ITimeProvider* _timeProvider{nullptr}; std::vector _replayTasks; diff --git a/SilKit/source/tracing/Tracing.cpp b/SilKit/source/tracing/Tracing.cpp index e0fe2c0e7..d3ae57190 100644 --- a/SilKit/source/tracing/Tracing.cpp +++ b/SilKit/source/tracing/Tracing.cpp @@ -19,7 +19,7 @@ namespace Tracing { // Tracing //! \brief Creates the ITraceMessageSink's as declared in the configuration. -auto CreateTraceMessageSinks(Services::Logging::ILogger* logger, +auto CreateTraceMessageSinks(Services::Logging::ILoggerInternal* logger, const Config::ParticipantConfiguration& participantConfig) -> std::vector> { @@ -60,10 +60,10 @@ auto CreateTraceMessageSinks(Services::Logging::ILogger* logger, { if (!sinkInUse(sinkCfg.name)) { - Services::Logging::Warn( - logger, - "Tracing: the trace sink '{}' on participant '{}' is not referenced in the config, creating anyway!", - sinkCfg.name, participantConfig.participantName); + logger->MakeMessage(Services::Logging::Level::Warn, Services::Logging::Topic::Tracing) + .SetMessage("Tracing: the trace sink '{}' on participant '{}' is not referenced in the config, creating anyway!", + sinkCfg.name, participantConfig.participantName) + .Dispatch(); } switch (sinkCfg.type) @@ -99,7 +99,7 @@ auto CreateTraceMessageSinks(Services::Logging::ILogger* logger, return newSinks; } -auto CreateReplayFiles(Services::Logging::ILogger* logger, const Config::ParticipantConfiguration& participantConfig) +auto CreateReplayFiles(Services::Logging::ILoggerInternal* logger, const Config::ParticipantConfiguration& participantConfig) -> std::map> { std::map> replayFiles; @@ -116,7 +116,7 @@ auto CreateReplayFiles(Services::Logging::ILogger* logger, const Config::Partici } case Config::TraceSource::Type::PcapFile: { - auto provider = PcapReplay{}; + PcapReplay provider{}; auto file = provider.OpenFile(participantConfig, source.inputPath, logger); replayFiles.insert({source.name, std::move(file)}); break; diff --git a/SilKit/source/tracing/Tracing.hpp b/SilKit/source/tracing/Tracing.hpp index 93ed87d83..2e755a8f5 100644 --- a/SilKit/source/tracing/Tracing.hpp +++ b/SilKit/source/tracing/Tracing.hpp @@ -16,19 +16,20 @@ #include "ITraceMessageSink.hpp" #include "IReplay.hpp" #include "ParticipantConfiguration.hpp" +#include "ILoggerInternal.hpp" namespace SilKit { namespace Tracing { // Configure the trace sinks based on the configuration and return a vector of // the sinks. -auto CreateTraceMessageSinks(Services::Logging::ILogger* logger, +auto CreateTraceMessageSinks(Services::Logging::ILoggerInternal* logger, const Config::ParticipantConfiguration& participantConfig) -> std::vector>; // Configure replay files from the trace source configurations and return a vector of // the files. -auto CreateReplayFiles(Services::Logging::ILogger* logger, const Config::ParticipantConfiguration& participantConfig) +auto CreateReplayFiles(Services::Logging::ILoggerInternal* logger, const Config::ParticipantConfiguration& participantConfig) -> std::map>; //! \brief Predicate to check whether any of the participant's controllers From 34540c1f354a77ef91de2050fcf7ac1c6da18b74 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Thu, 16 Apr 2026 09:44:47 +0200 Subject: [PATCH 13/23] fixup! fixup! Upgrade logging in asio component --- SilKit/source/core/vasio/SilKitLink.hpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/SilKit/source/core/vasio/SilKitLink.hpp b/SilKit/source/core/vasio/SilKitLink.hpp index 5d5375392..98e0b3a97 100644 --- a/SilKit/source/core/vasio/SilKitLink.hpp +++ b/SilKit/source/core/vasio/SilKitLink.hpp @@ -200,12 +200,15 @@ void SilKitLink::DispatchSilKitMessage(ReceiverT* to, const IServiceEndpoi } catch (const std::exception& e) { - Services::Logging::Warn(_logger, "Callback for {}[\"{}\"] threw an exception: {}", MsgTypeName(), Name(), - e.what()); + _logger->MakeMessage(Services::Logging::Level::Warn, Services::Logging::Topic::Asio) + .SetMessage("Callback for {}[\"{}\"] threw an exception: {}", MsgTypeName(), Name(), e.what()) + .Dispatch(); } catch (...) { - Services::Logging::Warn(_logger, "Callback for {}[\"{}\"] threw an unknown exception", MsgTypeName(), Name()); + _logger->MakeMessage(Services::Logging::Level::Warn, Services::Logging::Topic::Asio) + .SetMessage("Callback for {}[\"{}\"] threw an unknown exception", MsgTypeName(), Name()) + .Dispatch(); } } From 51f0bb8d2d779fe8f39f861655a3c8e1e860e6e9 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Thu, 16 Apr 2026 10:52:06 +0200 Subject: [PATCH 14/23] fixup! fixup! Upgrade logging in asio component --- .../core/vasio/Test_TransformAcceptorUris.cpp | 26 ++++++++++++++--- .../core/vasio/TransformAcceptorUris.cpp | 29 ++++++++++++------- .../core/vasio/TransformAcceptorUris.hpp | 4 +-- .../core/vasio/io/util/TracingMacros.hpp | 6 ++-- 4 files changed, 46 insertions(+), 19 deletions(-) diff --git a/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp b/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp index db31a1ac7..a57c01325 100644 --- a/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp +++ b/SilKit/source/core/vasio/Test_TransformAcceptorUris.cpp @@ -8,6 +8,8 @@ #include "gtest/gtest.h" +#include "LoggerMessage.hpp" + #include #include #include @@ -226,12 +228,12 @@ struct AudienceVAsioPeer final : DummyVAsioPeerBase } }; -struct DummyLogger : SilKit::Services::Logging::ILogger +struct DummyLogger : SilKit::Services::Logging::ILoggerInternal { void Log(SilKit::Services::Logging::Level level, const std::string& msg) override { const auto now = std::chrono::steady_clock::now(); - std::cout << "[DummyLogger:" << level << ":" + std::cout << "[DummyLogger:" << static_cast(level) << ":" << std::chrono::duration_cast(now.time_since_epoch()).count() << "] " << msg << std::endl; } @@ -240,7 +242,7 @@ struct DummyLogger : SilKit::Services::Logging::ILogger const std::string& msg) override { const auto now = std::chrono::steady_clock::now(); - std::cout << "[DummyLogger:" << level << ":" << topic << ":" + std::cout << "[DummyLogger:" << static_cast(level) << ":" << static_cast(topic) << ":" << std::chrono::duration_cast(now.time_since_epoch()).count() << "] " << msg << std::endl; } @@ -265,7 +267,23 @@ struct DummyLogger : SilKit::Services::Logging::ILogger SilKit::Services::Logging::Level GetLogLevel() const override { - return SilKit::Services::Logging::Level::Off; + return SilKit::Services::Logging::Level::Trace; + } + + void ProcessLoggerMessage(const SilKit::Services::Logging::LoggerMessage& msg) override + { + Log(msg.GetLevel(), msg.GetTopic(), msg.GetMsgString()); + } + + void LogReceivedMsg(const SilKit::Services::Logging::LogMsg& msg) override + { + Log(msg.level, msg.topic, msg.payload); + } + + SilKit::Services::Logging::LoggerMessage MakeMessage(SilKit::Services::Logging::Level level, + SilKit::Services::Logging::Topic topic) override + { + return SilKit::Services::Logging::LoggerMessage{this, level, topic}; } }; diff --git a/SilKit/source/core/vasio/TransformAcceptorUris.cpp b/SilKit/source/core/vasio/TransformAcceptorUris.cpp index c14e7b144..6421b1016 100644 --- a/SilKit/source/core/vasio/TransformAcceptorUris.cpp +++ b/SilKit/source/core/vasio/TransformAcceptorUris.cpp @@ -4,7 +4,7 @@ #include "TransformAcceptorUris.hpp" -#include "Logger.hpp" +#include "LoggerMessage.hpp" #include @@ -17,6 +17,7 @@ namespace { using SilKit::Core::Uri; using SilKit::SilKitError; +using namespace SilKit::Services::Logging; struct UriLexicographicLess { @@ -70,7 +71,7 @@ inline auto GetUriInfo(const Uri& uri) -> UriInfo return UriInfo{}; } -auto TransformAcceptorUris(SilKit::Services::Logging::ILogger* logger, IVAsioPeer* advertisedPeer, +auto TransformAcceptorUris(SilKit::Services::Logging::ILoggerInternal* logger, IVAsioPeer* advertisedPeer, IVAsioPeer* audiencePeer) -> std::vector { const auto src = Uri::Parse(advertisedPeer->GetRemoteAddress()); @@ -82,18 +83,22 @@ auto TransformAcceptorUris(SilKit::Services::Logging::ILogger* logger, IVAsioPee std::set acceptorUris; const auto acceptUri = [logger, &acceptorUris, audiencePeer, advertisedPeer](const Uri& uri) { - Services::Logging::Debug(logger, "SIL Kit Registry: TransformAcceptorUris: '{}' to '{}': Accept: {}", - advertisedPeer->GetInfo().participantName, audiencePeer->GetInfo().participantName, - uri.EncodedString()); + logger->MakeMessage(Level::Debug, Topic::Participant) + .SetMessage("SIL Kit Registry: TransformAcceptorUris: '{}' to '{}': Accept: {}", + advertisedPeer->GetInfo().participantName, audiencePeer->GetInfo().participantName, + uri.EncodedString()) + .Dispatch(); acceptorUris.emplace(uri); }; const auto acceptNewTcpUri = [logger, &acceptorUris, audiencePeer, advertisedPeer](const std::string& host, uint16_t port) { auto uri = Uri::MakeTcp(host, port); - Services::Logging::Debug(logger, "SIL Kit Registry: TransformAcceptorUris: '{}' to '{}': Accept: {}", - advertisedPeer->GetInfo().participantName, audiencePeer->GetInfo().participantName, - uri.EncodedString()); + logger->MakeMessage(Level::Debug, Topic::Participant) + .SetMessage("SIL Kit Registry: TransformAcceptorUris: '{}' to '{}': Accept: {}", + advertisedPeer->GetInfo().participantName, audiencePeer->GetInfo().participantName, + uri.EncodedString()) + .Dispatch(); acceptorUris.emplace(std::move(uri)); }; @@ -118,9 +123,11 @@ auto TransformAcceptorUris(SilKit::Services::Logging::ILogger* logger, IVAsioPee const auto uri = Uri::Parse(uriString); const auto uriInfo = GetUriInfo(uri); - Services::Logging::Debug(logger, "SIL Kit Registry: TransformAcceptorUris: '{}' to '{}': Decide: {}", - advertisedPeer->GetInfo().participantName, audiencePeer->GetInfo().participantName, - uri.EncodedString()); + logger->MakeMessage(Level::Debug, Topic::Participant) + .SetMessage("SIL Kit Registry: TransformAcceptorUris: '{}' to '{}': Decide: {}", + advertisedPeer->GetInfo().participantName, audiencePeer->GetInfo().participantName, + uri.EncodedString()) + .Dispatch(); if (uriInfo.catchallIp) { diff --git a/SilKit/source/core/vasio/TransformAcceptorUris.hpp b/SilKit/source/core/vasio/TransformAcceptorUris.hpp index b990e9a56..d2dc8f6c9 100644 --- a/SilKit/source/core/vasio/TransformAcceptorUris.hpp +++ b/SilKit/source/core/vasio/TransformAcceptorUris.hpp @@ -4,8 +4,8 @@ #pragma once -#include "silkit/services/logging/ILogger.hpp" +#include "LoggerMessage.hpp" #include "IVAsioPeer.hpp" #include "Uri.hpp" @@ -27,7 +27,7 @@ struct UriInfo auto GetUriInfo(const Uri& uri) -> UriInfo; -auto TransformAcceptorUris(SilKit::Services::Logging::ILogger* logger, IVAsioPeer* advertisedPeer, +auto TransformAcceptorUris(SilKit::Services::Logging::ILoggerInternal* logger, IVAsioPeer* advertisedPeer, IVAsioPeer* audiencePeer) -> std::vector; } // namespace Core diff --git a/SilKit/source/core/vasio/io/util/TracingMacros.hpp b/SilKit/source/core/vasio/io/util/TracingMacros.hpp index 556481b0f..b39924a40 100644 --- a/SilKit/source/core/vasio/io/util/TracingMacros.hpp +++ b/SilKit/source/core/vasio/io/util/TracingMacros.hpp @@ -20,7 +20,7 @@ namespace VSilKit { template -void TraceEvent(SilKit::Services::Logging::ILogger* logger, fmt::string_view fileName, size_t line, +void TraceEvent(SilKit::Services::Logging::ILoggerInternal* logger, fmt::string_view fileName, size_t line, fmt::string_view function, const void* object, Args&&... args) { if (logger == nullptr) @@ -50,7 +50,9 @@ void TraceEvent(SilKit::Services::Logging::ILogger* logger, fmt::string_view fil formattedArguments.clear(); fmt::format_to(std::back_inserter(formattedArguments), std::forward(args)...); - SilKit::Services::Logging::Trace(logger, "{} {}", formattedPrefix, formattedArguments); + logger->MakeMessage(SilKit::Services::Logging::Level::Trace, SilKit::Services::Logging::Topic::Asio) + .SetMessage("{} {}", formattedPrefix, formattedArguments) + .Dispatch(); } From e339ca2fd468ed81dc6bbfbeca340658eb8781c7 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Thu, 16 Apr 2026 11:17:37 +0200 Subject: [PATCH 15/23] fixup! fixup! Upgrade logging in asio component --- SilKit/source/core/vasio/VAsioRegistry.cpp | 2 +- SilKit/source/core/vasio/VAsioRegistry.hpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/SilKit/source/core/vasio/VAsioRegistry.cpp b/SilKit/source/core/vasio/VAsioRegistry.cpp index dfbdf3a7f..09870d1c7 100644 --- a/SilKit/source/core/vasio/VAsioRegistry.cpp +++ b/SilKit/source/core/vasio/VAsioRegistry.cpp @@ -48,7 +48,7 @@ VAsioRegistry::VAsioRegistry(std::shared_ptrOnLoggerCreated(dynamic_cast(_logger.get())); + _registryEventListener->OnLoggerCreated(_logger.get()); } dynamic_cast(*_metricsProcessor).SetLogger(*_logger); diff --git a/SilKit/source/core/vasio/VAsioRegistry.hpp b/SilKit/source/core/vasio/VAsioRegistry.hpp index 7904f45d9..34ca95b4c 100644 --- a/SilKit/source/core/vasio/VAsioRegistry.hpp +++ b/SilKit/source/core/vasio/VAsioRegistry.hpp @@ -6,7 +6,7 @@ #include -#include "silkit/services/logging/ILogger.hpp" +#include "ILoggerInternal.hpp" #include "silkit/vendor/ISilKitRegistry.hpp" #include "silkit/services/orchestration/OrchestrationDatatypes.hpp" @@ -32,7 +32,7 @@ struct IRegistryEventListener { virtual ~IRegistryEventListener() = default; - virtual void OnLoggerCreated(SilKit::Services::Logging::ILogger* logger) = 0; + virtual void OnLoggerCreated(SilKit::Services::Logging::ILoggerInternal* logger) = 0; virtual void OnRegistryUri(const std::string& registryUri) = 0; virtual void OnParticipantConnected(const std::string& simulationName, const std::string& participantName) = 0; virtual void OnParticipantDisconnected(const std::string& simulationName, const std::string& participantName) = 0; From 39d9a9d7eae8d3241225671de37604afe43850a5 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Thu, 16 Apr 2026 11:18:18 +0200 Subject: [PATCH 16/23] Roll out new logger interface in dashboard component --- .../services/logging/LoggingDatatypes.hpp | 3 + .../internal/traits/SilKitLoggingTraits.hpp | 10 +++ SilKit/source/dashboard/DashboardInstance.cpp | 88 ++++++++++++------- SilKit/source/dashboard/DashboardInstance.hpp | 4 +- .../client/DashboardSystemServiceClient.cpp | 15 +++- .../client/DashboardSystemServiceClient.hpp | 6 +- .../dashboard/service/DashboardRestClient.cpp | 18 ++-- .../dashboard/service/DashboardRestClient.hpp | 8 +- 8 files changed, 100 insertions(+), 52 deletions(-) diff --git a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp index 94b0f6c63..8644938c1 100644 --- a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp +++ b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp @@ -41,6 +41,9 @@ enum class Topic : uint32_t SystemMonitor = 11, Controller = 12, Tracing = 13, + Metrics = 14, + Dashboard = 15, + NetworkSimulation = 16, Invalid = 0xffffffff //!< Invalid log message topic }; diff --git a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp index bfc73efa3..86a5f46ea 100644 --- a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp @@ -61,6 +61,13 @@ class LifecycleManagement; } } +namespace SilKit { +namespace Dashboard { +class DashboardRestClient; +class DashboardSystemServiceClient; +class DashboardInstance; +} +} namespace SilKit { namespace Core { @@ -127,6 +134,9 @@ DefineSilKitLoggingTrait_Topic(SilKit::Services::Can::CanController, SilKit::Ser DefineSilKitLoggingTrait_Topic(SilKit::Services::Ethernet::EthController, SilKit::Services::Logging::Topic::Controller); DefineSilKitLoggingTrait_Topic(SilKit::Services::Flexray::FlexrayController, SilKit::Services::Logging::Topic::Controller); +DefineSilKitLoggingTrait_Topic(SilKit::Dashboard::DashboardRestClient, SilKit::Services::Logging::Topic::Dashboard); +DefineSilKitLoggingTrait_Topic(SilKit::Dashboard::DashboardSystemServiceClient, SilKit::Services::Logging::Topic::Dashboard); +DefineSilKitLoggingTrait_Topic(SilKit::Dashboard::DashboardInstance, SilKit::Services::Logging::Topic::Dashboard); } // namespace Core diff --git a/SilKit/source/dashboard/DashboardInstance.cpp b/SilKit/source/dashboard/DashboardInstance.cpp index 2c5a81871..092197e59 100644 --- a/SilKit/source/dashboard/DashboardInstance.cpp +++ b/SilKit/source/dashboard/DashboardInstance.cpp @@ -9,9 +9,6 @@ #include "DashboardRestClient.hpp" -namespace Log = SilKit::Services::Logging; - - namespace { @@ -76,15 +73,16 @@ void DashboardInstance::SetupDashboardConnection(const std::string& dashboardUri using namespace SilKit::Services; using namespace SilKit::Services::Logging; using namespace SilKit::Dashboard; + class EventQueueWorkerThread { - ILogger* _logger{nullptr}; + ILoggerInternal* _logger{nullptr}; IRestClient* _dashboardRestClient{nullptr}; LockedQueue* _eventQueue{nullptr}; std::future _abort; public: //CTor - EventQueueWorkerThread(ILogger* logger, IRestClient* dashboardRestClient, LockedQueue* eventQueue, + EventQueueWorkerThread(ILoggerInternal* logger, IRestClient* dashboardRestClient, LockedQueue* eventQueue, std::future abort) : _logger{logger} , _dashboardRestClient{dashboardRestClient} @@ -149,8 +147,9 @@ class EventQueueWorkerThread if (it != simulationNameToId.end()) { // it is possible that multiple SimulationStart events are created (due to the queuing) - Log::Debug(_logger, "Dashboard: Simulation {} already has id {}", event.GetSimulationName(), - it->second); + _logger->MakeMessage(Level::Debug, *this) + .SetMessage("Dashboard: Simulation {} already has id {}", event.GetSimulationName(), it->second) + .Dispatch(); continue; } @@ -160,7 +159,9 @@ class EventQueueWorkerThread if (simulationId == 0) { - Log::Warn(_logger, "Dashboard: Simulation {} could not be created", event.GetSimulationName()); + _logger->MakeMessage(Level::Warn, *this) + .SetMessage("Dashboard: Simulation {} could not be created", event.GetSimulationName()) + .Dispatch(); continue; } @@ -174,7 +175,9 @@ class EventQueueWorkerThread const auto it{simulationNameToId.find(event.GetSimulationName())}; if (it == simulationNameToId.end()) { - Log::Warn(_logger, "Dashboard: Simulation {} is unknown", event.GetSimulationName()); + _logger->MakeMessage(Level::Warn, *this) + .SetMessage("Dashboard: Simulation {} is unknown", event.GetSimulationName()) + .Dispatch(); continue; } @@ -231,7 +234,9 @@ class EventQueueWorkerThread default: { - Log::Error(_logger, "Dashboard: unexpected SilKitEventType"); + _logger->MakeMessage(Level::Error, *this) + .SetMessage("Dashboard: unexpected SilKitEventType") + .Dispatch(); } break; } @@ -260,11 +265,15 @@ class EventQueueWorkerThread } catch (const std::exception& exception) { - Log::Error(_logger, "Dashboard: event queue worker failed: {}", exception.what()); + _logger->MakeMessage(Level::Error, *this) + .SetMessage("Dashboard: event queue worker failed: {}", exception.what()) + .Dispatch(); } catch (...) { - Log::Error(_logger, "Dashboard: event queue worker failed with unknown exception"); + _logger->MakeMessage(Level::Error, *this) + .SetMessage("Dashboard: event queue worker failed with unknown exception") + .Dispatch(); } }; @@ -283,8 +292,6 @@ void DashboardInstance::RunEventQueueWorkerThread() auto DashboardInstance::GetOrCreateSimulationData(const std::string& simulationName) -> SimulationData& { auto& simulationDataRef{_simulationEventHandlers[simulationName]}; - //vikabgm: only used for debugging? simulationDataRef.systemStateTracker.SetLogger(_logger); - return simulationDataRef; } @@ -293,7 +300,7 @@ void DashboardInstance::RemoveSimulationData(const std::string& simulationName) _simulationEventHandlers.erase(simulationName); } -void DashboardInstance::OnLoggerCreated(SilKit::Services::Logging::ILogger* logger) +void DashboardInstance::OnLoggerCreated(SilKit::Services::Logging::ILoggerInternal* logger) { SILKIT_ASSERT(_logger == nullptr); _logger = logger; @@ -301,15 +308,19 @@ void DashboardInstance::OnLoggerCreated(SilKit::Services::Logging::ILogger* logg void DashboardInstance::OnRegistryUri(const std::string& registryUri) { - Log::Debug(_logger, "DashboardInstance::OnRegistryUri: registryUri={}", registryUri); + _logger->MakeMessage(Level::Debug, *this) + .SetMessage("DashboardInstance::OnRegistryUri: registryUri={}", registryUri) + .Dispatch(); SILKIT_ASSERT(_registryUri == nullptr); _registryUri = std::make_unique(registryUri); } void DashboardInstance::OnParticipantConnected(const std::string& simulationName, const std::string& participantName) { - Log::Trace(_logger, "DashboardInstance::OnParticipantConnected: simulationName={} participantName={}", - simulationName, participantName); + _logger->MakeMessage(Level::Trace, *this) + .SetMessage("DashboardInstance::OnParticipantConnected: simulationName={} participantName={}", + simulationName, participantName) + .Dispatch(); auto& simulationData{GetOrCreateSimulationData(simulationName)}; @@ -318,7 +329,8 @@ void DashboardInstance::OnParticipantConnected(const std::string& simulationName const auto connectUri{ SilKit::Core::Uri::MakeSilKit(_registryUri->Host(), _registryUri->Port(), simulationName)}; _silKitEventQueue.Enqueue( - SilKitEvent{simulationName, SimulationStart{connectUri.EncodedString(), GetCurrentSystemTime()}}); + SilKitEvent{simulationName, SimulationStart{connectUri.EncodedString(), GetCurrentSystemTime()}} + ); } _silKitEventQueue.Enqueue(SilKitEvent{ @@ -327,8 +339,10 @@ void DashboardInstance::OnParticipantConnected(const std::string& simulationName void DashboardInstance::OnParticipantDisconnected(const std::string& simulationName, const std::string& participantName) { - Log::Debug(_logger, "DashboardInstance::OnParticipantDisconnected: simulationName={} participantName={}", - simulationName, participantName); + _logger->MakeMessage(Level::Debug, *this) + .SetMessage("DashboardInstance::OnParticipantDisconnected: simulationName={} participantName={}", + simulationName, participantName) + .Dispatch(); bool isEmpty{false}; @@ -355,10 +369,11 @@ void DashboardInstance::OnRequiredParticipantsUpdate(const std::string& simulati const std::string& participantName, SilKit::Util::Span requiredParticipantNames) { - Log::Trace(_logger, - "DashboardInstance::OnRequiredParticipantsUpdate: simulationName={} participantName={} " - "requiredParticipantNames={}", - simulationName, participantName, requiredParticipantNames.size()); + _logger->MakeMessage(Level::Trace, *this) + .SetMessage("DashboardInstance::OnRequiredParticipantsUpdate: simulationName={} participantName={} " + "requiredParticipantNames={}", + simulationName, participantName, requiredParticipantNames.size()) + .Dispatch(); auto& simulationData{GetOrCreateSimulationData(simulationName)}; const auto result{simulationData.systemStateTracker.UpdateRequiredParticipants(requiredParticipantNames)}; @@ -373,10 +388,12 @@ void DashboardInstance::OnParticipantStatusUpdate( const std::string& simulationName, const std::string& participantName, const SilKit::Services::Orchestration::ParticipantStatus& participantStatus) { - Log::Trace(_logger, - "DashboardInstance::OnParticipantStatusUpdate: simulationName={} participantName={} " - "participantState={}", - simulationName, participantName, participantStatus.state); + _logger->MakeMessage(Level::Trace, *this) + .SetMessage("DashboardInstance::OnParticipantStatusUpdate: simulationName={} participantName={} " + "participantState={}", + + simulationName, participantName, participantStatus.state) + .Dispatch(); auto& simulationData{GetOrCreateSimulationData(simulationName)}; const auto result{simulationData.systemStateTracker.UpdateParticipantStatus(participantStatus)}; @@ -396,9 +413,10 @@ void DashboardInstance::OnServiceDiscoveryEvent( const std::string& simulationName, const std::string& participantName, const SilKit::Core::Discovery::ServiceDiscoveryEvent& serviceDiscoveryEvent) { - Log::Trace(_logger, - "DashboardInstance::OnServiceDiscoveryEvent: simulationName={} participantName={} serviceName={}", - simulationName, participantName, serviceDiscoveryEvent.serviceDescriptor.GetServiceName()); + _logger->MakeMessage(Level::Trace, *this) + .SetMessage("DashboardInstance::OnServiceDiscoveryEvent: simulationName={} participantName={} serviceName={}", + simulationName, participantName, serviceDiscoveryEvent.serviceDescriptor.GetServiceName()) + .Dispatch(); if (ShouldSkipServiceDiscoveryEvent(serviceDiscoveryEvent)) { @@ -412,8 +430,10 @@ void DashboardInstance::OnServiceDiscoveryEvent( void DashboardInstance::OnMetricsUpdate(const std::string& simulationName, const std::string& origin, const VSilKit::MetricsUpdate& metricsUpdate) { - Log::Trace(_logger, "DashboardInstance::OnMetricsUpdate: simulationName={} origin={} metricsUpdate={}", - simulationName, origin, metricsUpdate); + _logger->MakeMessage(Level::Trace, *this) + .SetMessage("DashboardInstance::OnMetricsUpdate: simulationName={} origin={} metricsUpdate={}", + simulationName, origin, metricsUpdate) + .Dispatch(); std::pair data{origin, metricsUpdate}; diff --git a/SilKit/source/dashboard/DashboardInstance.hpp b/SilKit/source/dashboard/DashboardInstance.hpp index 273adc522..997317b68 100644 --- a/SilKit/source/dashboard/DashboardInstance.hpp +++ b/SilKit/source/dashboard/DashboardInstance.hpp @@ -57,7 +57,7 @@ class DashboardInstance final void RunEventQueueWorkerThread(); private: // SilKit::Core::IRegistryEventListener - void OnLoggerCreated(SilKit::Services::Logging::ILogger* logger) override; + void OnLoggerCreated(SilKit::Services::Logging::ILoggerInternal* logger) override; void OnRegistryUri(const std::string& registryUri) override; void OnParticipantConnected(const std::string& simulationName, const std::string& participantName) override; void OnParticipantDisconnected(const std::string& simulationName, const std::string& participantName) override; @@ -73,7 +73,7 @@ class DashboardInstance final private: /// Assigned in OnLoggerCreated - SilKit::Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; /// Assigned in OnRegistryUri std::unique_ptr _registryUri; diff --git a/SilKit/source/dashboard/client/DashboardSystemServiceClient.cpp b/SilKit/source/dashboard/client/DashboardSystemServiceClient.cpp index 0ef8bcbcb..011aedd13 100644 --- a/SilKit/source/dashboard/client/DashboardSystemServiceClient.cpp +++ b/SilKit/source/dashboard/client/DashboardSystemServiceClient.cpp @@ -9,12 +9,13 @@ #include OATPP_CODEGEN_BEGIN(ApiClient) using namespace std::chrono_literals; +using namespace SilKit::Services::Logging; namespace SilKit { namespace Dashboard { DashboardSystemServiceClient::DashboardSystemServiceClient( - Services::Logging::ILogger* logger, std::shared_ptr dashboardSystemApiClient, + Services::Logging::ILoggerInternal* logger, std::shared_ptr dashboardSystemApiClient, std::shared_ptr objectMapper) : _logger(logger) , _dashboardSystemApiClient(dashboardSystemApiClient) @@ -56,15 +57,21 @@ void DashboardSystemServiceClient::Log(std::shared_ptrMakeMessage(Level::Error, *this) + .SetMessage("Dashboard: {} server unavailable", message) + .Dispatch(); } else if (response->getStatusCode() >= 400) { - Services::Logging::Error(_logger, "Dashboard: {} returned {}", message, response->getStatusCode()); + _logger->MakeMessage(Level::Error, *this) + .SetMessage("Dashboard: {} returned {}", message, response->getStatusCode()) + .Dispatch(); } else { - Services::Logging::Debug(_logger, "Dashboard: {} returned {}", message, response->getStatusCode()); + _logger->MakeMessage(Level::Debug, *this) + .SetMessage("Dashboard: {} returned {}", message, response->getStatusCode()) + .Dispatch(); } } diff --git a/SilKit/source/dashboard/client/DashboardSystemServiceClient.hpp b/SilKit/source/dashboard/client/DashboardSystemServiceClient.hpp index 72b379cb3..452bc7bf6 100644 --- a/SilKit/source/dashboard/client/DashboardSystemServiceClient.hpp +++ b/SilKit/source/dashboard/client/DashboardSystemServiceClient.hpp @@ -8,7 +8,7 @@ #include -#include "silkit/services/logging/ILogger.hpp" +#include "ILoggerInternal.hpp" #include "DashboardSystemApiClient.hpp" @@ -18,7 +18,7 @@ namespace Dashboard { class DashboardSystemServiceClient : public IDashboardSystemServiceClient { public: - DashboardSystemServiceClient(Services::Logging::ILogger* logger, + DashboardSystemServiceClient(Services::Logging::ILoggerInternal* logger, std::shared_ptr dashboardSystemApiClient, std::shared_ptr objectMapper); ~DashboardSystemServiceClient(); @@ -33,7 +33,7 @@ class DashboardSystemServiceClient : public IDashboardSystemServiceClient void Log(std::shared_ptr response, const std::string& message); private: - Services::Logging::ILogger* _logger; + Services::Logging::ILoggerInternal* _logger; std::shared_ptr _dashboardSystemApiClient; std::shared_ptr _objectMapper; }; diff --git a/SilKit/source/dashboard/service/DashboardRestClient.cpp b/SilKit/source/dashboard/service/DashboardRestClient.cpp index cff2e1773..1f2202564 100644 --- a/SilKit/source/dashboard/service/DashboardRestClient.cpp +++ b/SilKit/source/dashboard/service/DashboardRestClient.cpp @@ -11,6 +11,8 @@ #include "SilKitToOatppMapper.hpp" #include "client/DashboardSystemServiceClient.hpp" +using namespace SilKit::Services::Logging; + namespace SilKit { namespace Dashboard { @@ -23,7 +25,7 @@ LibraryInitializer::~LibraryInitializer() oatpp::base::Environment::destroy(); } -DashboardRestClient::DashboardRestClient(Services::Logging::ILogger* logger, const std::string& dashboardServerUri) +DashboardRestClient::DashboardRestClient(Services::Logging::ILoggerInternal* logger, const std::string& dashboardServerUri) : _logger(logger) { _libraryInit = std::make_shared(); @@ -42,7 +44,7 @@ DashboardRestClient::DashboardRestClient(Services::Logging::ILogger* logger, con } DashboardRestClient::DashboardRestClient(std::shared_ptr libraryInit, - Services::Logging::ILogger* logger, + Services::Logging::ILoggerInternal* logger, std::shared_ptr serviceClient, std::shared_ptr mapper) @@ -88,15 +90,21 @@ bool DashboardRestClient::IsBulkUpdateSupported() uint64_t DashboardRestClient::OnSimulationStart(const std::string& connectUri, uint64_t time) { - Services::Logging::Info(_logger, "Dashboard: creating simulation {} {}", connectUri, time); + _logger->MakeMessage(Level::Info, *this) + .SetMessage("Dashboard: creating simulation {} {}", connectUri, time) + .Dispatch(); auto simulation = _serviceClient->CreateSimulation(_silKitToOatppMapper->CreateSimulationCreationRequestDto(connectUri, time)); if (simulation) { - Services::Logging::Info(_logger, "Dashboard: created simulation with id {}", *simulation->id.get()); + _logger->MakeMessage(Level::Info, *this) + .SetMessage("Dashboard: created simulation with id {}", *simulation->id.get()) + .Dispatch(); return simulation->id; } - _logger->Warn("Dashboard: creating simulation failed"); + _logger->MakeMessage(Level::Warn, *this) + .SetMessage("Dashboard: creating simulation failed") + .Dispatch(); return 0; } diff --git a/SilKit/source/dashboard/service/DashboardRestClient.hpp b/SilKit/source/dashboard/service/DashboardRestClient.hpp index 8cb485de0..578fee298 100644 --- a/SilKit/source/dashboard/service/DashboardRestClient.hpp +++ b/SilKit/source/dashboard/service/DashboardRestClient.hpp @@ -8,7 +8,7 @@ #include #include -#include "silkit/services/logging/ILogger.hpp" +#include "ILoggerInternal.hpp" #include "ISilKitToOatppMapper.hpp" #include "IDashboardSystemServiceClient.hpp" @@ -31,11 +31,11 @@ struct LibraryInitializer class DashboardRestClient : public VSilKit::IRestClient { public: - DashboardRestClient(Services::Logging::ILogger* logger, const std::string& dashboardServerUri); + DashboardRestClient(Services::Logging::ILoggerInternal* logger, const std::string& dashboardServerUri); ~DashboardRestClient() override; public: // For testing - DashboardRestClient(std::shared_ptr libraryInit, Services::Logging::ILogger* logger, + DashboardRestClient(std::shared_ptr libraryInit, Services::Logging::ILoggerInternal* logger, std::shared_ptr serviceClient, std::shared_ptr mapper); @@ -50,7 +50,7 @@ class DashboardRestClient : public VSilKit::IRestClient private: //member std::shared_ptr _libraryInit; - Services::Logging::ILogger* _logger; + Services::Logging::ILoggerInternal* _logger; std::shared_ptr _retryPolicy; std::shared_ptr _silKitToOatppMapper; std::shared_ptr _apiClient; From f4e3bc9f31150a0c252f1156d54335c4acd7968e Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Thu, 16 Apr 2026 11:30:35 +0200 Subject: [PATCH 17/23] Roll out new logger interface in metrics component --- .../source/core/internal/traits/SilKitLoggingTraits.hpp | 3 +++ SilKit/source/services/metrics/MetricsManager.cpp | 2 +- SilKit/source/services/metrics/MetricsManager.hpp | 4 ++-- SilKit/source/services/metrics/MetricsProcessor.cpp | 8 +++++--- SilKit/source/services/metrics/MetricsProcessor.hpp | 6 ++++-- SilKit/source/services/metrics/MetricsSender.cpp | 5 +---- SilKit/source/services/metrics/MetricsSender.hpp | 2 +- 7 files changed, 17 insertions(+), 13 deletions(-) diff --git a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp index 86a5f46ea..a42dece34 100644 --- a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp @@ -10,6 +10,7 @@ namespace VSilKit { class SystemStateTracker; class ConnectPeer; +class MetricsProcessor; } namespace SilKit { @@ -139,5 +140,7 @@ DefineSilKitLoggingTrait_Topic(SilKit::Dashboard::DashboardSystemServiceClient, DefineSilKitLoggingTrait_Topic(SilKit::Dashboard::DashboardInstance, SilKit::Services::Logging::Topic::Dashboard); +DefineSilKitLoggingTrait_Topic(VSilKit::MetricsProcessor, SilKit::Services::Logging::Topic::Metrics); + } // namespace Core } // namespace SilKit diff --git a/SilKit/source/services/metrics/MetricsManager.cpp b/SilKit/source/services/metrics/MetricsManager.cpp index eac242457..0c67c45ee 100644 --- a/SilKit/source/services/metrics/MetricsManager.cpp +++ b/SilKit/source/services/metrics/MetricsManager.cpp @@ -145,7 +145,7 @@ MetricsManager::MetricsManager(std::string participantName, IMetricsProcessor& p } -void MetricsManager::SetLogger(SilKit::Services::Logging::ILogger& logger) +void MetricsManager::SetLogger(SilKit::Services::Logging::ILoggerInternal& logger) { _logger = &logger; } diff --git a/SilKit/source/services/metrics/MetricsManager.hpp b/SilKit/source/services/metrics/MetricsManager.hpp index e74f0e22d..cc7f60727 100644 --- a/SilKit/source/services/metrics/MetricsManager.hpp +++ b/SilKit/source/services/metrics/MetricsManager.hpp @@ -52,7 +52,7 @@ class MetricsManager : public IMetricsManager public: MetricsManager(std::string participantName, IMetricsProcessor& processor); - void SetLogger(SilKit::Services::Logging::ILogger& logger); + void SetLogger(SilKit::Services::Logging::ILoggerInternal& logger); public: // IMetricsManager void SubmitUpdates() override; @@ -67,7 +67,7 @@ class MetricsManager : public IMetricsManager private: std::string _participantName; IMetricsProcessor* _processor{nullptr}; - SilKit::Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; // Metrics diff --git a/SilKit/source/services/metrics/MetricsProcessor.cpp b/SilKit/source/services/metrics/MetricsProcessor.cpp index d97f68938..e5bdc79ce 100644 --- a/SilKit/source/services/metrics/MetricsProcessor.cpp +++ b/SilKit/source/services/metrics/MetricsProcessor.cpp @@ -7,7 +7,7 @@ #include "IParticipantInternal.hpp" #include "LoggerMessage.hpp" -namespace Log = SilKit::Services::Logging; +using namespace SilKit::Services::Logging; namespace VSilKit { @@ -16,7 +16,7 @@ MetricsProcessor::MetricsProcessor(std::string participantName) { } -void MetricsProcessor::SetLogger(SilKit::Services::Logging::ILogger& logger) +void MetricsProcessor::SetLogger(SilKit::Services::Logging::ILoggerInternal& logger) { _logger = &logger; } @@ -27,7 +27,9 @@ void MetricsProcessor::SetSinks(std::vector> sinks if (_sinksSetUp) { - Log::Error(_logger, "Refusing to setup metrics sinks again"); + _logger->MakeMessage(Level::Error, *this) + .SetMessage("Refusing to setup metrics sinks again") + .Dispatch(); return; } diff --git a/SilKit/source/services/metrics/MetricsProcessor.hpp b/SilKit/source/services/metrics/MetricsProcessor.hpp index b365fb440..b4db07024 100644 --- a/SilKit/source/services/metrics/MetricsProcessor.hpp +++ b/SilKit/source/services/metrics/MetricsProcessor.hpp @@ -8,6 +8,8 @@ #include "MetricsDatatypes.hpp" #include "MetricsReceiver.hpp" +#include "ILoggerInternal.hpp" + #include #include #include @@ -23,7 +25,7 @@ class MetricsProcessor std::mutex _mutex; std::string _participantName; - SilKit::Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; std::atomic _sinksSetUp{false}; std::vector> _sinks; @@ -34,7 +36,7 @@ class MetricsProcessor explicit MetricsProcessor(std::string participantName); public: - void SetLogger(SilKit::Services::Logging::ILogger& logger); + void SetLogger(SilKit::Services::Logging::ILoggerInternal& logger); void SetSinks(std::vector> sinks); public: // IMetricsProcessor diff --git a/SilKit/source/services/metrics/MetricsSender.cpp b/SilKit/source/services/metrics/MetricsSender.cpp index fa805e93f..f7686609c 100644 --- a/SilKit/source/services/metrics/MetricsSender.cpp +++ b/SilKit/source/services/metrics/MetricsSender.cpp @@ -7,15 +7,12 @@ #include "LoggerMessage.hpp" -namespace Log = SilKit::Services::Logging; - - namespace VSilKit { MetricsSender::MetricsSender(SilKit::Core::IParticipantInternal* participant) : _participant{participant} - , _logger{participant->GetLogger()} + , _logger{participant->GetLoggerInternal()} { _serviceDescriptor.SetNetworkName("default"); } diff --git a/SilKit/source/services/metrics/MetricsSender.hpp b/SilKit/source/services/metrics/MetricsSender.hpp index cee9db555..6c9646306 100644 --- a/SilKit/source/services/metrics/MetricsSender.hpp +++ b/SilKit/source/services/metrics/MetricsSender.hpp @@ -34,7 +34,7 @@ class MetricsSender private: SilKit::Core::IParticipantInternal* _participant{nullptr}; - SilKit::Services::Logging::ILogger* _logger{nullptr}; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; SilKit::Core::ServiceDescriptor _serviceDescriptor; }; From af977a180fec78a9e57eb31c7faff32acac4a418 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Thu, 16 Apr 2026 13:02:40 +0200 Subject: [PATCH 18/23] Roll out new logger interface in network simulator component --- .../services/logging/LoggingDatatypes.hpp | 2 +- .../internal/traits/SilKitLoggingTraits.hpp | 16 +++++++++- .../netsim/NetworkSimulatorInternal.cpp | 30 +++++++++++++------ .../netsim/NetworkSimulatorInternal.hpp | 2 +- .../netsim/SimulatedNetworkInternal.cpp | 14 +++++---- .../netsim/SimulatedNetworkInternal.hpp | 2 +- .../netsim/SimulatedNetworkRouter.cpp | 14 +++++---- .../netsim/SimulatedNetworkRouter.hpp | 5 ++-- 8 files changed, 59 insertions(+), 26 deletions(-) diff --git a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp index 8644938c1..c379b09b1 100644 --- a/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp +++ b/SilKit/include/silkit/services/logging/LoggingDatatypes.hpp @@ -43,7 +43,7 @@ enum class Topic : uint32_t Tracing = 13, Metrics = 14, Dashboard = 15, - NetworkSimulation = 16, + NetSim = 16, Invalid = 0xffffffff //!< Invalid log message topic }; diff --git a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp index a42dece34..864709caa 100644 --- a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp @@ -68,7 +68,17 @@ class DashboardRestClient; class DashboardSystemServiceClient; class DashboardInstance; } -} +} + +namespace SilKit { +namespace Experimental { +namespace NetworkSimulation { +class NetworkSimulatorInternal; +class SimulatedNetworkInternal; +class SimulatedNetworkRouter; +} +} +} namespace SilKit { namespace Core { @@ -142,5 +152,9 @@ DefineSilKitLoggingTrait_Topic(SilKit::Dashboard::DashboardInstance, SilKit::Ser DefineSilKitLoggingTrait_Topic(VSilKit::MetricsProcessor, SilKit::Services::Logging::Topic::Metrics); +DefineSilKitLoggingTrait_Topic(SilKit::Experimental::NetworkSimulation::NetworkSimulatorInternal, SilKit::Services::Logging::Topic::NetSim); +DefineSilKitLoggingTrait_Topic(SilKit::Experimental::NetworkSimulation::SimulatedNetworkInternal, SilKit::Services::Logging::Topic::NetSim); +DefineSilKitLoggingTrait_Topic(SilKit::Experimental::NetworkSimulation::SimulatedNetworkRouter, SilKit::Services::Logging::Topic::NetSim); + } // namespace Core } // namespace SilKit diff --git a/SilKit/source/experimental/netsim/NetworkSimulatorInternal.cpp b/SilKit/source/experimental/netsim/NetworkSimulatorInternal.cpp index 0419b29df..e9e17116c 100644 --- a/SilKit/source/experimental/netsim/NetworkSimulatorInternal.cpp +++ b/SilKit/source/experimental/netsim/NetworkSimulatorInternal.cpp @@ -17,7 +17,7 @@ namespace NetworkSimulation { NetworkSimulatorInternal::NetworkSimulatorInternal(Core::IParticipantInternal* participant) : _participant{participant} - , _logger{participant->GetLogger()} + , _logger{participant->GetLoggerInternal()} { _nextControllerDescriptor = 0; _networkSimulatorStarted = false; @@ -30,11 +30,16 @@ void NetworkSimulatorInternal::SimulateNetwork(const std::string& networkName, S { if (_networkSimulatorStarted) { - SilKit::Services::Logging::Warn(_logger, "SimulateNetwork() must not be used after Start()."); + _logger->MakeMessage(SilKit::Services::Logging::Level::Warn, *this) + .SetMessage("SimulateNetwork() must not be used after Start().") + .Dispatch(); return; } - _logger->Debug("SimulateNetwork '" + networkName + "' of type " + to_string(networkType)); + _logger->MakeMessage(SilKit::Services::Logging::Level::Debug, *this) + .SetMessage("SimulateNetwork '{}' of type {}", networkName, to_string(networkType)) + .Dispatch(); + CreateSimulatedNetwork(networkName, networkType, std::move(simulatedNetwork)); } @@ -42,7 +47,9 @@ void NetworkSimulatorInternal::Start() { if (_networkSimulatorStarted) { - SilKit::Services::Logging::Warn(_logger, "Start() has already been called."); + _logger->MakeMessage(SilKit::Services::Logging::Level::Warn, *this) + .SetMessage("Start() has already been called.") + .Dispatch(); return; } @@ -50,7 +57,9 @@ void NetworkSimulatorInternal::Start() if (_simulatedNetworks.empty()) { - SilKit::Services::Logging::Warn(_logger, "NetworkSimulator was started without any simulated networks."); + _logger->MakeMessage(SilKit::Services::Logging::Level::Warn, *this) + .SetMessage("NetworkSimulator was started without any simulated networks.") + .Dispatch(); } // Register the service discovery AFTER the network simulator has been registered. @@ -76,8 +85,9 @@ auto NetworkSimulatorInternal::GetServiceDescriptorString(ControllerDescriptor c auto serviceDescriptor_it = _serviceDescriptorByControllerDescriptor.find(controllerDescriptor); if (serviceDescriptor_it == _serviceDescriptorByControllerDescriptor.end()) { - SilKit::Services::Logging::Warn(_logger, - "GetServiceDescriptorString queried with an unknown controllerDescriptor."); + _logger->MakeMessage(SilKit::Services::Logging::Level::Warn, *this) + .SetMessage("GetServiceDescriptorString queried with an unknown controllerDescriptor.") + .Dispatch(); return ""; } return serviceDescriptor_it->second.to_string(); @@ -146,8 +156,10 @@ void NetworkSimulatorInternal::DiscoveryHandler(SilKit::Core::Discovery::Service if (simulatedNetwork) { auto errorMsg = "NetworkSimulation: Network '" + networkName + "' is already simulated by '" - + fromParticipantName + "'."; - _logger->Error(errorMsg); + + fromParticipantName + "'. "; + _logger->MakeMessage(SilKit::Services::Logging::Level::Error, *this) + .SetMessage(errorMsg) + .Dispatch(); throw SilKitError{errorMsg}; } } diff --git a/SilKit/source/experimental/netsim/NetworkSimulatorInternal.hpp b/SilKit/source/experimental/netsim/NetworkSimulatorInternal.hpp index 8fdf691b4..eab81e9a0 100644 --- a/SilKit/source/experimental/netsim/NetworkSimulatorInternal.hpp +++ b/SilKit/source/experimental/netsim/NetworkSimulatorInternal.hpp @@ -70,7 +70,7 @@ class NetworkSimulatorInternal ControllerDescriptor NextControllerDescriptor(); Core::IParticipantInternal* _participant = nullptr; - SilKit::Services::Logging::ILogger* _logger; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; std::mutex _discoveredNetworksMutex; std::set _discoveredNetworks; std::unordered_map _controllerCountPerNetwork; diff --git a/SilKit/source/experimental/netsim/SimulatedNetworkInternal.cpp b/SilKit/source/experimental/netsim/SimulatedNetworkInternal.cpp index 5820ede52..3a15a065e 100644 --- a/SilKit/source/experimental/netsim/SimulatedNetworkInternal.cpp +++ b/SilKit/source/experimental/netsim/SimulatedNetworkInternal.cpp @@ -18,7 +18,7 @@ SimulatedNetworkInternal::SimulatedNetworkInternal(Core::IParticipantInternal* p const std::string& networkName, SimulatedNetworkType networkType, std::unique_ptr userSimulatedNetwork) : _participant{participant} - , _logger{participant->GetLogger()} + , _logger{participant->GetLoggerInternal()} , _networkName{networkName} , _networkType{networkType} , _userSimulatedNetwork{std::move(userSimulatedNetwork)} @@ -88,9 +88,10 @@ void SimulatedNetworkInternal::AddSimulatedController(const SilKit::Core::Servic } else { - SilKit::Services::Logging::Warn( - _logger, "NetworkSimulation: No simulated controller was provided for controller '{}' on participant '{}'", - controllerName, fromParticipantName); + _logger->MakeMessage(SilKit::Services::Logging::Level::Warn, *this) + .SetMessage("NetworkSimulation: No simulated controller was provided for controller '{}' on participant '{}'", + controllerName, fromParticipantName) + .Dispatch(); } } @@ -106,8 +107,9 @@ auto SimulatedNetworkInternal::LookupControllerDescriptor( return {true, it_controllerDescriptorByServiceId->second}; } } - SilKit::Services::Logging::Error( - _logger, "NetworkSimulation: Cannot associate participant name + service Id to controller descriptor."); + _logger->MakeMessage(SilKit::Services::Logging::Level::Error, *this) + .SetMessage("NetworkSimulation: Cannot associate participant name + service Id to controller descriptor.") + .Dispatch(); return {false, {}}; } diff --git a/SilKit/source/experimental/netsim/SimulatedNetworkInternal.hpp b/SilKit/source/experimental/netsim/SimulatedNetworkInternal.hpp index a33c5b883..4d59adbf8 100644 --- a/SilKit/source/experimental/netsim/SimulatedNetworkInternal.hpp +++ b/SilKit/source/experimental/netsim/SimulatedNetworkInternal.hpp @@ -38,7 +38,7 @@ class SimulatedNetworkInternal auto ExtractControllerTypeName(const SilKit::Core::ServiceDescriptor& serviceDescriptor) -> std::string; Core::IParticipantInternal* _participant = nullptr; - SilKit::Services::Logging::ILogger* _logger; + SilKit::Services::Logging::ILoggerInternal* _logger{nullptr}; std::string _networkName; SimulatedNetworkType _networkType; diff --git a/SilKit/source/experimental/netsim/SimulatedNetworkRouter.cpp b/SilKit/source/experimental/netsim/SimulatedNetworkRouter.cpp index 13d4124d2..3d884a469 100644 --- a/SilKit/source/experimental/netsim/SimulatedNetworkRouter.cpp +++ b/SilKit/source/experimental/netsim/SimulatedNetworkRouter.cpp @@ -24,8 +24,9 @@ SimulatedNetworkRouter::SimulatedNetworkRouter(Core::IParticipantInternal* parti _participant->RegisterSimulator(this, _networkName, _networkType); _participant->AddAsyncSubscriptionsCompletionHandler([this]() { - SilKit::Services::Logging::Debug(_participant->GetLogger(), "Announce simulation of network '{}' of type {}", - _networkName, to_string(_networkType)); + _participant->GetLoggerInternal()->MakeMessage(SilKit::Services::Logging::Level::Debug, *this) + .SetMessage("Announce simulation of network '{}' of type {}", _networkName, to_string(_networkType)) + .Dispatch(); // Announcing the network via ServiceDiscovery. Controllers on that network switch to simulated mode. AnnounceNetwork(_networkName, _networkType); }); @@ -114,9 +115,12 @@ auto SimulatedNetworkRouter::GetSimulatedControllerFromServiceEndpoint(const Sil return it_simulatedControllersByServiceId->second; } } - _participant->GetLogger()->Error( - "NetworkSimulation: No simulated controller was found to route message from participant '" + fromParticipant - + "', serviceId " + std::to_string(fromServiceId)); + + _participant->GetLoggerInternal()->MakeMessage(SilKit::Services::Logging::Level::Error, *this) + .SetMessage("NetworkSimulation: No simulated controller was found to route message from participant '{}' serviceId {}", + fromParticipant, fromServiceId) + .Dispatch(); + return {}; } diff --git a/SilKit/source/experimental/netsim/SimulatedNetworkRouter.hpp b/SilKit/source/experimental/netsim/SimulatedNetworkRouter.hpp index e855f3f97..a0cb66fec 100644 --- a/SilKit/source/experimental/netsim/SimulatedNetworkRouter.hpp +++ b/SilKit/source/experimental/netsim/SimulatedNetworkRouter.hpp @@ -82,8 +82,9 @@ class SimulatedNetworkRouter : public Core::ISimulator } else { - _participant->GetLogger()->Warn("EventProvider has no receiving controller on network '" + _networkName - + "'"); + _participant->GetLoggerInternal()->MakeMessage(SilKit::Services::Logging::Level::Warn, *this) + .SetMessage("EventProvider has no receiving controller on network '{}'", _networkName) + .Dispatch(); } } } From 9c46c6066addbe8f74caf8cc44a9414c6976031a Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Thu, 16 Apr 2026 15:22:35 +0200 Subject: [PATCH 19/23] Cleaning and missing roll out --- SilKit/source/config/YamlReader.cpp | 30 -------------- .../internal/traits/SilKitLoggingTraits.hpp | 11 +----- .../orchestration/LifecycleStates.cpp | 39 +++++++++++++------ 3 files changed, 28 insertions(+), 52 deletions(-) diff --git a/SilKit/source/config/YamlReader.cpp b/SilKit/source/config/YamlReader.cpp index 6236490d5..845acb259 100644 --- a/SilKit/source/config/YamlReader.cpp +++ b/SilKit/source/config/YamlReader.cpp @@ -190,42 +190,12 @@ void YamlReader::Read(SilKit::Config::Sink::Format& obj) } } - void YamlReader::Read(SilKit::Config::Sink& obj) { OptionalRead(obj.type, "Type"); OptionalRead(obj.level, "Level"); OptionalRead(obj.format, "Format"); - - /* auto readTopics = [](std::vector& topicList, - std::vector temp) -> bool - { - for (auto&& topic : temp) - { - SilKit::Services::Logging::Topic enumTopic = SilKit::Services::Logging::from_topic_string(topic); - if (enumTopic == SilKit::Services::Logging::Topic::Invalid) - { - return false; - } - topicList.push_back(enumTopic); - } - return true; - }; - std::vector temp{}; - OptionalRead(temp, "DisabledTopics"); - - if( !readTopics(obj.disabledTopics, temp)) - { - throw MakeConfigurationError("Unknown SilKit::Services::Logging::Topic: "); - } - - OptionalRead(temp, "EnabledTopics"); - if (!readTopics(obj.enabledTopics, temp)) - { - throw MakeConfigurationError("Unknown SilKit::Services::Logging::Topic: "); - }*/ - std::vector temp{}; OptionalRead(temp, "DisabledTopics"); diff --git a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp index 864709caa..8adef9c65 100644 --- a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp @@ -28,9 +28,6 @@ class VAsioRegistry; template class Participant; - - - } } @@ -99,8 +96,6 @@ struct SilKitTopicTrait : TopicTraits { }; - - #define DefineSilKitLoggingTrait_Topic(Component,TopicName) \ template <> \ struct TopicTraits \ @@ -114,9 +109,6 @@ struct SilKitTopicTrait : TopicTraits DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeSyncService, SilKit::Services::Logging::Topic::TimeSync); DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::TimeConfiguration, SilKit::Services::Logging::Topic::TimeConfig); -DefineSilKitLoggingTrait_Topic(SilKit::Core::IParticipantInternal, SilKit::Services::Logging::Topic::Participant); - - template struct TopicTraits> { @@ -125,7 +117,7 @@ struct TopicTraits> return SilKit::Services::Logging::Topic::Participant; } }; - +DefineSilKitLoggingTrait_Topic(SilKit::Core::IParticipantInternal, SilKit::Services::Logging::Topic::Participant); DefineSilKitLoggingTrait_Topic(SilKit::Core::RequestReply::ParticipantReplies, SilKit::Services::Logging::Topic::Participant); DefineSilKitLoggingTrait_Topic(SilKit::Services::Orchestration::LifecycleService, SilKit::Services::Logging::Topic::LifeCycle); @@ -149,7 +141,6 @@ DefineSilKitLoggingTrait_Topic(SilKit::Dashboard::DashboardRestClient, SilKit::S DefineSilKitLoggingTrait_Topic(SilKit::Dashboard::DashboardSystemServiceClient, SilKit::Services::Logging::Topic::Dashboard); DefineSilKitLoggingTrait_Topic(SilKit::Dashboard::DashboardInstance, SilKit::Services::Logging::Topic::Dashboard); - DefineSilKitLoggingTrait_Topic(VSilKit::MetricsProcessor, SilKit::Services::Logging::Topic::Metrics); DefineSilKitLoggingTrait_Topic(SilKit::Experimental::NetworkSimulation::NetworkSimulatorInternal, SilKit::Services::Logging::Topic::NetSim); diff --git a/SilKit/source/services/orchestration/LifecycleStates.cpp b/SilKit/source/services/orchestration/LifecycleStates.cpp index c4c4543af..a91638c0a 100644 --- a/SilKit/source/services/orchestration/LifecycleStates.cpp +++ b/SilKit/source/services/orchestration/LifecycleStates.cpp @@ -99,7 +99,9 @@ void State::InvalidStateTransition(std::string transitionName, bool triggerError } else { - _lifecycleManager->GetLogger()->Warn(ss.str()); + _lifecycleManager->GetLogger()->MakeMessage(Logging::Level::Warn, Logging::Topic::LifeCycle) + .SetMessage(ss.str()) + .Dispatch(); } } @@ -276,7 +278,9 @@ void CommunicationInitializedState::CommunicationInitialized(std::string reason) } break; case SilKit::Services::Orchestration::CallbackResult::Deferred: - _lifecycleManager->GetLogger()->Debug("Deferred CommunicationReady callback."); + _lifecycleManager->GetLogger()->MakeMessage(Logging::Level::Debug, Logging::Topic::LifeCycle) + .SetMessage("Deferred CommunicationReady callback.") + .Dispatch(); break; default: break; @@ -627,8 +631,9 @@ void ShuttingDownState::ShutdownParticipant(std::string reason) auto success = _lifecycleManager->HandleShutdown(); if (!success) { - _lifecycleManager->GetLogger()->Warn( - "ShutdownHandler threw an exception. This is ignored. The participant will now shut down."); + _lifecycleManager->GetLogger()->MakeMessage(Logging::Level::Warn, Logging::Topic::LifeCycle) + .SetMessage("ShutdownHandler threw an exception. This is ignored. The participant will now shut down.") + .Dispatch(); } _lifecycleManager->SetStateAndForwardIntent(_lifecycleManager->GetShutdownState(), &ILifecycleState::ShutdownParticipant, std::move(reason)); @@ -641,7 +646,10 @@ void ShuttingDownState::AbortSimulation(std::string /*reason*/) void ShuttingDownState::ResolveAbortSimulation(std::string /*reason*/) { - _lifecycleManager->GetLogger()->Info("Received abort signal while shutting down - ignoring abort."); + _lifecycleManager->GetLogger() + ->MakeMessage(Logging::Level::Info, Logging::Topic::LifeCycle) + .SetMessage("Received abort signal while shutting down - ignoring abort.") + .Dispatch(); } auto ShuttingDownState::toString() -> std::string @@ -695,9 +703,10 @@ void ShutdownState::ShutdownParticipant(std::string reason) } else { - Logging::Warn(_lifecycleManager->GetLogger(), - "lifecycle failed to shut down correctly - original shutdown reason was '{}'.", - std::move(reason)); + _lifecycleManager->GetLogger() + ->MakeMessage(Logging::Level::Warn, Logging::Topic::LifeCycle) + .SetMessage("lifecycle failed to shut down correctly - original shutdown reason was '{}'.", std::move(reason)) + .Dispatch(); } }); } @@ -709,7 +718,10 @@ void ShutdownState::AbortSimulation(std::string /*reason*/) void ShutdownState::ResolveAbortSimulation(std::string /*reason*/) { - _lifecycleManager->GetLogger()->Info("Received abort signal after shutdown - ignoring abort."); + _lifecycleManager->GetLogger() + ->MakeMessage(Logging::Level::Info, Logging::Topic::LifeCycle) + .SetMessage("Received abort signal after shutdown - ignoring abort.") + .Dispatch(); } auto ShutdownState::toString() -> std::string @@ -752,7 +764,9 @@ void AbortingState::ResolveAbortSimulation(std::string reason) else { std::string msg = "ShutdownHandler threw an exception. This is ignored. The participant will now shut down."; - _lifecycleManager->GetLogger()->Warn(msg); + _lifecycleManager->GetLogger()->MakeMessage(Logging::Level::Warn, Logging::Topic::LifeCycle) + .SetMessage(msg) + .Dispatch(); } _lifecycleManager->ShutdownAfterAbort(std::move(reason)); } @@ -804,8 +818,9 @@ void ErrorState::ResolveAbortSimulation(std::string reason) void ErrorState::Error(std::string reason) { - _lifecycleManager->GetLogger()->Warn("Received error transition within error state. Original reason: " - + std::move(reason)); + _lifecycleManager->GetLogger()->MakeMessage(Logging::Level::Warn, Logging::Topic::LifeCycle) + .SetMessage("Received error transition within error state. Original reason: " + std::move(reason)) + .Dispatch(); } auto ErrorState::toString() -> std::string From eaa18ac91004f951f04220f625b2edef7710fd58 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Mon, 20 Apr 2026 13:13:57 +0200 Subject: [PATCH 20/23] Cleanups and fixes --- .../silkit/services/logging/string_utils.hpp | 15 +++ SilKit/source/services/logging/Logger.cpp | 102 ++++++++---------- SilKit/source/services/logging/Logger.hpp | 30 +++--- 3 files changed, 75 insertions(+), 72 deletions(-) diff --git a/SilKit/include/silkit/services/logging/string_utils.hpp b/SilKit/include/silkit/services/logging/string_utils.hpp index 3a2478a50..07802dc78 100644 --- a/SilKit/include/silkit/services/logging/string_utils.hpp +++ b/SilKit/include/silkit/services/logging/string_utils.hpp @@ -139,6 +139,15 @@ std::ostream& operator<<(std::ostream& outStream, const Topic& topic) case Topic::Tracing: outStream << "tracing"; break; + case Topic::Metrics: + outStream << "metrics"; + break; + case Topic::Dashboard: + outStream << "dashboard"; + break; + case Topic::NetSim: + outStream << "netsim"; + break; case Topic::None: outStream << "none"; break; @@ -179,6 +188,12 @@ inline Topic from_topic_string(const std::string& topicStr) return Topic::Controller; if (topic == "tracing") return Topic::Tracing; + if (topic == "metrics") + return Topic::Metrics; + if (topic == "netsim") + return Topic::NetSim; + if (topic == "dashboard") + return Topic::Dashboard; return Topic::Invalid; } /* diff --git a/SilKit/source/services/logging/Logger.cpp b/SilKit/source/services/logging/Logger.cpp index 2fe0d1b4a..e11ffd711 100644 --- a/SilKit/source/services/logging/Logger.cpp +++ b/SilKit/source/services/logging/Logger.cpp @@ -301,7 +301,7 @@ Logger::Logger(const std::string& participantName, Config::Logging config) for (const auto& pair : _spdlogLogger) { - auto log_level = to_spdlog(Services::Logging::Level::Trace /* pair.second.level*/); + auto log_level = to_spdlog(pair.second.level); pair.first->set_level(log_level); if (pair.second.type == Config::Sink::Type::Stdout) @@ -361,49 +361,69 @@ Logger::Logger(const std::string& participantName, Config::Logging config) -void Logger::ProcessLoggerMessage(const LoggerMessage& msg) +void Logger::DispatchToSinks(log_clock::time_point now, Level level, Topic topic, + const std::function& formatter, + const std::function&, log_clock::time_point)>& remoteDispatcher) { - const auto now = log_clock::now(); - - for (const auto& pair : _spdlogLogger) { - if (!(pair.second.level <= msg.GetLevel())) + if (!(pair.second.level <= level)) { continue; } - if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, msg.GetTopic()))) + if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, topic))) { continue; } - if (pair.second.format == Config::Sink::Format::Json) - { - JsonLogMessage myJsonMsg{msg.GetMsgString(), msg.GetKeyValues(), msg.GetTopic()}; - pair.first->log(now, spdlog::source_loc{}, to_spdlog(msg.GetLevel()), fmt::format("{}", myJsonMsg)); - } - else - { - SimpleLogMessage myMsg{msg.GetMsgString(), msg.GetKeyValues(), msg.GetTopic()}; - pair.first->log(now, spdlog::source_loc{}, to_spdlog(msg.GetLevel()), fmt::format("{}", myMsg)); - } + auto formatted = formatter(pair.second.format); + pair.first->log(now, spdlog::source_loc{}, to_spdlog(level), formatted); } for (const auto& pair : _remoteLogger) { - if (!(pair.second.level <= msg.GetLevel())) + if (!(pair.second.level <= level)) { continue; } - if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, msg.GetTopic()))) + if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, topic))) { continue; } - pair.first->Log(now, msg); + + if (remoteDispatcher) + { + remoteDispatcher(pair.first, now); + } + else + { + pair.first->Log(now, level, topic, formatter(Config::Sink::Format::Simple)); + } } +} +void Logger::ProcessLoggerMessage(const LoggerMessage& msg) +{ + const auto now = log_clock::now(); + + DispatchToSinks(now, msg.GetLevel(), msg.GetTopic(), + [&msg](Config::Sink::Format format) -> std::string { + if (format == Config::Sink::Format::Json) + { + JsonLogMessage myJsonMsg{msg.GetMsgString(), msg.GetKeyValues(), msg.GetTopic()}; + return fmt::format("{}", myJsonMsg); + } + else + { + SimpleLogMessage myMsg{msg.GetMsgString(), msg.GetKeyValues(), msg.GetTopic()}; + return fmt::format("{}", myMsg); + } + }, + [&msg](const std::shared_ptr& remote, log_clock::time_point tp) { + remote->Log(tp, msg); + }); } void Logger::LogReceivedMsg(const LogMsg& msg) @@ -417,7 +437,6 @@ void Logger::LogReceivedMsg(const LogMsg& msg) auto fmt{fmt::format("{}", jsonMsg)}; auto spdlog_msg = to_spdlog(msg, fmt); - for (auto&& sink : pair.first->sinks()) { if (to_spdlog(msg.level) < sink->level()) @@ -458,50 +477,21 @@ void Logger::Log(Level level, const std::string& msg) void Logger::Log(Level level, Topic topic, const std::string& msg) { + const auto now = log_clock::now(); - const auto now = log_clock::now(); - - - for (const auto& pair : _spdlogLogger) - { - if (!(pair.second.level <= level)) - { - continue; - } - - if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, topic))) - { - continue; - } - - if (pair.second.format == Config::Sink::Format::Json) + DispatchToSinks(now, level, topic, [&msg, topic](Config::Sink::Format format) -> std::string { + if (format == Config::Sink::Format::Json) { JsonString jsonString{msg, topic}; - pair.first->log(now, spdlog::source_loc{}, to_spdlog(level), fmt::format("{}", jsonString)); + return fmt::format("{}", jsonString); } else { - pair.first->log(now, spdlog::source_loc{}, to_spdlog(level), - fmt::format("[{}] {}", to_string(topic), msg)); + return fmt::format("[{}] {}", to_string(topic), msg); } - } - - for (const auto& pair : _remoteLogger) - { - if (!(pair.second.level <= level)) - { - continue; - } - - if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, topic))) - { - continue; - } - pair.first->Log(now, level, topic, msg); - } + }); } - void Logger::Trace(const std::string& msg) { Log(Level::Trace, msg); diff --git a/SilKit/source/services/logging/Logger.hpp b/SilKit/source/services/logging/Logger.hpp index f8600a03f..7d00321bf 100755 --- a/SilKit/source/services/logging/Logger.hpp +++ b/SilKit/source/services/logging/Logger.hpp @@ -179,37 +179,35 @@ class Logger : public ILoggerInternal void LogReceivedMsg(const LogMsg& msg) override; private: - // ---------------------------------------- // Private members Config::Logging _config; - - std::map, Config::Sink> _spdlogLogger; std::map, Config::Sink> _remoteLogger; + // Private methods + void DispatchToSinks(log_clock::time_point now, Level level, Topic topic, + const std::function& formatter, + const std::function&, log_clock::time_point)>& remoteDispatcher = nullptr); bool IsTopicEnabled(const std::vector& enabledTopics, - const std::vector& disabledTopics, + const std::vector& disabledTopics, const Topic msgTopic) const { - auto returnVal = true; - auto inEnabledTopics = false; - auto inDisabledTopics = false; - - if (!enabledTopics.empty()) + // Explicitly disabled topics are always filtered out + if (!disabledTopics.empty() + && std::find(disabledTopics.begin(), disabledTopics.end(), msgTopic) != disabledTopics.end()) { - inEnabledTopics = std::find(enabledTopics.begin(), enabledTopics.end(), msgTopic) != enabledTopics.end(); + return false; } - if (!disabledTopics.empty()) + // If an allow-list is specified, only those topics pass + if (!enabledTopics.empty()) { - inDisabledTopics = std::find(disabledTopics.begin(), disabledTopics.end(), msgTopic) - != disabledTopics.end(); + return std::find(enabledTopics.begin(), enabledTopics.end(), msgTopic) != enabledTopics.end(); } - returnVal = !inDisabledTopics && (inEnabledTopics == !enabledTopics.empty()); - - return returnVal; + // No filter configured - allow everything + return true; } }; From 04816b6ac87a68a61ed0398790511e614a1624d5 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Tue, 21 Apr 2026 10:44:42 +0200 Subject: [PATCH 21/23] Fix, update missing logger calls --- SilKit/source/dashboard/DashboardInstance.cpp | 8 ++++++-- SilKit/source/services/orchestration/TimeSyncService.cpp | 3 ++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/SilKit/source/dashboard/DashboardInstance.cpp b/SilKit/source/dashboard/DashboardInstance.cpp index 092197e59..612da67ce 100644 --- a/SilKit/source/dashboard/DashboardInstance.cpp +++ b/SilKit/source/dashboard/DashboardInstance.cpp @@ -96,11 +96,15 @@ class EventQueueWorkerThread auto bulkUpdateAvailable = _dashboardRestClient->IsBulkUpdateSupported(); if (bulkUpdateAvailable) { - _logger->Debug("Dashboard bulk-updates are available"); + _logger->MakeMessage(Level::Debug, *this) + .SetMessage("Dashboard bulk-updates are available") + .Dispatch(); } else { - _logger->Debug("Dashboard bulk-updates are not available, falling back to individual requests"); + _logger->MakeMessage(Level::Debug, *this) + .SetMessage("Dashboard bulk-updates are not available, falling back to individual requests") + .Dispatch(); } return bulkUpdateAvailable; diff --git a/SilKit/source/services/orchestration/TimeSyncService.cpp b/SilKit/source/services/orchestration/TimeSyncService.cpp index e2b23484b..d10c1cb77 100644 --- a/SilKit/source/services/orchestration/TimeSyncService.cpp +++ b/SilKit/source/services/orchestration/TimeSyncService.cpp @@ -635,7 +635,8 @@ void TimeSyncService::InitializeTimeSyncPolicy(bool isSynchronizingVirtualTime) } catch (const std::exception& e) { - _logger->Critical(e.what()); + _logger->MakeMessage(Logging::Level::Critical, *this).SetMessage(e.what()) + .Dispatch(); throw; } } From fb1baa7e62c128d77296ca23deea373a954134fd Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Tue, 21 Apr 2026 10:45:26 +0200 Subject: [PATCH 22/23] Fix, clean public logger interface --- .../detail/impl/services/logging/Logger.hpp | 53 ++----------------- .../silkit/services/logging/ILogger.hpp | 26 --------- SilKit/source/capi/CapiLogger.cpp | 6 +-- .../services/logging/ILoggerInternal.hpp | 22 ++++++++ 4 files changed, 28 insertions(+), 79 deletions(-) diff --git a/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp b/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp index 3985f58e6..1fef2d566 100644 --- a/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp +++ b/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp @@ -5,6 +5,7 @@ #pragma once #include "silkit/capi/Logger.h" + #include "silkit/services/logging/ILogger.hpp" @@ -23,26 +24,18 @@ class Logger : public SilKit::Services::Logging::ILogger inline ~Logger() override = default; inline void Log(SilKit::Services::Logging::Level level, const std::string& msg) override; - inline void Log(SilKit::Services::Logging::Level level, SilKit::Services::Logging::Topic topic, - const std::string& msg) override; inline void Trace(const std::string& msg) override; - inline void Trace(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline void Debug(const std::string& msg) override; - inline void Debug(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline void Info(const std::string& msg) override; - inline void Info(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline void Warn(const std::string& msg) override; - inline void Warn(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline void Error(const std::string& msg) override; - inline void Error(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline void Critical(const std::string& msg) override; - inline void Critical(const SilKit::Services::Logging::Topic topic, const std::string& msg) override; inline auto GetLogLevel() const -> SilKit::Services::Logging::Level override; @@ -82,20 +75,10 @@ Logger::Logger(SilKit_Vendor_Vector_SilKitRegistry* silKitRegistry) } void Logger::Log(SilKit::Services::Logging::Level level, const std::string& msg) -{ - Log(level, SilKit::Services::Logging::Topic::None, msg); -} - -void Logger::Log(SilKit::Services::Logging::Level level, SilKit::Services::Logging::Topic topic, - const std::string& msg) { const auto loggingLevel = static_cast(level); - std::string formatted; - // formatted = "[" + topic + "] " + msg; // todo logger topic - formatted = msg; - - const auto returnCode = SilKit_Logger_Log(_logger, loggingLevel, formatted.c_str()); + const auto returnCode = SilKit_Logger_Log(_logger, loggingLevel, msg.c_str()); ThrowOnError(returnCode); } @@ -105,66 +88,36 @@ void Logger::Trace(const std::string& msg) ThrowOnError(returnCode); } -void Logger::Trace(SilKit::Services::Logging::Topic topic, const std::string& msg) -{ - Log(SilKit::Services::Logging::Level::Trace, topic, msg); -} - void Logger::Debug(const std::string& msg) { const auto returnCode = SilKit_Logger_Log(_logger, SilKit_LoggingLevel_Debug, msg.c_str()); ThrowOnError(returnCode); } -void Logger::Debug(SilKit::Services::Logging::Topic topic, const std::string& msg) -{ - Log(SilKit::Services::Logging::Level::Debug, topic, msg); -} - void Logger::Info(const std::string& msg) { const auto returnCode = SilKit_Logger_Log(_logger, SilKit_LoggingLevel_Info, msg.c_str()); ThrowOnError(returnCode); } -void Logger::Info(SilKit::Services::Logging::Topic topic, const std::string& msg) -{ - Log(SilKit::Services::Logging::Level::Info, topic, msg); -} - void Logger::Warn(const std::string& msg) { const auto returnCode = SilKit_Logger_Log(_logger, SilKit_LoggingLevel_Warn, msg.c_str()); ThrowOnError(returnCode); } -void Logger::Warn(SilKit::Services::Logging::Topic topic, const std::string& msg) -{ - Log(SilKit::Services::Logging::Level::Warn, topic, msg); -} - void Logger::Error(const std::string& msg) { const auto returnCode = SilKit_Logger_Log(_logger, SilKit_LoggingLevel_Error, msg.c_str()); ThrowOnError(returnCode); } -void Logger::Error(SilKit::Services::Logging::Topic topic, const std::string& msg) -{ - Log(SilKit::Services::Logging::Level::Error, topic, msg); -} - void Logger::Critical(const std::string& msg) { const auto returnCode = SilKit_Logger_Log(_logger, SilKit_LoggingLevel_Critical, msg.c_str()); ThrowOnError(returnCode); } -void Logger::Critical(SilKit::Services::Logging::Topic topic, const std::string& msg) -{ - Log(SilKit::Services::Logging::Level::Critical, topic, msg); -} - auto Logger::GetLogLevel() const -> SilKit::Services::Logging::Level { SilKit_LoggingLevel loggingLevel{SilKit_LoggingLevel_Info}; @@ -179,4 +132,4 @@ auto Logger::GetLogLevel() const -> SilKit::Services::Logging::Level } // namespace Services } // namespace Impl DETAIL_SILKIT_DETAIL_VN_NAMESPACE_CLOSE -} // namespace SilKit +} // namespace SilKit \ No newline at end of file diff --git a/SilKit/include/silkit/services/logging/ILogger.hpp b/SilKit/include/silkit/services/logging/ILogger.hpp index d2a60d711..224950244 100755 --- a/SilKit/include/silkit/services/logging/ILogger.hpp +++ b/SilKit/include/silkit/services/logging/ILogger.hpp @@ -24,50 +24,24 @@ class ILogger */ virtual void Log(Level level, const std::string& msg) = 0; - /*! \brief Log a message with a specified level and topic/category - * - * \param level The log level for the message - * \param topic The topic or category for the message (UTF-8). - * \param msg The message which shall be logged (UTF-8). - */ - virtual void Log(Level level, Topic topic, const std::string& msg) = 0; - //! \brief Log a message with log level trace. virtual void Trace(const std::string& msg) = 0; - //! \brief Log a message with log level trace and a topic/category. - virtual void Trace(Topic topic, const std::string& msg) = 0; - //! \brief Log a message with log level debug. virtual void Debug(const std::string& msg) = 0; - //! \brief Log a message with log level debug and a topic/category. - virtual void Debug(Topic topic, const std::string& msg) = 0; - //! \brief Log a message with log level info. virtual void Info(const std::string& msg) = 0; - //! \brief Log a message with log level info and a topic/category. - virtual void Info(Topic topic, const std::string& msg) = 0; - //! \brief Log a message with log level warn. virtual void Warn(const std::string& msg) = 0; - //! \brief Log a message with log level warn and a topic/category. - virtual void Warn(Topic topic, const std::string& msg) = 0; - //! \brief Log a message with log level error. virtual void Error(const std::string& msg) = 0; - //! \brief Log a message with log level error and a topic/category. - virtual void Error(Topic topic, const std::string& msg) = 0; - //! \brief Log a message with log level critical. virtual void Critical(const std::string& msg) = 0; - //! \brief Log a message with log level critical and a topic/category. - virtual void Critical(Topic topic, const std::string& msg) = 0; - //! \brief Get the lowest configured log level of all sinks virtual Level GetLogLevel() const = 0; }; diff --git a/SilKit/source/capi/CapiLogger.cpp b/SilKit/source/capi/CapiLogger.cpp index 475d85423..ea3f26fe9 100644 --- a/SilKit/source/capi/CapiLogger.cpp +++ b/SilKit/source/capi/CapiLogger.cpp @@ -4,8 +4,7 @@ #include "silkit/capi/SilKit.h" #include "silkit/SilKit.hpp" -#include "silkit/services/logging/ILogger.hpp" - +#include "ILoggerInternal.hpp" #include "CapiImpl.hpp" #include @@ -17,7 +16,8 @@ try ASSERT_VALID_POINTER_PARAMETER(self); ASSERT_VALID_POINTER_PARAMETER(message); - auto logger = reinterpret_cast(self); + auto loggerPublic = reinterpret_cast(self); + auto logger = dynamic_cast(loggerPublic); auto enumLevel = static_cast(level); auto topic = SilKit::Services::Logging::Topic::User; diff --git a/SilKit/source/services/logging/ILoggerInternal.hpp b/SilKit/source/services/logging/ILoggerInternal.hpp index 07739e9fa..b7596c944 100644 --- a/SilKit/source/services/logging/ILoggerInternal.hpp +++ b/SilKit/source/services/logging/ILoggerInternal.hpp @@ -25,6 +25,28 @@ struct ILoggerInternal : ILogger virtual void ProcessLoggerMessage(const LoggerMessage& msg) = 0; virtual void LogReceivedMsg(const LogMsg& msg) = 0; + /*! \brief Log a message with a specified level and topic/category + * + * \param level The log level for the message + * \param topic The topic or category for the message (UTF-8). + * \param msg The message which shall be logged (UTF-8). + */ + virtual void Log(Level level, Topic topic, const std::string& msg) = 0; + + //! \brief Log a message with log level trace and a topic/category. + virtual void Trace(Topic topic, const std::string& msg) = 0; + //! \brief Log a message with log level debug and a topic/category. + virtual void Debug(Topic topic, const std::string& msg) = 0; + //! \brief Log a message with log level info and a topic/category. + virtual void Info(Topic topic, const std::string& msg) = 0; + //! \brief Log a message with log level warn and a topic/category. + virtual void Warn(Topic topic, const std::string& msg) = 0; + //! \brief Log a message with log level error and a topic/category. + virtual void Error(Topic topic, const std::string& msg) = 0; + //! \brief Log a message with log level critical and a topic/category. + virtual void Critical(Topic topic, const std::string& msg) = 0; + + template LoggerMessage MakeMessage(Level level, ServiceT&) { From 6a0d2ef9c29af60292e9b0472f5c0ebf2b573835 Mon Sep 17 00:00:00 2001 From: "Becker, Lukas" Date: Tue, 21 Apr 2026 16:34:01 +0200 Subject: [PATCH 23/23] Fix review requests --- .../detail/impl/services/logging/Logger.hpp | 2 +- .../silkit/services/logging/string_utils.hpp | 36 +++++----- SilKit/source/config/Configuration.hpp | 2 +- SilKit/source/config/YamlReader.cpp | 46 ++++++------ SilKit/source/config/YamlReader.hpp | 1 + SilKit/source/core/internal/internal_fwd.hpp | 32 +++++++++ .../internal/traits/SilKitLoggingTraits.hpp | 71 +------------------ .../io/impl/AsioGenericRawByteStream.cpp | 2 +- SilKit/source/services/logging/Logger.cpp | 4 +- SilKit/source/services/logging/Logger.hpp | 22 +++++- .../source/services/logging/LoggerMessage.hpp | 6 +- .../source/services/logging/LoggingSerdes.cpp | 3 +- 12 files changed, 102 insertions(+), 125 deletions(-) diff --git a/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp b/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp index 1fef2d566..11f8c13c8 100644 --- a/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp +++ b/SilKit/include/silkit/detail/impl/services/logging/Logger.hpp @@ -132,4 +132,4 @@ auto Logger::GetLogLevel() const -> SilKit::Services::Logging::Level } // namespace Services } // namespace Impl DETAIL_SILKIT_DETAIL_VN_NAMESPACE_CLOSE -} // namespace SilKit \ No newline at end of file +} // namespace SilKit diff --git a/SilKit/include/silkit/services/logging/string_utils.hpp b/SilKit/include/silkit/services/logging/string_utils.hpp index 07802dc78..1053adada 100644 --- a/SilKit/include/silkit/services/logging/string_utils.hpp +++ b/SilKit/include/silkit/services/logging/string_utils.hpp @@ -101,58 +101,58 @@ std::ostream& operator<<(std::ostream& outStream, const Topic& topic) switch (topic) { case Topic::User: - outStream << "user"; + outStream << "User"; break; case Topic::TimeSync: - outStream << "timesync"; + outStream << "TimeSync"; break; case Topic::LifeCycle: - outStream << "lifecycle"; + outStream << "LifeCycle"; break; case Topic::SystemState: - outStream << "systemstate"; + outStream << "SystemState"; break; case Topic::MessageTracing: - outStream << "messagetracing"; + outStream << "MessageTracing"; break; case Topic::ServiceDiscovery: - outStream << "servicediscovery"; + outStream << "ServiceDiscovery"; break; case Topic::Participant: - outStream << "participant"; + outStream << "Participant"; break; case Topic::Asio: - outStream << "asio"; + outStream << "Asio"; break; case Topic::TimeConfig: - outStream << "timeconfig"; + outStream << "TimeConfig"; break; case Topic::RequestReply: - outStream << "requestreply"; + outStream << "RequestReply"; break; case Topic::SystemMonitor: - outStream << "systemmonitor"; + outStream << "SystemMonitor"; break; case Topic::Controller: - outStream << "controller"; + outStream << "Controller"; break; case Topic::Tracing: - outStream << "tracing"; + outStream << "Tracing"; break; case Topic::Metrics: - outStream << "metrics"; + outStream << "Metrics"; break; case Topic::Dashboard: - outStream << "dashboard"; + outStream << "Dashboard"; break; case Topic::NetSim: - outStream << "netsim"; + outStream << "NetSim"; break; case Topic::None: - outStream << "none"; + outStream << "None"; break; default: - outStream << "invalid"; + outStream << "Invalid"; } return outStream; } diff --git a/SilKit/source/config/Configuration.hpp b/SilKit/source/config/Configuration.hpp index 73b0c9839..b654c6d99 100644 --- a/SilKit/source/config/Configuration.hpp +++ b/SilKit/source/config/Configuration.hpp @@ -85,7 +85,7 @@ struct Sink std::vector enabledTopics{}; }; -//! \brief Logger serviceoo +//! \brief Logger service struct Logging { bool logFromRemotes{false}; diff --git a/SilKit/source/config/YamlReader.cpp b/SilKit/source/config/YamlReader.cpp index 845acb259..0614dba49 100644 --- a/SilKit/source/config/YamlReader.cpp +++ b/SilKit/source/config/YamlReader.cpp @@ -24,7 +24,6 @@ void YamlReader::Read(SilKit::Services::MatchingLabel::Kind& value) throw MakeConfigurationError("MatchingLabel::Kind should be an integer of Mandatory(2)|Optional(1)."); } - void YamlReader::Read(SilKit::Services::Logging::Level& obj) { if (IsString("Critical")) @@ -47,6 +46,25 @@ void YamlReader::Read(SilKit::Services::Logging::Level& obj) } } +void YamlReader::Read(SilKit::Services::Logging::Topic& obj) +{ + if (!IsScalar() ) + { + throw MakeConfigurationError("Topic should be a string."); + } + + std::string value; + Read(value); + + const auto topic = SilKit::Services::Logging::from_topic_string(value); + + if (topic == SilKit::Services::Logging::Topic::Invalid) + { + throw MakeConfigurationError("Unknown SilKit::Services::Logging::Topic"); + } + obj = topic; +} + void YamlReader::Read(SilKit::Services::Flexray::FlexrayClusterParameters& obj) { // Parse parameters as an int value; uint8_t would be interpreted as a character @@ -195,30 +213,8 @@ void YamlReader::Read(SilKit::Config::Sink& obj) OptionalRead(obj.type, "Type"); OptionalRead(obj.level, "Level"); OptionalRead(obj.format, "Format"); - - std::vector temp{}; - OptionalRead(temp, "DisabledTopics"); - - for (auto&& topic : temp) - { - SilKit::Services::Logging::Topic enumTopic = SilKit::Services::Logging::from_topic_string(topic); - if (enumTopic == SilKit::Services::Logging::Topic::Invalid) - { - throw MakeConfigurationError("Unknown SilKit::Services::Logging::Topic: "); - } - obj.disabledTopics.push_back(enumTopic); - } - temp.clear(); - OptionalRead(temp, "EnabledTopics"); - for (auto&& topic : temp) - { - SilKit::Services::Logging::Topic enumTopic = SilKit::Services::Logging::from_topic_string(topic); - if (enumTopic == SilKit::Services::Logging::Topic::Invalid) - { - throw MakeConfigurationError("Unknown SilKit::Services::Logging::Topic: "); - } - obj.enabledTopics.push_back(enumTopic); - } + OptionalRead(obj.disabledTopics, "DisabledTopics"); + OptionalRead(obj.enabledTopics, "EnabledTopics"); if (obj.type == SilKit::Config::Sink::Type::File) { diff --git a/SilKit/source/config/YamlReader.hpp b/SilKit/source/config/YamlReader.hpp index 8e74b4fea..5e44e88de 100644 --- a/SilKit/source/config/YamlReader.hpp +++ b/SilKit/source/config/YamlReader.hpp @@ -283,6 +283,7 @@ struct YamlReader : BasicYamlReader void Read(SilKit::Services::MatchingLabel& value); void Read(SilKit::Services::MatchingLabel::Kind& value); void Read(SilKit::Services::Logging::Level& obj); + void Read(SilKit::Services::Logging::Topic& obj); void Read(SilKit::Services::Flexray::FlexrayClusterParameters& obj); void Read(SilKit::Services::Flexray::FlexrayNodeParameters& obj); void Read(SilKit::Services::Flexray::FlexrayTxBufferConfig& obj); diff --git a/SilKit/source/core/internal/internal_fwd.hpp b/SilKit/source/core/internal/internal_fwd.hpp index cbcb4e81e..416b09d69 100644 --- a/SilKit/source/core/internal/internal_fwd.hpp +++ b/SilKit/source/core/internal/internal_fwd.hpp @@ -4,18 +4,39 @@ #pragma once +namespace VSilKit { +class SystemStateTracker; +class ConnectPeer; +class MetricsProcessor; +} // namespace VSilKit namespace SilKit { +namespace Dashboard { +class DashboardRestClient; +class DashboardSystemServiceClient; +class DashboardInstance; +} // namespace Dashboard +namespace Experimental { +namespace NetworkSimulation { +class NetworkSimulatorInternal; +class SimulatedNetworkInternal; +class SimulatedNetworkRouter; +} // namespace NetworkSimulation +} // namespace Experimental namespace Services { namespace Can { +class CanController; class IMsgForCanSimulator; } // namespace Can namespace Ethernet { +class EthController; class IMsgForEthSimulator; } // namespace Ethernet namespace Flexray { +class FlexrayController; class IMsgForFlexrayBusSimulator; } // namespace Flexray namespace Lin { +class LinController; class IMsgForLinSimulator; } // namespace Lin namespace PubSub { @@ -32,15 +53,26 @@ class RpcServerInternal; class RpcDiscoverer; } // namespace Rpc namespace Orchestration { +class TimeConfiguration; +class SystemMonitor; +class LifecycleManagement; class LifecycleService; class TimeSyncService; } // namespace Orchestration } // namespace Services namespace Core { +class IParticipantInternal; +class ConnectKnownParticipants; +class RemoteConnectionManager; +class VAsioConnection; +class VAsioRegistry; +template +class Participant; namespace Discovery { class IServiceDiscovery; } // namespace Discovery namespace RequestReply { +class ParticipantReplies; class IRequestReplyService; class IParticipantReplies; } // namespace RequestReply diff --git a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp index 8adef9c65..7ceda9b08 100644 --- a/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp +++ b/SilKit/source/core/internal/traits/SilKitLoggingTraits.hpp @@ -3,80 +3,11 @@ // SPDX-License-Identifier: MIT #pragma once + #include "internal_fwd.hpp" #include "silkit/services/logging/LoggingDatatypes.hpp" -namespace VSilKit { -class SystemStateTracker; -class ConnectPeer; -class MetricsProcessor; -} - -namespace SilKit { -namespace Core { - -namespace RequestReply { -class ParticipantReplies; -} - -class IParticipantInternal; -class ConnectKnownParticipants; -class RemoteConnectionManager; -class VAsioConnection; -class VAsioRegistry; - -template -class Participant; -} -} - -namespace SilKit { -namespace Services { - -namespace Lin { -class LinController; -} -namespace Can { -class CanController; -} -namespace Ethernet { -class EthController; -} -namespace Flexray{ -class FlexrayController; -} - - -namespace Orchestration { -class TimeSyncService; -class TimeConfiguration; -class SystemMonitor; -class LifecycleService; - -class LifecycleManagement; -} -} -} - -namespace SilKit { -namespace Dashboard { -class DashboardRestClient; -class DashboardSystemServiceClient; -class DashboardInstance; -} -} - -namespace SilKit { -namespace Experimental { -namespace NetworkSimulation { -class NetworkSimulatorInternal; -class SimulatedNetworkInternal; -class SimulatedNetworkRouter; -} -} -} - namespace SilKit { namespace Core { diff --git a/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp b/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp index b13569549..4fe99f4c4 100644 --- a/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp +++ b/SilKit/source/core/vasio/io/impl/AsioGenericRawByteStream.cpp @@ -270,7 +270,7 @@ void AsioGenericRawByteStream::HandleShutdownOrError() _socket.close(errorCode); if (errorCode) { - _logger->MakeMessage(Log::Level::Warn, Log::Topic::Asio) + _logger->MakeMessage(Log::Level::Warn, *this) .SetMessage("AsioGenericRawByteStream::HandleShutdownOrError: socket close failed: {}", errorCode.message()) .Dispatch(); diff --git a/SilKit/source/services/logging/Logger.cpp b/SilKit/source/services/logging/Logger.cpp index e11ffd711..9de154a25 100644 --- a/SilKit/source/services/logging/Logger.cpp +++ b/SilKit/source/services/logging/Logger.cpp @@ -372,7 +372,7 @@ void Logger::DispatchToSinks(log_clock::time_point now, Level level, Topic topic continue; } - if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, topic))) + if (IsTopicDisabled(pair.second.enabledTopics, pair.second.disabledTopics, topic)) { continue; } @@ -388,7 +388,7 @@ void Logger::DispatchToSinks(log_clock::time_point now, Level level, Topic topic continue; } - if (!(IsTopicEnabled(pair.second.enabledTopics, pair.second.disabledTopics, topic))) + if (IsTopicDisabled(pair.second.enabledTopics, pair.second.disabledTopics, topic)) { continue; } diff --git a/SilKit/source/services/logging/Logger.hpp b/SilKit/source/services/logging/Logger.hpp index 7d00321bf..1503319fa 100755 --- a/SilKit/source/services/logging/Logger.hpp +++ b/SilKit/source/services/logging/Logger.hpp @@ -194,8 +194,7 @@ class Logger : public ILoggerInternal const Topic msgTopic) const { // Explicitly disabled topics are always filtered out - if (!disabledTopics.empty() - && std::find(disabledTopics.begin(), disabledTopics.end(), msgTopic) != disabledTopics.end()) + if (std::find(disabledTopics.begin(), disabledTopics.end(), msgTopic) != disabledTopics.end()) { return false; } @@ -209,6 +208,25 @@ class Logger : public ILoggerInternal // No filter configured - allow everything return true; } + + bool IsTopicDisabled(const std::vector& enabledTopics, + const std::vector& disabledTopics, const Topic msgTopic) const + { + // Explicitly disabled topics are always filtered out + if (std::find(disabledTopics.begin(), disabledTopics.end(), msgTopic) != disabledTopics.end()) + { + return true; + } + + // If an allow-list is specified, only those topics pass + if (!enabledTopics.empty()) + { + return !(std::find(enabledTopics.begin(), enabledTopics.end(), msgTopic) != enabledTopics.end()); + } + + // No filter configured - allow everything + return false; + } }; } // namespace Logging diff --git a/SilKit/source/services/logging/LoggerMessage.hpp b/SilKit/source/services/logging/LoggerMessage.hpp index de4cf7020..42bcfbd1a 100644 --- a/SilKit/source/services/logging/LoggerMessage.hpp +++ b/SilKit/source/services/logging/LoggerMessage.hpp @@ -141,8 +141,7 @@ class LoggerMessage } } - - void SetKeyValue(const std::vector& labels) + void SetKeyValue(const std::vector& labels) { if (_logger->GetLogLevel() <= _level) { @@ -150,7 +149,7 @@ class LoggerMessage } } - void SetKeyValue(const Core::ServiceDescriptor& descriptor) + void SetKeyValue(const Core::ServiceDescriptor& descriptor) { if (_logger->GetLogLevel() <= _level) { @@ -161,7 +160,6 @@ class LoggerMessage } } - auto GetLevel() const -> Level { return _level; diff --git a/SilKit/source/services/logging/LoggingSerdes.cpp b/SilKit/source/services/logging/LoggingSerdes.cpp index 69d1e097b..ae89a09da 100644 --- a/SilKit/source/services/logging/LoggingSerdes.cpp +++ b/SilKit/source/services/logging/LoggingSerdes.cpp @@ -24,7 +24,8 @@ inline MessageBuffer& operator>>(MessageBuffer& buffer, SourceLoc& sourceLoc) inline MessageBuffer& operator<<(MessageBuffer& buffer, const LogMsg& msg) { - buffer << msg.loggerName << msg.level << msg.time << msg.source << msg.payload << msg.keyValues << msg.topic; + buffer << msg.loggerName << msg.level << msg.time << msg.source << msg.payload << msg.keyValues + << SilKit::Services::Logging:to_string(msg.topic); return buffer; } inline MessageBuffer& operator>>(MessageBuffer& buffer, LogMsg& msg)