Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow manual rotation of rotating_file_sink #3269

Merged
merged 4 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions include/spdlog/sinks/rotating_file_sink-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ SPDLOG_INLINE filename_t rotating_file_sink<Mutex>::filename() {
return file_helper_.filename();
}

template <typename Mutex>
SPDLOG_INLINE void rotating_file_sink<Mutex>::rotate_now() {
SPDLOG_TRY { rotate_(); }
SPDLOG_CATCH_STD
hjs-ast marked this conversation as resolved.
Show resolved Hide resolved
}

template <typename Mutex>
SPDLOG_INLINE void rotating_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/rotating_file_sink.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class rotating_file_sink final : public base_sink<Mutex> {
const file_event_handlers &event_handlers = {});
static filename_t calc_filename(const filename_t &filename, std::size_t index);
filename_t filename();
void rotate_now();

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 @@ -101,3 +101,23 @@ TEST_CASE("rotating_file_logger3", "[rotating_logger]") {
REQUIRE_THROWS_AS(spdlog::rotating_logger_mt("logger", basename, max_size, 0),
spdlog::spdlog_ex);
}

// test on-demand rotation of logs
TEST_CASE("rotating_file_logger4", "[rotating_logger]") {
prepare_logdir();
size_t max_size = 1024 * 10;
spdlog::filename_t basename = SPDLOG_FILENAME_T(ROTATING_LOG);
auto sink = std::make_shared<spdlog::sinks::rotating_file_sink_st>(basename, max_size, 2);
auto logger = std::make_shared<spdlog::logger>("rotating_sink_logger", sink);

logger->info("Test message - pre-rotation");
logger->flush();

sink->rotate_now();

logger->info("Test message - post-rotation");
logger->flush();

REQUIRE(get_filesize(ROTATING_LOG) > 0);
REQUIRE(get_filesize(ROTATING_LOG ".1") > 0);
}