file_helper.h 1.7 KB

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