107 lines
2.7 KiB
C++
107 lines
2.7 KiB
C++
#include <Void/Log/RotatingFileLogger.hpp>
|
|
#include <Void/Log/Log.hpp>
|
|
|
|
#include <format>
|
|
#include <stdexcept>
|
|
|
|
namespace Void::Logging
|
|
{
|
|
|
|
RotatingFileLogger::RotatingFileLogger(const std::filesystem::path& path,
|
|
Options options)
|
|
: Logger(LoggerOptions{
|
|
.mode = options.mode,
|
|
.policy = options.policy,
|
|
.limits = DeliveryLimits{
|
|
.entries = options.capacity > 0 ? options.capacity : 1,
|
|
.owned_bytes = std::max<std::size_t>(
|
|
8ULL * 1024ULL * 1024ULL,
|
|
(options.capacity > 0 ? options.capacity : 1) * 1024ULL),
|
|
.max_fields = 64,
|
|
.max_scopes = 64},
|
|
.failure_policy = FailurePolicy::Quarantine,
|
|
.suppress_reentrancy = false}),
|
|
m_path(path),
|
|
m_file(path,
|
|
Detail::RollingFileOptions{options.max_bytes,
|
|
options.max_files,
|
|
options.create_directories})
|
|
{
|
|
if (!m_file.open()) {
|
|
throw std::runtime_error(std::format(
|
|
"RotatingFileLogger: cannot open '{}'", m_path.string()));
|
|
}
|
|
Void::Log::debug("Log.RotatingFile", "opened '{}'", m_path.string());
|
|
}
|
|
|
|
Void::Result::Result<std::unique_ptr<RotatingFileLogger>,
|
|
Void::Result::Error>
|
|
RotatingFileLogger::open(const std::filesystem::path& path,
|
|
Options options)
|
|
{
|
|
try {
|
|
return Void::Result::ok(
|
|
std::make_unique<RotatingFileLogger>(path, options));
|
|
} catch (const std::exception& e) {
|
|
return Void::Result::fail(make_log_error(
|
|
LogErrorCode::io_error, std::string{e.what()}));
|
|
}
|
|
}
|
|
|
|
RotatingFileLogger::~RotatingFileLogger() noexcept { flush(); }
|
|
|
|
Void::Result::Result<void> RotatingFileLogger::reopen()
|
|
{
|
|
flush();
|
|
if (!m_file.reopen()) {
|
|
return Void::Result::fail(make_log_error(
|
|
LogErrorCode::io_error,
|
|
std::format("RotatingFileLogger::reopen failed for '{}'",
|
|
m_path.string())));
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Void::Result::Result<void> RotatingFileLogger::sync_files()
|
|
{
|
|
flush();
|
|
if (is_quarantined()) {
|
|
return Void::Result::fail(make_log_error(
|
|
LogErrorCode::io_error, last_error_summary()));
|
|
}
|
|
return m_file.sync();
|
|
}
|
|
|
|
void RotatingFileLogger::write(const Entry& entry)
|
|
{
|
|
append(entry);
|
|
m_file.flush();
|
|
}
|
|
|
|
void RotatingFileLogger::on_flush(std::span<const Entry> entries)
|
|
{
|
|
for (const auto& entry : entries) {
|
|
append(entry);
|
|
}
|
|
m_file.flush();
|
|
}
|
|
|
|
void RotatingFileLogger::append(const Entry& entry)
|
|
{
|
|
if (m_formatter) {
|
|
auto bounded = format_bounded(
|
|
*m_formatter,
|
|
entry,
|
|
delivery_limits().max_format_scratch_bytes,
|
|
delivery_limits().truncate_oversize);
|
|
if (!bounded) {
|
|
throw std::runtime_error(bounded.error().message());
|
|
}
|
|
m_file.write(*bounded);
|
|
} else {
|
|
m_file.write(
|
|
std::format("[{}] {}", to_string(entry.level), entry.message));
|
|
}
|
|
}
|
|
|
|
} // namespace Void::Logging
|