From ce4d7263138719590ca826fce02cae9f5bc3904a Mon Sep 17 00:00:00 2001 From: Markus Grimm Date: Fri, 10 Feb 2017 08:36:40 +0100 Subject: [PATCH] Proper logrotation for rosout --- tools/rosout/rosout.cpp | 44 +++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/tools/rosout/rosout.cpp b/tools/rosout/rosout.cpp index 343300845a..468363d540 100644 --- a/tools/rosout/rosout.cpp +++ b/tools/rosout/rosout.cpp @@ -178,40 +178,42 @@ class Rosout // check for rolling if (current_file_size_ > max_file_size_) { + std::cout << "rosout log file " << log_file_name_.c_str() << " reached max size, rotating log files" << std::endl; if (fclose(handle_)) { std::cerr << "Error closing rosout log file '" << log_file_name_.c_str() << "': " << strerror(ferror(handle_)) << std::endl; } - current_backup_index_++; - if (current_backup_index_ <= max_backup_index_) + if (current_backup_index_ == max_backup_index_) { std::stringstream backup_file_name; - backup_file_name << log_file_name_ << "." << current_backup_index_; - int rc = rename(log_file_name_.c_str(), backup_file_name.str().c_str()); + backup_file_name << log_file_name_ << "." << max_backup_index_; + int rc = remove(backup_file_name.str().c_str()); if (rc != 0) { - rc = remove(backup_file_name.str().c_str()); - if (rc == 0) - { - rc = rename(log_file_name_.c_str(), backup_file_name.str().c_str()); - if (rc) - { - std::cerr << "Error rotating rosout log file '" << log_file_name_.c_str() << "' to '" << backup_file_name.str().c_str() << "': " << strerror(errno); - } - } + std::cerr << "Error deleting oldest rosout log file '" << backup_file_name.str().c_str() << "': " << strerror(errno) << std::endl; } - if (rc) - { - std::cerr << "Error rotating rosout log file '" << log_file_name_.c_str() << "'' to '" << backup_file_name.str().c_str() << "'" << std::endl; - } - else + } + std::size_t i = std::min(max_backup_index_, current_backup_index_ + 1); + while (i > 0) + { + std::stringstream current_file_name; + current_file_name << log_file_name_; + if (i > 1) { - std::cout << "rosout log file " << log_file_name_.c_str() << " reached max size, back up data to " << backup_file_name.str().c_str() << std::endl; + current_file_name << "." << (i - 1); } - if (current_backup_index_ == max_backup_index_) + std::stringstream rotated_file_name; + rotated_file_name << log_file_name_ << "." << i; + int rc = rename(current_file_name.str().c_str(), rotated_file_name.str().c_str()); + if (rc != 0) { - current_backup_index_ = 0; + std::cerr << "Error rotating rosout log file '" << current_file_name.str().c_str() << "' to '" << rotated_file_name.str().c_str() << "': " << strerror(errno) << std::endl; } + --i; + } + if (current_backup_index_ < max_backup_index_) + { + ++current_backup_index_; } handle_ = fopen(log_file_name_.c_str(), "w"); if (handle_ == 0)