spdlog/include/spdlog/details/file_helper.h

61 lines
1.6 KiB
C
Raw Normal View History

2019-06-04 05:09:16 +08:00
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
2016-04-20 16:57:49 +08:00
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
2019-04-06 18:45:33 +08:00
#include "spdlog/common.h"
#include <tuple>
2016-04-20 16:57:49 +08:00
2018-03-17 18:47:46 +08:00
namespace spdlog {
namespace details {
2016-04-20 16:57:49 +08:00
2019-04-06 18:45:33 +08:00
// Helper class for file sinks.
// When failing to open a file, retry several times(5) with a delay interval(10 ms).
// Throw spdlog_ex exception on errors.
2016-04-20 16:57:49 +08:00
class file_helper
{
public:
2018-02-25 08:25:15 +08:00
explicit file_helper() = default;
2016-04-20 16:57:49 +08:00
2018-03-09 21:26:33 +08:00
file_helper(const file_helper &) = delete;
file_helper &operator=(const file_helper &) = delete;
2019-04-27 07:34:50 +08:00
~file_helper();
2019-04-06 18:45:33 +08:00
2019-04-27 07:34:50 +08:00
void open(const filename_t &fname, bool truncate = false);
void reopen(bool truncate);
void flush();
void close();
void write(const memory_buf_t &buf);
2019-04-27 07:34:50 +08:00
size_t size() const;
2019-04-06 18:45:33 +08:00
const filename_t &filename() const;
static bool file_exists(const filename_t &fname);
2019-04-27 07:34:50 +08:00
2017-12-01 09:46:19 +08:00
//
// return file path and its extension:
2017-12-01 09:46:19 +08:00
//
// "mylog.txt" => ("mylog", ".txt")
// "mylog" => ("mylog", "")
2017-12-23 00:55:19 +08:00
// "mylog." => ("mylog.", "")
// "/dir1/dir2/mylog.txt" => ("/dir1/dir2/mylog", ".txt")
2017-12-01 09:46:19 +08:00
//
// the starting dot in filenames is ignored (hidden files):
//
2017-12-23 00:55:19 +08:00
// ".mylog" => (".mylog". "")
// "my_folder/.mylog" => ("my_folder/.mylog", "")
2017-12-01 09:46:19 +08:00
// "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt")
2019-04-06 18:45:33 +08:00
static std::tuple<filename_t, filename_t> split_by_extension(const filename_t &fname);
2018-02-25 08:25:15 +08:00
2016-04-20 16:57:49 +08:00
private:
2019-06-04 03:49:21 +08:00
const int open_tries = 5;
const int open_interval = 10;
2018-08-17 19:07:49 +08:00
std::FILE *fd_{nullptr};
2016-10-13 04:08:44 +08:00
filename_t _filename;
2016-04-20 16:57:49 +08:00
};
2018-03-17 18:47:46 +08:00
} // namespace details
} // namespace spdlog
2019-04-06 18:45:33 +08:00
#ifdef SPDLOG_HEADER_ONLY
2019-05-11 18:19:53 +08:00
#include "file_helper-inl.h"
2019-04-27 23:44:48 +08:00
#endif