2#ifndef LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_LOGGERS_FILELOGGER_HPP_INCLUDED
3#define LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_LOGGERS_FILELOGGER_HPP_INCLUDED
24#include <time_shield/text/time_parser.hpp>
28#if defined(__EMSCRIPTEN__)
30 class FileLogger :
public ILogger {
51 FileLogger(
const std::string&,
const bool& =
true,
const int& = 30,
52 const uint64_t& = 0,
const uint32_t& = 0) { warn(); }
53 FileLogger(
const std::string&,
const bool&,
const int&,
bool, std::size_t,
55 FileLogger(
const std::string&,
const bool&,
const int&, uint64_t, uint32_t,
58 void log(
const LogRecord&,
const std::string&)
override { warn(); }
64 void wait()
override {}
68 static bool warned =
false;
71 std::cerr <<
"FileLogger is not supported under Emscripten" << std::endl;
121 m_executor.reset(new detail::SingleThreadExecutor());
122 m_executor->set_max_queue_size(m_config.queue_capacity);
123 m_executor->set_queue_policy(m_config.queue_policy);
133 const std::string& directory,
134 const bool& async =
true,
135 const int& auto_delete_days = 30) {
144 const std::string& directory,
146 const int& auto_delete_days,
147 bool use_dedicated_executor,
148 std::size_t queue_capacity,
156 use_dedicated_executor,
162 const std::string& directory,
164 const int& auto_delete_days,
165 uint64_t max_file_size_bytes,
166 uint32_t max_rotated_files) {
177 const std::string& directory,
179 const int& auto_delete_days,
180 uint64_t max_file_size_bytes,
181 uint32_t max_rotated_files,
182 bool use_dedicated_executor,
183 std::size_t queue_capacity,
191 use_dedicated_executor,
209 std::unique_ptr<detail::SingleThreadExecutor> old_executor;
212 if (
m_shutdown.load(std::memory_order_acquire))
return;
221 std::lock_guard<std::mutex> lock(
m_mutex);
227 std::lock_guard<std::mutex> lock(
m_mutex);
245 old_executor->shutdown();
261 if (
m_shutdown.load(std::memory_order_acquire)) {
265 std::lock_guard<std::mutex> lock(
m_mutex);
274 m_executor->set_max_queue_size(queue_capacity);
286 void log(
const LogRecord& record,
const std::string& message)
override {
288 if (
m_shutdown.load(std::memory_order_acquire))
return;
292 std::lock_guard<std::mutex> lock(
m_mutex);
295 }
catch (
const std::exception& e) {
296 std::cerr <<
"Log error: " << e.what() << std::endl;
302 m_executor->add_task([
this, message, timestamp_ms]() {
303 std::lock_guard<std::mutex> lock(
m_mutex);
306 }
catch (
const std::exception& e) {
307 std::cerr <<
"Log async log error: " << e.what() << std::endl;
312 std::lock_guard<std::mutex> lock(
m_mutex);
315 }
catch (
const std::exception& e) {
316 std::cerr <<
"Log async log error: " << e.what() << std::endl;
334 return std::string();
380 std::vector<LogFileInfo> files;
382# if __cplusplus >= 201703L
384 fs::path dir_path = fs::u8path(directory);
386 fs::path dir_path(directory);
388 if (!fs::exists(dir_path) || !fs::is_directory(dir_path)) {
392 for (
const auto& entry : fs::directory_iterator(dir_path)) {
393 if (!fs::is_regular_file(entry.status()))
continue;
395 const std::string file_path = entry.path().u8string();
397 const std::string file_path = entry.path().string();
401 files.push_back(info);
405 const std::vector<std::string> file_list =
get_list_files(directory);
406 for (
size_t i = 0; i < file_list.size(); ++i) {
409 files.push_back(info);
425 for (
size_t i = 0; i < files.size(); ++i) {
441 std::vector<LogFileReadResult>
read_log_files(
const std::vector<std::string>& paths)
const override {
443 std::vector<LogFileReadResult> results;
444 results.reserve(paths.size());
446 for (
size_t i = 0; i < paths.size(); ++i) {
448 for (
size_t j = 0; j < files.size(); ++j) {
449 if (
same_path(files[j].path, paths[i])) {
461 results.push_back(result);
475 if (
m_shutdown.load(std::memory_order_acquire)) {
478 result.
message =
"FileLogger is shut down";
483 std::lock_guard<std::mutex> lock(
m_mutex);
489 for (
size_t i = 0; i < files.size(); ++i) {
501 }
catch (
const std::exception& e) {
504 result.
message = std::string(
"FileLogger clear error: ") + e.what();
508 result.
message =
"FileLogger clear error";
522 std::lock_guard<std::mutex> lock(
m_mutex);
530 if (
m_shutdown.exchange(
true, std::memory_order_acq_rel))
return;
534 std::lock_guard<std::mutex> lock(
m_mutex);
559 const std::string& directory,
561 int auto_delete_days,
562 uint64_t max_file_size_bytes,
563 uint32_t max_rotated_files,
564 bool use_dedicated_executor,
565 std::size_t queue_capacity,
568 config.directory = directory;
569 config.async = async;
570 config.auto_delete_days = auto_delete_days;
571 config.max_file_size_bytes = max_file_size_bytes;
572 config.max_rotated_files = max_rotated_files;
573 config.use_dedicated_executor = use_dedicated_executor;
574 config.queue_capacity = queue_capacity;
575 config.queue_policy = queue_policy;
585 std::lock_guard<std::mutex> lock(
m_mutex);
590 }
catch (
const std::exception& e) {
591 std::cerr <<
"Initialization error: " << e.what() << std::endl;
598 std::lock_guard<std::mutex> lock(
m_mutex);
636 throw std::runtime_error(
"Failed to open log file: " +
m_file_path);
638 m_file.seekp(0, std::ios::end);
646 std::string date_str = time_shield::to_iso8601_date(date_ts);
651 const std::string& file_path,
652 const std::string& current_file_path,
665 info.
name = filename;
681 std::lock_guard<std::mutex> lock(
m_mutex);
693 std::ifstream in(utf8_to_ansi(file_path).c_str(), std::ios_base::binary);
695 std::ifstream in(file_path.c_str(), std::ios_base::binary);
702 std::ostringstream stream;
703 stream << in.rdbuf();
710 return std::remove(utf8_to_ansi(file_path).c_str()) == 0;
712 return std::remove(file_path.c_str()) == 0;
718 if (lhs.day_start_ms != rhs.day_start_ms) {
719 return lhs.day_start_ms > rhs.day_start_ms;
722 return lhs.is_current && !rhs.is_current;
726 if (lhs_key.kind_rank != rhs_key.
kind_rank) {
727 return lhs_key.kind_rank > rhs_key.
kind_rank;
729 if (lhs_key.primary != rhs_key.
primary) {
730 return lhs_key.primary > rhs_key.
primary;
732 if (lhs_key.secondary != rhs_key.
secondary) {
733 return lhs_key.secondary > rhs_key.
secondary;
748 long long primary = 0;
749 long long secondary = 0;
758 if (plain_name.size() > 15 && plain_name[10] ==
'_') {
760 const std::string rest = plain_name.substr(11, plain_name.size() - 15);
761 const size_t dot = rest.find(
'.');
762 const std::string time_part = dot == std::string::npos ? rest : rest.substr(0, dot);
763 key.
primary = std::strtoll(time_part.c_str(),
nullptr, 10);
764 if (dot != std::string::npos) {
765 key.
secondary = std::strtoll(rest.substr(dot + 1).c_str(),
nullptr, 10);
770 if (plain_name.size() > 15 && plain_name[10] ==
'.') {
773 plain_name.substr(11, plain_name.size() - 15).c_str(),
781# if __cplusplus >= 201703L
783 return fs::u8path(file_path).parent_path().lexically_normal() ==
784 fs::u8path(directory_path).lexically_normal();
786 return fs::path(file_path).parent_path().lexically_normal() ==
787 fs::path(directory_path).lexically_normal();
790 const size_t pos = file_path.find_last_of(
"/\\");
791 if (pos == std::string::npos)
return false;
792 std::string parent = file_path.substr(0, pos);
793 return parent == directory_path;
797 bool same_path(
const std::string& lhs,
const std::string& rhs)
const {
798# if __cplusplus >= 201703L
800 return fs::u8path(lhs).lexically_normal() == fs::u8path(rhs).lexically_normal();
802 return fs::path(lhs).lexically_normal() == fs::path(rhs).lexically_normal();
805 return normalize_path_separators(lhs) == normalize_path_separators(rhs);
810 std::string normalized = path;
811 for (
size_t i = 0; i < normalized.size(); ++i) {
812 if (normalized[i] ==
'\\') normalized[i] =
'/';
818 return ends_with(filename,
".gz") || ends_with(filename,
".zst");
822 return strip_compression_suffix_impl(filename);
826 if (ends_with_impl(filename,
".gz")) {
827 return filename.substr(0, filename.size() - 3);
829 if (ends_with_impl(filename,
".zst")) {
830 return filename.substr(0, filename.size() - 4);
835 bool ends_with(
const std::string& value,
const std::string& suffix)
const {
836 return ends_with_impl(value, suffix);
839 static bool ends_with_impl(
const std::string& value,
const std::string& suffix) {
840 return value.size() >= suffix.size() &&
841 value.compare(value.size() - suffix.size(), suffix.size(), suffix) == 0;
847 void write_log(
const std::string& message,
const int64_t& timestamp_ms) {
848 const int64_t message_date_ts = time_shield::start_of_day(time_shield::ms_to_sec(timestamp_ms));
849 if (message_date_ts != m_current_date_ts) {
850 open_log_file(message_date_ts);
852 if (m_config.max_file_size_bytes > 0) {
853 const uint64_t add =
static_cast<uint64_t
>(message.size() + 1);
854 if (m_current_file_size + add > m_config.max_file_size_bytes) {
855 rotate_current_file();
858 if (m_file.is_open()) {
859 m_file << message <<
'\n';
860 m_current_file_size +=
static_cast<uint64_t
>(message.size() + 1);
866 if (m_file.is_open()) m_file.close();
868 const std::string base = time_shield::to_iso8601_date(m_current_date_ts);
869 const std::string dir = get_directory_path();
870 std::string rotated_str;
871# if __cplusplus >= 201703L
873 fs::path cur = (fs::u8path(dir) / (base +
".log")).lexically_normal();
874 fs::path rotated = fs::u8path(make_rotated_name(base, dir)).lexically_normal();
876 fs::path cur = (fs::path(dir) / (base +
".log")).lexically_normal();
877 fs::path rotated = fs::path(make_rotated_name(base, dir)).lexically_normal();
880 fs::rename(cur, rotated, ec);
882 throw std::runtime_error(
"Failed to rename log file: " + ec.message());
885 rotated_str = rotated.u8string();
887 rotated_str = rotated.string();
891 const std::string cur = dir +
"\\" + base +
".log";
893 const std::string cur = dir +
"/" + base +
".log";
895 rotated_str = make_rotated_name(base, dir);
897 if (std::rename(utf8_to_ansi(cur).c_str(), utf8_to_ansi(rotated_str).c_str()) != 0) {
899 if (std::rename(cur.c_str(), rotated_str.c_str()) != 0) {
901 throw std::runtime_error(
"Failed to rename log file");
905 open_log_file(m_current_date_ts);
906 m_current_file_size = 0;
909 if (m_config.compress_async) {
912 m_config.compress, m_config.compress_level, m_config.external_cmd));
914 m_compressor->enqueue(rotated_str);
916 detail::compress_file(m_config.compress, rotated_str, m_config.compress_level, m_config.external_cmd);
920 if (m_config.max_rotated_files > 0) {
921 enforce_rotation_retention(base, m_config.max_rotated_files, dir);
926# if __cplusplus >= 201703L
927 std::vector<fs::path> files;
928 for (
const auto& entry : fs::directory_iterator(dir)) {
929 if (!fs::is_regular_file(entry.status()))
continue;
930 std::string name = entry.path().filename().string();
931 if (name.rfind(base, 0) == 0 && name != base +
".log") {
932 files.emplace_back(entry.path());
935 if (files.size() <= max_files)
return;
937 auto extract = [&base](
const std::string& name) {
940 std::string rest = name.substr(base.size());
941 if (!rest.empty() && (rest[0] ==
'_' || rest[0] ==
'.')) {
942 rest = rest.substr(1);
943 size_t dot = rest.find(
'.');
944 ts = std::strtoll(rest.substr(0, dot).c_str(),
nullptr, 10);
945 if (dot != std::string::npos) {
946 size_t dot2 = rest.find(
'.', dot + 1);
947 if (dot2 != std::string::npos) {
948 idx = std::atoi(rest.substr(dot + 1, dot2 - dot - 1).c_str());
952 return std::make_pair(ts, idx);
954 std::sort(files.begin(), files.end(), [&](
const fs::path& a,
const fs::path& b) {
955 auto pa = extract(a.filename().string());
956 auto pb = extract(b.filename().string());
957 return (pa.first == pb.first) ? (pa.second < pb.second) : (pa.first < pb.first);
959 size_t to_remove = files.size() - max_files;
960 for (
size_t i = 0; i < to_remove; ++i) {
961 fs::remove(files[i]);
964 std::vector<std::string> files;
966 for (
const auto& path : file_list) {
967 std::string name = path.substr(path.find_last_of(
"/\\") + 1);
968 if (name.rfind(base, 0) == 0 && name != base +
".log") {
969 files.emplace_back(path);
972 if (files.size() <= max_files)
return;
974 auto extract = [&base](
const std::string& name) {
977 std::string rest = name.substr(base.size());
978 if (!rest.empty() && (rest[0] ==
'_' || rest[0] ==
'.')) {
979 rest = rest.substr(1);
980 size_t dot = rest.find(
'.');
981 ts = std::strtoll(rest.substr(0, dot).c_str(),
nullptr, 10);
982 if (dot != std::string::npos) {
983 size_t dot2 = rest.find(
'.', dot + 1);
984 if (dot2 != std::string::npos) {
985 idx = std::atoi(rest.substr(dot + 1, dot2 - dot - 1).c_str());
989 return std::make_pair(ts, idx);
991 std::sort(files.begin(), files.end(), [&](
const std::string& a,
const std::string& b) {
992 auto pa = extract(a.substr(a.find_last_of(
"/\\") + 1));
993 auto pb = extract(b.substr(b.find_last_of(
"/\\") + 1));
994 return (pa.first == pb.first) ? (pa.second < pb.second) : (pa.first < pb.first);
996 size_t to_remove = files.size() - max_files;
997 for (
size_t i = 0; i < to_remove; ++i) {
999 remove(utf8_to_ansi(files[i]).c_str());
1001 remove(files[i].c_str());
1008 switch (m_config.naming) {
1010 return make_sequence_name(base, dir);
1013 return make_timestamp_name(base, dir);
1015 return make_sequence_name(base, dir);
1020 std::string rotated;
1021# if __cplusplus >= 201703L
1023 std::ostringstream oss;
1024 oss << dir <<
"/" << base <<
'.' << std::setw(m_config.seq_width)
1025 << std::setfill(
'0') << idx <<
".log";
1026 rotated = oss.str();
1027 if (!fs::exists(rotated))
break;
1030 auto file_exists = [](
const std::string& path) {
1032 std::ifstream f(utf8_to_ansi(path).c_str());
1034 std::ifstream f(path.c_str());
1039 std::ostringstream oss;
1040 oss << dir <<
"/" << base <<
'.' << std::setw(m_config.seq_width)
1041 << std::setfill(
'0') << idx <<
".log";
1042 rotated = oss.str();
1043 if (!file_exists(rotated))
break;
1051 time_t sec =
static_cast<time_t
>(time_shield::ms_to_sec(ts_ms));
1054 gmtime_s(&tm, &sec);
1056 gmtime_r(&sec, &tm);
1059 std::strftime(buf,
sizeof(buf),
"%H%M%S", &tm);
1060 std::string timepart(buf);
1063 std::snprintf(msbuf,
sizeof(msbuf),
"%03d",
static_cast<int>(ts_ms % 1000));
1066 std::string rotated = dir +
"/" + base +
"_" + timepart +
".log";
1067# if __cplusplus >= 201703L
1068 if (!fs::exists(rotated))
return rotated;
1071 std::string candidate = rotated.substr(0, rotated.size() - 4) +
"." + std::to_string(idx) +
".log";
1072 if (!fs::exists(candidate))
return candidate;
1075 auto file_exists = [](
const std::string& path) {
1077 std::ifstream f(utf8_to_ansi(path).c_str());
1079 std::ifstream f(path.c_str());
1083 if (!file_exists(rotated))
return rotated;
1086 std::ostringstream oss;
1087 oss << rotated.substr(0, rotated.size() - 4) <<
'.' << idx <<
".log";
1088 std::string candidate = oss.str();
1089 if (!file_exists(candidate))
return candidate;
1096 const int64_t threshold_ts = m_current_date_ts - (time_shield::SEC_PER_DAY * m_config.auto_delete_days);
1097# if __cplusplus >= 201703L
1099 fs::path dir_path = fs::u8path(get_directory_path());
1101 fs::path dir_path(get_directory_path());
1104 if (!fs::exists(dir_path) ||
1105 !fs::is_directory(dir_path)) {
1109 for (
const auto& entry : fs::directory_iterator(dir_path)) {
1110 if (!fs::is_regular_file(entry.status()))
continue;
1111 std::string filename = entry.path().filename().string();
1112 if (is_valid_log_filename(filename)) {
1113 const int64_t file_date_ts = get_date_ts_from_filename(filename);
1114 if (file_date_ts < threshold_ts) {
1115 fs::remove(entry.path());
1120 std::vector<std::string> file_list =
get_list_files(get_directory_path());
1121 for (
const auto& file_path : file_list) {
1123 std::string filename = file_path.substr(file_path.find_last_of(
"/\\") + 1);
1124 if (is_valid_log_filename(filename)) {
1125 const int64_t file_date_ts = get_date_ts_from_filename(filename);
1126 if (file_date_ts < threshold_ts) {
1128 remove(utf8_to_ansi(file_path).c_str());
1130 remove(file_path.c_str());
1142 const std::string plain_name = strip_compression_suffix(filename);
1143 static const std::regex current_pattern(R
"(^\d{4}-\d{2}-\d{2}\.log$)");
1144 static const std::regex sequence_pattern(R
"(^\d{4}-\d{2}-\d{2}\.\d+\.log$)");
1145 static const std::regex timestamp_pattern(R
"(^\d{4}-\d{2}-\d{2}_\d{6}(\d{3})?(\.\d+)?\.log$)");
1146 return std::regex_match(plain_name, current_pattern) ||
1147 std::regex_match(plain_name, sequence_pattern) ||
1148 std::regex_match(plain_name, timestamp_pattern);
1155 return time_shield::ts(filename.substr(0, 10));
1161 return time_shield::start_of_day(time_shield::ms_to_sec(current_timestamp_ms()));
1173 std::lock_guard<std::mutex> lock(m_file_path_mutex);
1180 std::lock_guard<std::mutex> lock(m_file_path_mutex);
1187 return m_last_log_ts;
Defines the interface for loggers used in the logging system.
Logs messages to files with date-based rotation and automatic deletion of old logs.
std::mutex m_mutex
Mutex to protect file operations.
int64_t m_current_date_ts
Timestamp of the current log file's date.
static Config make_config(const std::string &directory, bool async, int auto_delete_days, uint64_t max_file_size_bytes, uint32_t max_rotated_files, bool use_dedicated_executor, std::size_t queue_capacity, QueuePolicy queue_policy)
void stop_logging()
Stops the logging process by closing the file and waiting for tasks.
void initialize_directory()
Initializes the logging directory.
std::string make_rotated_name(const std::string &base, const std::string &dir) const
std::string get_last_log_file_name() const
Retrieves the last log file name.
static FileSortKey make_file_sort_key(const LogFileInfo &info)
void remove_old_logs()
Removes old log files based on the auto-delete days configuration.
std::unique_ptr< detail::CompressionWorker > m_compressor
Background compressor.
int64_t get_date_ts_from_filename(const std::string &filename) const
Extracts the date timestamp from the log filename.
void set_config(const Config &config)
Updates executor-related configuration at runtime.
static bool ends_with_impl(const std::string &value, const std::string &suffix)
FileLogger(const Config &config)
Constructor with custom configuration.
int64_t current_timestamp_ms() const
Gets the current timestamp in milliseconds.
Config m_config
Configuration for the file logger.
int64_t get_time_since_last_log() const
Retrieves the time since the last log.
std::string get_last_log_file_path() const
Retrieves the last log file path.
bool try_make_log_file_info(const std::string &file_path, const std::string ¤t_file_path, LogFileInfo &info) const
FileLogger(const std::string &directory, const bool &async=true, const int &auto_delete_days=30)
Constructor with directory and asynchronous flag.
void rotate_current_file()
std::mutex m_file_path_mutex
Mutex to protect file path operations.
std::string normalize_path_separators(const std::string &path) const
uint64_t m_current_file_size
Current size of the log file.
std::string make_sequence_name(const std::string &base, const std::string &dir) const
void set_log_level(LogLevel level) override
Sets the minimal log level for this logger.
bool ends_with(const std::string &value, const std::string &suffix) const
bool is_direct_child_path(const std::string &file_path, const std::string &directory_path) const
int64_t get_int_param(const LoggerParam ¶m) const override
Retrieves an integer parameter from the logger.
void sort_log_files_newest_first(std::vector< LogFileInfo > &files) const
LogClearResult clear_logs(const LogClearOptions &options=LogClearOptions()) override
Clears managed log files and reopens the current log file.
std::ofstream m_file
Output file stream for logging.
std::atomic< int64_t > m_last_log_ts
Timestamp of the last log.
std::vector< LogFileInfo > list_log_files() const override
Lists persisted log files owned by this backend.
std::string strip_compression_suffix(const std::string &filename) const
std::unique_ptr< detail::SingleThreadExecutor > m_executor
Dedicated executor (null = use global).
virtual ~FileLogger()
Destructor to stop logging and close file.
void start_logging()
Starts the logging process by initializing the file and directory.
bool is_valid_log_filename(const std::string &filename) const
Checks if the filename matches the log file naming pattern.
std::atomic< int64_t > m_last_log_mono_ts
Timestamp of the last log.
bool read_plain_file(const std::string &file_path, std::string &out) const
static std::string strip_compression_suffix_impl(const std::string &filename)
std::string get_string_param(const LoggerParam ¶m) const override
Retrieves a string parameter from the logger.
int64_t get_last_log_ts() const
Retrieves the timestamp of the last log.
FileLogger(const std::string &directory, const bool &async, const int &auto_delete_days, uint64_t max_file_size_bytes, uint32_t max_rotated_files, bool use_dedicated_executor, std::size_t queue_capacity, QueuePolicy queue_policy)
Constructor with directory, rotation, and dedicated executor options.
std::string m_file_path
Path of the currently open log file.
void log(const LogRecord &record, const std::string &message) override
Logs a message to a file with thread safety.
std::atomic< bool > m_shutdown
FileLogger(const std::string &directory, const bool &async, const int &auto_delete_days, bool use_dedicated_executor, std::size_t queue_capacity, QueuePolicy queue_policy)
Constructor with directory, async flag, and dedicated executor options.
FileLogger()
Default constructor that uses default configuration.
int64_t get_current_utc_date_ts() const
Gets the current UTC date timestamp in seconds.
LogFileReadResult read_log_file(const std::string &path) const override
Reads one persisted log file owned by this backend.
std::string make_timestamp_name(const std::string &base, const std::string &dir) const
void open_log_file(const int64_t &date_ts)
Opens a new log file based on the provided date timestamp.
std::string get_directory_path() const
Gets the full path to the logging directory.
void write_log(const std::string &message, const int64_t ×tamp_ms)
Writes a log message to the file.
void enforce_rotation_retention(const std::string &base, uint32_t max_files, const std::string &dir)
std::vector< LogFileReadResult > read_log_files(const std::vector< std::string > &paths) const override
Reads several persisted log files owned by this backend.
bool remove_file_path(const std::string &file_path) const
void shutdown() override
Stops logger-owned asynchronous resources after draining pending writes.
bool set_queue_config(std::size_t queue_capacity, QueuePolicy queue_policy)
Updates queue_capacity and queue_policy at runtime without draining tasks.
std::string create_file_path(int64_t date_ts) const
Creates a file path for the log file based on the date timestamp.
bool is_compressed_log_filename(const std::string &filename) const
LogLevel get_log_level() const override
Gets the minimal log level for this logger.
std::mutex m_lifecycle_mutex
Serializes direct log() calls with shutdown().
std::atomic< int > m_log_level
void wait() override
Waits for all asynchronous tasks to complete.
std::string m_file_name
Name of the currently open log file.
bool same_path(const std::string &lhs, const std::string &rhs) const
FileLogger(const std::string &directory, const bool &async, const int &auto_delete_days, uint64_t max_file_size_bytes, uint32_t max_rotated_files)
Constructor with directory, size-based rotation and additional options.
double get_float_param(const LoggerParam ¶m) const override
Retrieves a floating-point parameter from the logger.
LogFileReadResult read_log_file_from_info(const LogFileInfo &info) const
Optional buffered snapshot access returns empty results by default.
Background worker performing asynchronous compression.
Per-instance single-thread executor for isolated async logging.
void add_task(std::function< void()> task)
Enqueue a task for asynchronous execution.
void wait()
Block until the queue is empty or a shutdown is requested.
static TaskExecutor & get_instance()
Returns the global executor instance.
#define LOGIT_CURRENT_TIMESTAMP_MS()
Macro to get the current timestamp in milliseconds.
#define LOGIT_MONOTONIC_MS()
bool compress_file(CompressType type, const std::string &src, int level, const std::string &external_cmd)
Compress a file using the specified compression type.
QueuePolicy
Queue overflow handling policy used by TaskExecutor and SingleThreadExecutor.
The primary namespace for the LogIt++ library.
std::vector< std::string > get_list_files(const std::string &path)
Recursively retrieves a list of all files in a directory.
RotationNaming
Naming policy for rotated log files.
@ Sequence
Append a numeric sequence: YYYY-MM-DD.001.log.
@ TimestampMs
Append HHMMSSmmm timestamp: YYYY-MM-DD_HHMMSSmmm.log.
@ Timestamp
Append HHMMSS timestamp: YYYY-MM-DD_HHMMSS.log.
@ LOG_LVL_TRACE
Trace level logging.
void create_directories(const std::string &path)
Creates directories recursively for the given path.
LoggerParam
Enumeration for different logger parameters that can be retrieved.
@ TimeSinceLastLog
The time elapsed since the last log in seconds.
@ LastLogTimestamp
The timestamp of the last log.
@ LastFileName
The name of the last file written to.
@ LastFilePath
The full path of the last file written to.
std::string get_file_name(const std::string &file_path)
Extracts the file name from a full file path.
CompressType
Supported compression algorithms for rotated files.
@ NONE
Do not compress rotated files.
detail::QueuePolicy QueuePolicy
Public queue overflow handling policy.
std::string get_exec_dir()
Retrieves the directory of the executable file.
Configuration for the file logger.
std::size_t queue_capacity
Maximum queue size for the dedicated executor (0 = unlimited).
uint32_t seq_width
Width of sequence index.
uint64_t max_file_size_bytes
Max size for log file before rotation (0 = off).
bool use_dedicated_executor
Use a dedicated executor instead of the global TaskExecutor; native builds create one worker thread p...
uint32_t max_rotated_files
Number of rotated files to keep (0 = unlimited).
QueuePolicy queue_policy
Overflow policy for the dedicated executor.
int auto_delete_days
Number of days after which old log files are deleted.
bool async
Flag indicating whether logging should be asynchronous.
bool compress_async
Run compression in background thread.
std::string external_cmd
External command template.
CompressType compress
Compression algorithm for rotated files.
int compress_level
Compression level.
std::string directory
Directory where log files are stored.
RotationNaming naming
Naming policy for rotated files.
std::string artifact_name
Selects which data categories a logger cleanup should remove.
Result returned by logger cleanup operations.
std::string message
Optional diagnostic or unsupported reason.
std::size_t cleared_records
Number of primary records/files cleared when available.
LogClearStatus status
Detailed cleanup status.
bool ok
True when the backend completed cleanup.
Metadata for a persisted log file owned by a logger backend.
std::string name
File name without the parent directory.
bool is_current
True when this is the file currently used for appends.
int64_t day_start_ms
Start-of-day UTC timestamp derived from the file name.
std::string path
Full path to the file.
bool is_compressed
True when the file is a compressed rotated artifact.
Result of reading a persisted log file from a file-based backend.
LogFileInfo file
Metadata for the requested file.
bool ok
Whether the read succeeded.
std::string content
File contents when the read succeeded.
Stores log metadata and content.
const int64_t timestamp_ms
Timestamp in milliseconds.