Skip to content

Commit

Permalink
Adding support to truncate on demand for basic file sink
Browse files Browse the repository at this point in the history
  • Loading branch information
matteodelseppia committed Dec 2, 2024
1 parent 1e6250e commit 5dcd8f2
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions include/spdlog/sinks/basic_file_sink-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ SPDLOG_INLINE const filename_t &basic_file_sink<Mutex>::filename() const {
return file_helper_.filename();
}

template <typename Mutex>
SPDLOG_INLINE void basic_file_sink<Mutex>::truncate() {
file_helper_.close();
file_helper_.reopen(true);
}

template <typename Mutex>
SPDLOG_INLINE void basic_file_sink<Mutex>::sink_it_(const details::log_msg &msg) {
memory_buf_t formatted;
Expand Down
1 change: 1 addition & 0 deletions include/spdlog/sinks/basic_file_sink.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class basic_file_sink final : public base_sink<Mutex> {
bool truncate = false,
const file_event_handlers &event_handlers = {});
const filename_t &filename() const;
void truncate();

protected:
void sink_it_(const details::log_msg &msg) override;
Expand Down
20 changes: 20 additions & 0 deletions tests/test_file_logging.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,26 @@ TEST_CASE("flush_on", "[flush_on]") {
default_eol, default_eol, default_eol));
}

TEST_CASE("simple_file_logger", "[truncate]") {
prepare_logdir();
const spdlog::filename_t filename = SPDLOG_FILENAME_T(SIMPLE_LOG);
const bool truncate = true;
const auto sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filename, truncate);
const auto logger = std::make_shared<spdlog::logger>("simple_file_logger", sink);

logger->info("Test message {}", 3.14);
logger->info("Test message {}", 2.71);
logger->flush();
REQUIRE(count_lines(SIMPLE_LOG) == 2);

sink->truncate();
REQUIRE(count_lines(SIMPLE_LOG) == 0);

logger->info("Test message {}", 6.28);
logger->flush();
REQUIRE(count_lines(SIMPLE_LOG) == 1);
}

TEST_CASE("rotating_file_logger1", "[rotating_logger]") {
prepare_logdir();
size_t max_size = 1024 * 10;
Expand Down

0 comments on commit 5dcd8f2

Please sign in to comment.