file_helper.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. {
  13. public:
  14. file_helper() = default;
  15. explicit file_helper(const file_event_handlers &event_handlers);
  16. file_helper(const file_helper &) = delete;
  17. file_helper &operator=(const file_helper &) = delete;
  18. ~file_helper();
  19. void open(const filename_t &fname, bool truncate = false);
  20. void reopen(bool truncate);
  21. void flush();
  22. void sync();
  23. void close();
  24. void write(const memory_buf_t &buf);
  25. size_t size() const;
  26. const filename_t &filename() const;
  27. //
  28. // return file path and its extension:
  29. //
  30. // "mylog.txt" => ("mylog", ".txt")
  31. // "mylog" => ("mylog", "")
  32. // "mylog." => ("mylog.", "")
  33. // "/dir1/dir2/mylog.txt" => ("/dir1/dir2/mylog", ".txt")
  34. //
  35. // the starting dot in filenames is ignored (hidden files):
  36. //
  37. // ".mylog" => (".mylog". "")
  38. // "my_folder/.mylog" => ("my_folder/.mylog", "")
  39. // "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt")
  40. static std::tuple<filename_t, filename_t> split_by_extension(const filename_t &fname);
  41. private:
  42. const int open_tries_ = 5;
  43. const unsigned int open_interval_ = 10;
  44. std::FILE *fd_{nullptr};
  45. filename_t filename_;
  46. file_event_handlers event_handlers_;
  47. };
  48. } // namespace details
  49. } // namespace spdlog
  50. #ifdef SPDLOG_HEADER_ONLY
  51. # include "file_helper-inl.h"
  52. #endif