logger.hpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. //
  2. // Copyright (c) 2023-2025 Ivica Siladic, Bruno Iljazovic, Korina Simicevic
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. #ifndef BOOST_MQTT5_LOGGER_HPP
  8. #define BOOST_MQTT5_LOGGER_HPP
  9. #include <boost/mqtt5/logger_traits.hpp>
  10. #include <boost/mqtt5/property_types.hpp>
  11. #include <boost/mqtt5/reason_codes.hpp>
  12. #include <boost/mqtt5/types.hpp>
  13. #include <boost/mqtt5/detail/traits.hpp>
  14. #include <boost/asio/ip/tcp.hpp>
  15. #include <boost/system/error_code.hpp>
  16. #include <boost/type_traits/remove_cv_ref.hpp>
  17. #include <cstdint>
  18. #include <iostream>
  19. #include <string_view>
  20. namespace boost::mqtt5 {
  21. namespace asio = boost::asio;
  22. using error_code = boost::system::error_code;
  23. /**
  24. * \brief Represents the severity level of log messages.
  25. */
  26. enum class log_level : uint8_t {
  27. /** Error messages that indicate serious issues. **/
  28. error = 1,
  29. /** Warnings that indicate potential problems or non-critical issues. **/
  30. warning,
  31. /** Informational messages that highlight normal application behaviour and events. **/
  32. info,
  33. /** Detailed messages useful for diagnosing issues. **/
  34. debug
  35. };
  36. /**
  37. * \brief A logger class that can used by the \ref mqtt_client to output
  38. * the results of operations to stderr.
  39. *
  40. * \details All functions are invoked directly within the \ref mqtt_client using
  41. * its default executor. If the \ref mqtt_client is initialized with an explicit or
  42. * implicit strand, none of the functions will be invoked concurrently.
  43. *
  44. * \par Thread safety
  45. * Distinct objects: safe. \n
  46. * Shared objects: unsafe. \n
  47. * This class is <b>not thread-safe</b>.
  48. */
  49. class logger {
  50. constexpr static auto prefix = "[Boost.MQTT5]";
  51. log_level _level;
  52. public:
  53. /**
  54. * \brief Constructs a logger that filters log messages based on the specified log level.
  55. *
  56. * \param level Messages with a log level higher than the given log level will be suppressed.
  57. */
  58. logger(log_level level = log_level::info) : _level(level) {}
  59. /**
  60. * \brief Outputs the results of the resolve operation.
  61. *
  62. * \param ec Error code returned by the resolve operation.
  63. * \param host Hostname used in the resolve operation.
  64. * \param port Port used in the resolve operation.
  65. * \param eps Endpoints returned by the resolve operation.
  66. */
  67. void at_resolve(
  68. error_code ec, std::string_view host, std::string_view port,
  69. const asio::ip::tcp::resolver::results_type& eps
  70. ) {
  71. if (!ec && _level < log_level::info)
  72. return;
  73. output_prefix();
  74. std::clog
  75. << "resolve: "
  76. << host << ":" << port;
  77. std::clog << " - " << ec.message() << ".";
  78. if (_level == log_level::debug) {
  79. std::clog << " [";
  80. for (auto it = eps.begin(); it != eps.end();) {
  81. std::clog << it->endpoint().address().to_string();
  82. if (++it != eps.end())
  83. std::clog << ",";
  84. }
  85. std::clog << "]";
  86. }
  87. std::clog << std::endl;
  88. }
  89. /**
  90. * \brief Outputs the results of the TCP connect operation.
  91. *
  92. * \param ec Error code returned by the TCP connect operation.
  93. * \param ep The TCP endpoint used to establish the TCP connection.
  94. */
  95. void at_tcp_connect(error_code ec, asio::ip::tcp::endpoint ep) {
  96. if (!ec && _level < log_level::info)
  97. return;
  98. output_prefix();
  99. std::clog
  100. << "TCP connect: "
  101. << ep.address().to_string() << ":" << ep.port()
  102. << " - " << ec.message() << "."
  103. << std::endl;
  104. }
  105. /**
  106. * \brief Outputs the results of the TLS handshake operation.
  107. *
  108. * \param ec Error code returned by the TLS handshake operation.
  109. * \param ep The TCP endpoint used to establish the TLS handshake.
  110. */
  111. void at_tls_handshake(error_code ec, asio::ip::tcp::endpoint ep) {
  112. if (!ec && _level < log_level::info)
  113. return;
  114. output_prefix();
  115. std::clog
  116. << "TLS handshake: "
  117. << ep.address().to_string() << ":" << ep.port()
  118. << " - " << ec.message() << "."
  119. << std::endl;
  120. }
  121. /**
  122. * \brief Outputs the results of the WebSocket handshake operation.
  123. *
  124. * \param ec Error code returned by the WebSocket handshake operation.
  125. * \param ep The TCP endpoint used to establish the WebSocket handshake.
  126. */
  127. void at_ws_handshake(error_code ec, asio::ip::tcp::endpoint ep) {
  128. if (!ec && _level < log_level::info)
  129. return;
  130. output_prefix();
  131. std::clog
  132. << "WebSocket handshake: "
  133. << ep.address().to_string() << ":" << ep.port()
  134. << " - " << ec.message() << "."
  135. << std::endl;
  136. }
  137. /**
  138. * \brief Outputs the contents of the \__CONNACK\__ packet sent by the Broker.
  139. *
  140. * \param rc Reason Code in the received \__CONNACK\__ packet indicating
  141. * the result of the MQTT handshake.
  142. * \param session_present A flag indicating whether the Broker already has a session associated
  143. * with this connection.
  144. * \param ca_props \__CONNACK_PROPS\__ received in the \__CONNACK\__ packet.
  145. */
  146. void at_connack(
  147. reason_code rc,
  148. bool session_present, const connack_props& ca_props
  149. ) {
  150. if (!rc && _level < log_level::info)
  151. return;
  152. output_prefix();
  153. std::clog << "connack: " << rc.message() << ".";
  154. if (_level == log_level::debug) {
  155. std::clog << " session_present:" << session_present << " ";
  156. output_props(ca_props);
  157. }
  158. std::clog << std::endl;
  159. }
  160. /**
  161. * \brief Outputs the contents of the \__DISCONNECT\__ packet sent by the Broker.
  162. *
  163. * \param rc Reason Code in the received \__DISCONNECT\__ packet indicating
  164. * the reason behind the disconnection.
  165. * \param dc_props \__DISCONNECT_PROPS\__ received in the \__DISCONNECT\__ packet.
  166. */
  167. void at_disconnect(reason_code rc, const disconnect_props& dc_props) {
  168. output_prefix();
  169. std::clog << "disconnect: " << rc.message() << ".";
  170. if (_level == log_level::debug)
  171. output_props(dc_props);
  172. std::clog << std::endl;
  173. }
  174. /**
  175. * \brief Outputs the error message when it occurs at the transport layer
  176. * read or write operations.
  177. *
  178. * \param ec The error code returned by the `async_read_some` or
  179. * `async_write_some` operation on the underlying \__StreamType\__ stream.
  180. */
  181. void at_transport_error(error_code ec) {
  182. if (_level < log_level::info)
  183. return;
  184. output_prefix();
  185. std::clog
  186. << "transport layer error: " << ec.message() << "." << std::endl;
  187. }
  188. private:
  189. void output_prefix() {
  190. std::clog << prefix << " ";
  191. }
  192. template <typename Props>
  193. void output_props(const Props& props) {
  194. props.visit(
  195. [](const auto& prop, const auto& val) -> bool {
  196. if constexpr (detail::is_optional<decltype(val)>) {
  197. if (val.has_value()) {
  198. std::clog << property_name(prop) << ":";
  199. using value_type = boost::remove_cv_ref_t<decltype(*val)>;
  200. if constexpr (std::is_same_v<value_type, uint8_t>)
  201. std::clog << std::to_string(*val) << " ";
  202. else
  203. std::clog << *val << " ";
  204. }
  205. } else { // is vector
  206. if (val.empty())
  207. return true;
  208. std::clog << property_name(prop) << ":";
  209. std::clog << "[";
  210. for (size_t i = 0; i < val.size(); i++) {
  211. if constexpr (detail::is_pair<decltype(val[i])>)
  212. std::clog << "(" << val[i].first << "," << val[i].second << ")";
  213. else
  214. std::clog << std::to_string(val[i]);
  215. if (i + 1 < val.size())
  216. std::clog << ", ";
  217. }
  218. std::clog << "] ";
  219. }
  220. return true;
  221. }
  222. );
  223. }
  224. template <prop::property_type p>
  225. static std::string_view property_name(std::integral_constant<prop::property_type, p>) {
  226. return prop::name_v<p>;
  227. }
  228. };
  229. // Verify that the logger class satisfies the LoggerType concept
  230. static_assert(has_at_resolve<logger>);
  231. static_assert(has_at_tcp_connect<logger>);
  232. static_assert(has_at_tls_handshake<logger>);
  233. static_assert(has_at_ws_handshake<logger>);
  234. static_assert(has_at_connack<logger>);
  235. static_assert(has_at_disconnect<logger>);
  236. static_assert(has_at_transport_error<logger>);
  237. } // end namespace boost::mqtt5
  238. #endif // !BOOST_MQTT5_LOGGER_HPP