qxLib
file_logger_stream_fopen.inl
Go to the documentation of this file.
1 /**
2 
3  @file file_logger_stream_fopen.inl
4  @author Khrapov
5  @date 15.01.2026
6  @copyright (c) Nick Khrapov, 2026. All right reserved.
7 
8 **/
9 
10 namespace qx
11 {
12 
14  const config& streamConfig,
15  unit<size_t, units::data> bufferSize) noexcept
16  : base_file_logger_stream(streamConfig)
17 {
18  const std::filesystem::path path = prepare_folder_and_get_log_file_path(streamConfig);
19 
20  std::ios_base::sync_with_stdio(false);
21 
22  m_pFile = std::fopen(
23  path.generic_string().c_str(),
24  streamConfig.eLogFilePolicy == log_file_policy::clear_then_upend ? "wb" : "ab");
25  if (!m_pFile)
26  {
27  string sLastError = to_string(std::strerror(errno));
28  details::get_cerr<char_type>::get() << QXT("Can't open log file: ") << path << QXT(", error: ") << sLastError;
29  return;
30  }
31 
32  if (bufferSize.value > 0)
33  {
34  const unit<size_t, units::data> bytes = convert(bufferSize).to(units::data::bytes);
35  m_Buffer.resize(bytes.value);
36  std::setvbuf(m_pFile, m_Buffer.data(), _IOFBF, m_Buffer.size());
37  }
38 }
39 
41  : base_file_logger_stream(std::move(other))
42 {
43  std::swap(m_Buffer, other.m_Buffer);
44  std::swap(m_pFile, other.m_pFile);
45 }
46 
47 inline file_logger_stream_fopen::~file_logger_stream_fopen()
48 {
49  if (m_pFile)
50  {
51  std::fclose(m_pFile);
52  m_pFile = nullptr;
53  }
54 }
55 
57  const category& category,
58  verbosity eVerbosity,
59  std::thread::id threadId,
60  std::chrono::system_clock::time_point messageTime,
61  string_view svFile,
62  string_view svFunction,
63  int nLine,
64  string_view svMessage)
65 {
66  if (m_pFile)
67  {
68  const cstring_view svUtf8 = to_utf8(svMessage);
69  std::fwrite(svUtf8.data(), sizeof(char), svUtf8.size(), m_pFile);
70  }
71 }
72 
74 {
75  if (m_pFile)
76  std::fflush(m_pFile);
77 }
78 
79 } // namespace qx
Base class for all file logger streams.
static cstring_view to_utf8(string_view svMessage)
Encode a message as UTF-8 for a byte output.
A category is a class that identifies a particular piece of code. This code can be located in differe...
Definition: category.h:62
A conversion class.
Definition: base.h:77
FILE* based file logger stream.
virtual void do_flush() override
Flush the stream.
virtual void do_log(const category &category, verbosity eVerbosity, std::thread::id threadId, std::chrono::system_clock::time_point messageTime, string_view svFile, string_view svFunction, int nLine, string_view svMessage) override
Proceed stream logging.
file_logger_stream_fopen(const config &streamConfig=config(), unit< size_t, units::data > bufferSize={ 8192 *sizeof(char_type), units::data::bytes }) noexcept
file_logger_stream_fopen object constructor
void to_string(string &out, cstring_view stringView, const std::locale &locale=get_locale())
Convert a char string to common string type.
Definition: base.h:52