How do I roll log files and control sizes in C++?

Rolling log files is a technique used in software development to manage log file sizes and maintain organization. In C++, you can implement rolling log files by creating a logging mechanism that checks the size of the log file and rolls over when it reaches a specified limit.

Here’s a simple example of how to roll log files and control their sizes in C++:

#include #include #include #include #include class Logger { private: std::string filename; size_t max_size; size_t current_size; public: Logger(const std::string& name, size_t size) : filename(name), max_size(size), current_size(0) { std::ifstream file(filename, std::ifstream::ate); current_size = file.tellg(); } void log(const std::string& message) { if (current_size >= max_size) { roll_log(); } std::ofstream log_file(filename, std::ios::app); log_file << get_current_time() << ": " << message << std::endl; current_size += message.size() + 18; // Approx for timestamp } void roll_log() { std::string new_filename = filename + "." + get_current_time_suffix(); std::rename(filename.c_str(), new_filename.c_str()); std::ofstream log_file(filename, std::ios::trunc); current_size = 0; } std::string get_current_time() { std::time_t t = std::time(nullptr); char buf[100]; std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&t)); return buf; } std::string get_current_time_suffix() { std::time_t t = std::time(nullptr); char buf[20]; std::strftime(buf, sizeof(buf), "%Y%m%d%H%M%S", std::localtime(&t)); return buf; } }; int main() { Logger logger("logfile.txt", 1024); // Set max size to 1024 bytes logger.log("This is a log message."); return 0; }

rolling log files C++ log management log file size control C++ logging