Loading...
Searching...
No Matches
log_to_file.hpp
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
9#ifndef BOOST_REDIS_LOG_TO_STDERR_HPP
10#define BOOST_REDIS_LOG_TO_STDERR_HPP
11
12#include <algorithm>
13#include <cstddef>
14#include <cstdio>
15#include <string_view>
16
17namespace boost::redis::detail {
18
19// Shared by several ipp files
20inline void log_to_file(FILE* f, std::string_view msg, const char* prefix = "(Boost.Redis) ")
21{
22 // If the message is empty, data() might return a null pointer
23 const char* msg_ptr = msg.empty() ? "" : msg.data();
24
25 // Precision should be an int when passed to fprintf. Technically,
26 // message could be larger than INT_MAX. Impose a sane limit on message sizes
27 // to prevent memory problems
28 auto precision = static_cast<int>((std::min)(msg.size(), static_cast<std::size_t>(0xffffu)));
29
30 // Log the message. None of our messages should contain NULL bytes, so this should be OK.
31 // We choose fprintf over std::clog because it's safe in multi-threaded environments.
32 std::fprintf(f, "%s%.*s\n", prefix, precision, msg_ptr);
33}
34
35} // namespace boost::redis::detail
36
37#endif