log_to_file.hpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. //
  2. // Copyright (c) 2025 Marcelo Zimbres Silva (mzimbres@gmail.com),
  3. // Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
  4. //
  5. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  6. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. #ifndef BOOST_REDIS_LOG_TO_STDERR_HPP
  9. #define BOOST_REDIS_LOG_TO_STDERR_HPP
  10. #include <algorithm>
  11. #include <cstddef>
  12. #include <cstdio>
  13. #include <string_view>
  14. namespace boost::redis::detail {
  15. // Shared by several ipp files
  16. inline void log_to_file(FILE* f, std::string_view msg, const char* prefix = "(Boost.Redis) ")
  17. {
  18. // If the message is empty, data() might return a null pointer
  19. const char* msg_ptr = msg.empty() ? "" : msg.data();
  20. // Precision should be an int when passed to fprintf. Technically,
  21. // message could be larger than INT_MAX. Impose a sane limit on message sizes
  22. // to prevent memory problems
  23. auto precision = static_cast<int>((std::min)(msg.size(), static_cast<std::size_t>(0xffffu)));
  24. // Log the message. None of our messages should contain NULL bytes, so this should be OK.
  25. // We choose fprintf over std::clog because it's safe in multi-threaded environments.
  26. std::fprintf(f, "%s%.*s\n", prefix, precision, msg_ptr);
  27. }
  28. } // namespace boost::redis::detail
  29. #endif