1 | // Copyright(c) 2015-present, Gabi Melman & spdlog contributors. |
2 | // Distributed under the MIT License (http://opensource.org/licenses/MIT) |
3 | |
4 | #pragma once |
5 | |
6 | #include <spdlog/common.h> |
7 | #include <tuple> |
8 | |
9 | namespace spdlog { |
10 | namespace details { |
11 | |
12 | // Helper class for file sinks. |
13 | // When failing to open a file, retry several times(5) with a delay interval(10 ms). |
14 | // Throw spdlog_ex exception on errors. |
15 | |
16 | class SPDLOG_API file_helper |
17 | { |
18 | public: |
19 | file_helper() = default; |
20 | explicit file_helper(const file_event_handlers &event_handlers); |
21 | |
22 | file_helper(const file_helper &) = delete; |
23 | file_helper &operator=(const file_helper &) = delete; |
24 | ~file_helper(); |
25 | |
26 | void open(const filename_t &fname, bool truncate = false); |
27 | void reopen(bool truncate); |
28 | void flush(); |
29 | void close(); |
30 | void write(const memory_buf_t &buf); |
31 | size_t size() const; |
32 | const filename_t &filename() const; |
33 | |
34 | // |
35 | // return file path and its extension: |
36 | // |
37 | // "mylog.txt" => ("mylog", ".txt") |
38 | // "mylog" => ("mylog", "") |
39 | // "mylog." => ("mylog.", "") |
40 | // "/dir1/dir2/mylog.txt" => ("/dir1/dir2/mylog", ".txt") |
41 | // |
42 | // the starting dot in filenames is ignored (hidden files): |
43 | // |
44 | // ".mylog" => (".mylog". "") |
45 | // "my_folder/.mylog" => ("my_folder/.mylog", "") |
46 | // "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt") |
47 | static std::tuple<filename_t, filename_t> split_by_extension(const filename_t &fname); |
48 | |
49 | private: |
50 | const int open_tries_ = 5; |
51 | const unsigned int open_interval_ = 10; |
52 | std::FILE *fd_{nullptr}; |
53 | filename_t filename_; |
54 | file_event_handlers event_handlers_; |
55 | }; |
56 | } // namespace details |
57 | } // namespace spdlog |
58 | |
59 | #ifdef SPDLOG_HEADER_ONLY |
60 | # include "file_helper-inl.h" |
61 | #endif |
62 | |