diff --git a/source/util/log.cpp b/source/util/log.cpp index 9db0dc35..72a89fdc 100644 --- a/source/util/log.cpp +++ b/source/util/log.cpp @@ -25,10 +25,47 @@ std::filesystem::path logPath; std::mutex lock; +void trim(const unsigned int count) +{ + /* a poorman's circular buffer that keeps the last 'count' log lines. */ + std::vector v(count); + + std::ifstream input(logPath); + std::size_t index = 0; + std::string s; + while (std::getline(input, s)) { + v[index % count] = s; + index++; + } + + input.close(); + + // required because of len/cap discrepancy in vector used as a circular + // buffer. + const auto upto = count < index ? index : count; + + std::ofstream output(logPath, std::ios_base::out); + if (output.good()) { + for (size_t i = 0; i < upto; ++i) + output << v[(index + i) % count] << std::endl; + } else { + std::cerr << "could not open log file for trimming" << std::endl; + } + output.close(); +} + void init(enum Level lvl, std::filesystem::path lp) { FilterLevel = lvl; logPath = lp; + + // keep only the last X lines + trim(1000); + + if (!logFile) { + const auto mode = std::ios_base::out | std::ios_base::app; + logFile = std::ofstream(logPath, mode); + } } std::string all() diff --git a/source/util/log.h b/source/util/log.h index 91e7af1d..0c65aa4a 100644 --- a/source/util/log.h +++ b/source/util/log.h @@ -24,8 +24,8 @@ #include #include #include -#include #include +#include /* TODO: fmtlib: replace with std, when all compilers support `format'. */ #include @@ -59,6 +59,7 @@ void init(enum Level lvl, std::filesystem::path logPath); */ std::string all(); + template void backend(enum Level level, std::string_view fmt, Args&&... args) { @@ -94,11 +95,6 @@ void backend(enum Level level, std::string_view fmt, Args&&... args) << fmt::vformat(fmt, fmt::make_format_args(args...)) << std::endl; - if (!logFile) { - const auto mode = std::ios_base::out | std::ios_base::app; - logFile = std::ofstream(logPath, mode); - } - if (logFile.value().good()) { logFile.value() << timestamp_now_str_fn() << ": "