unilink  0.4.3
A simple C++ library for unified async communication
log_rotation.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2025 Jinwoo Sung
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <atomic>
20 #include <chrono>
21 #include <filesystem>
22 #include <mutex>
23 #include <string>
24 #include <vector>
25 
27 
28 namespace unilink {
29 namespace diagnostics {
30 
35  size_t max_file_size_bytes = 10 * 1024 * 1024; // 10MB default
36  size_t max_files = 10; // Keep 10 files max
37  bool enable_compression = false; // Future feature
38  std::string file_pattern = "{name}.{index}.log"; // File naming pattern
39 
40  LogRotationConfig() = default;
41 
42  LogRotationConfig(size_t max_size, size_t max_count) : max_file_size_bytes(max_size), max_files(max_count) {}
43 };
44 
52  public:
57  explicit LogRotation(const LogRotationConfig& config = LogRotationConfig{});
58 
64  bool should_rotate(const std::string& filepath) const;
65 
71  std::string rotate(const std::string& filepath);
72 
77  void cleanup_old_files(const std::string& base_filepath);
78 
84  std::string get_next_file_path(const std::string& base_filepath) const;
85 
90  void update_config(const LogRotationConfig& config);
91 
95  const LogRotationConfig& get_config() const { return config_; }
96 
102  static size_t get_file_size(const std::string& filepath);
103 
109  static std::vector<std::string> get_log_files(const std::string& base_filepath);
110 
111  private:
112  LogRotationConfig config_;
113  mutable std::mutex mutex_;
114 
120  std::string get_base_filename(const std::string& filepath) const;
121 
127  std::string get_directory(const std::string& filepath) const;
128 
134  int get_file_index(const std::string& filename) const;
135 
142  std::string generate_filename(const std::string& base_name, int index) const;
143 
148  void sort_files_by_time(std::vector<std::string>& files) const;
149 };
150 
151 } // namespace diagnostics
152 } // namespace unilink
#define UNILINK_API
Definition: visibility.hpp:37