|
1 | | -#include "stdafx.hpp" |
2 | 1 | #include "LoggerSystem.hpp" |
| 2 | +#include "Config.hpp" |
| 3 | +#include "Paths.hpp" |
| 4 | +#include "stdafx.hpp" |
3 | 5 |
|
4 | 6 | LoggerSystem::LoggerSystem(const Paths& aPaths, const Config& aConfig, const DevConsole& aDevConsole) |
5 | 7 | : m_paths(aPaths) |
@@ -32,6 +34,65 @@ void LoggerSystem::Shutdown() |
32 | 34 | spdlog::trace("{} logger(s) flushed", count); |
33 | 35 | } |
34 | 36 |
|
| 37 | +void LoggerSystem::RotateLogs(std::vector<std::wstring> pluginNames) const |
| 38 | +{ |
| 39 | + std::error_code error; |
| 40 | + auto files = std::filesystem::directory_iterator(m_paths.GetLogsDir(), error); |
| 41 | + |
| 42 | + if (error) |
| 43 | + { |
| 44 | + // Ignore and try the next time. |
| 45 | + return; |
| 46 | + } |
| 47 | + spdlog::trace("Rotate logs..."); |
| 48 | + pluginNames.emplace_back(L"RED4ext"); |
| 49 | + |
| 50 | + // List all log files. |
| 51 | + std::vector<std::filesystem::path> logs; |
| 52 | + |
| 53 | + for (const std::filesystem::directory_entry& file : files) |
| 54 | + { |
| 55 | + const auto fileName = file.path().filename().wstring(); |
| 56 | + |
| 57 | + if (file.is_regular_file() && fileName.ends_with(L".log")) |
| 58 | + { |
| 59 | + logs.emplace_back(file.path()); |
| 60 | + } |
| 61 | + } |
| 62 | + const Config::LoggingConfig config = m_config.GetLogging(); |
| 63 | + |
| 64 | + // Rotate oldest logs per plugin. |
| 65 | + for (auto pluginName : pluginNames) |
| 66 | + { |
| 67 | + pluginName = Utils::ToLower(pluginName); |
| 68 | + std::vector<std::filesystem::path> pluginLogs; |
| 69 | + |
| 70 | + logs.erase(std::remove_if(logs.begin(), logs.end(), |
| 71 | + [&pluginName, &pluginLogs](const auto& log) |
| 72 | + { |
| 73 | + if (log.filename().wstring().starts_with(pluginName)) |
| 74 | + { |
| 75 | + pluginLogs.push_back(log); |
| 76 | + return true; |
| 77 | + } |
| 78 | + return false; |
| 79 | + }), |
| 80 | + logs.end()); |
| 81 | + std::sort(pluginLogs.begin(), pluginLogs.end(), [](const auto& a, const auto& b) { return a > b; }); |
| 82 | + |
| 83 | + // maxFiles is guaranteed to be >= 1. |
| 84 | + for (size_t i = config.maxFiles; i < pluginLogs.size(); i++) |
| 85 | + { |
| 86 | + std::filesystem::remove(pluginLogs[i], error); |
| 87 | + } |
| 88 | + } |
| 89 | + // Remove log files of removed plugins. |
| 90 | + for (const auto& log : logs) |
| 91 | + { |
| 92 | + std::filesystem::remove(log, error); |
| 93 | + } |
| 94 | +} |
| 95 | + |
35 | 96 | void LoggerSystem::Trace(std::shared_ptr<PluginBase> aPlugin, std::string_view aText) |
36 | 97 | { |
37 | 98 | Log(aPlugin, spdlog::level::trace, aText); |
|
0 commit comments