Skip to content

Commit

Permalink
Cap logfile size
Browse files Browse the repository at this point in the history
  • Loading branch information
dechamps committed May 5, 2022
1 parent b69f2ee commit bb054b3
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
30 changes: 28 additions & 2 deletions log.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,40 @@ namespace dechamps_cpplog {
Logger(this) << "Host process: " << GetModuleName();
}

FileLogSink::FileLogSink(const std::filesystem::path& path) : stream(path, std::ios::app | std::ios::out) {
Logger(this) << "Logfile opened: " << path;
FileLogSink::FileLogSink(std::filesystem::path path, Options options) : path(std::move(path)), options(std::move(options)), stream(this->path, std::ios::app | std::ios::out) {
Logger(this) << "Logfile opened: " << this->path;
CheckSize();
}

FileLogSink::~FileLogSink() {
Logger(this) << "Closing logfile";
}

void FileLogSink::Write(const std::string_view str) {
if (!stream.is_open()) return;

stream_sink.Write(str);

const auto size = str.size();
if (size >= bytesRemainingUntilSizeCheck) CheckSize();
else bytesRemainingUntilSizeCheck -= size;
}

void FileLogSink::CheckSize() {
bytesRemainingUntilSizeCheck = (std::numeric_limits<uintmax_t>::max)();

const auto sizeBytes = std::filesystem::file_size(path);
const auto maxSizeBytes = options.maxSizeBytes;
Logger(this) << "Current log file size is " << sizeBytes << " bytes (maximum allowed: " << maxSizeBytes << " bytes)";

if (sizeBytes < maxSizeBytes) {
bytesRemainingUntilSizeCheck = options.sizeCheckPeriodBytes;
return;
}
Logger(this) << "Closing logfile as the maximum size is exceeded";
stream.close();
}

void ThreadSafeLogSink::Write(const std::string_view str) {
std::scoped_lock lock(mutex);
backend.Write(str);
Expand Down
14 changes: 12 additions & 2 deletions log.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,24 @@ namespace dechamps_cpplog {

class FileLogSink final : public LogSink {
public:
FileLogSink(const std::filesystem::path& path);
struct Options final {
uintmax_t maxSizeBytes = 1 * 1024 * 1024 * 1024;
uintmax_t sizeCheckPeriodBytes = std::max<uintmax_t>(maxSizeBytes / 10, 1);
};

FileLogSink(std::filesystem::path path, Options options = {});
~FileLogSink();

void Write(const std::string_view str) override { stream_sink.Write(str); }
void Write(const std::string_view str) override;

private:
void CheckSize();

const std::filesystem::path path;
Options options;
std::ofstream stream;
StreamLogSink stream_sink{ stream };
uintmax_t bytesRemainingUntilSizeCheck = (std::numeric_limits<uintmax_t>::max)();
};

class ThreadSafeLogSink final : public LogSink {
Expand Down

0 comments on commit bb054b3

Please sign in to comment.