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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?