Artem Senichev | e8837d5 | 2020-06-07 11:59:04 +0300 | [diff] [blame] | 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (C) 2020 YADRO |
| 3 | |
| 4 | #pragma once |
| 5 | |
| 6 | #include "log_buffer.hpp" |
| 7 | |
| 8 | #include <filesystem> |
| 9 | |
| 10 | /** |
| 11 | * @class FileStorage |
| 12 | * @brief Persistent file storage with automatic log file rotation. |
| 13 | */ |
| 14 | class FileStorage |
| 15 | { |
| 16 | public: |
| 17 | /** |
| 18 | * @brief Constructor. |
| 19 | * |
| 20 | * @param[in] path absolute path to the output directory |
| 21 | * @param[in] prefix prefix used for log file names |
| 22 | * @param[in] maxFiles max number of log files that can be stored |
| 23 | * |
| 24 | * @throw std::exception in case of errors |
| 25 | */ |
| 26 | FileStorage(const std::string& path, const std::string& prefix, |
| 27 | size_t maxFiles); |
| 28 | |
Nan Zhou | 042b5ba | 2021-06-18 09:32:45 -0700 | [diff] [blame^] | 29 | virtual ~FileStorage() = default; |
| 30 | |
Artem Senichev | e8837d5 | 2020-06-07 11:59:04 +0300 | [diff] [blame] | 31 | /** |
| 32 | * @brief Save log buffer to a file. |
| 33 | * |
| 34 | * @param[in] buf buffer with log message to save |
| 35 | * |
| 36 | * @throw std::exception in case of errors |
| 37 | * |
| 38 | * @return path to saved file |
| 39 | */ |
Nan Zhou | 042b5ba | 2021-06-18 09:32:45 -0700 | [diff] [blame^] | 40 | virtual std::string save(const LogBuffer& buf) const; |
Artem Senichev | e8837d5 | 2020-06-07 11:59:04 +0300 | [diff] [blame] | 41 | |
| 42 | private: |
| 43 | /** |
| 44 | * @brief Prepare output directory for a new log file and construct path. |
| 45 | * |
| 46 | * @throw std::exception in case of errors |
| 47 | * |
| 48 | * @return full path to the new file |
| 49 | */ |
| 50 | std::string newFile() const; |
| 51 | |
| 52 | /** |
| 53 | * @brief Rotate log files in the output directory by removing the oldest |
| 54 | * logs. |
| 55 | * |
| 56 | * @throw std::exception in case of errors |
| 57 | */ |
| 58 | void rotate() const; |
| 59 | |
| 60 | private: |
| 61 | /** @brief Output directory. */ |
| 62 | std::filesystem::path outDir; |
| 63 | /** @brief Prefix used for log file names. */ |
| 64 | std::string filePrefix; |
| 65 | /** @brief Max number of log files that can be stored. */ |
| 66 | size_t filesLimit; |
| 67 | }; |