MayaFlux 0.1.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
FileSink.hpp
Go to the documentation of this file.
1#pragma once
2
4#include "Sink.hpp"
5
6namespace MayaFlux::Journal {
7
8class MAYAFLUX_API FileSink : public Sink {
9public:
10 explicit FileSink(const std::string& filepath,
11 size_t max_file_size_mb = 10)
12 : writer_(std::make_unique<IO::TextFileWriter>())
13 {
14 writer_->set_max_file_size(max_file_size_mb * 1024 * 1024);
15 writer_->open(filepath,
16 IO::FileWriteOptions::CREATE | IO::FileWriteOptions::APPEND);
17 }
18
19 ~FileSink() override
20 {
21 if (writer_) {
22 writer_->close();
23 }
24 }
25
26 void write(const JournalEntry& entry) override
27 {
28 if (!writer_ || !writer_->is_open())
29 return;
30
31 auto line = format_entry(entry);
32 writer_->write_line(line);
33 }
34
35 void write(const RealtimeEntry& entry) override
36 {
37 if (!writer_ || !writer_->is_open())
38 return;
39
40 auto line = format_entry(entry);
41 writer_->write_line(line);
42 }
43
44 void flush() override
45 {
46 if (writer_) {
47 writer_->flush();
48 }
49 }
50
51 [[nodiscard]] bool is_available() const override
52 {
53 return writer_ && writer_->is_open();
54 }
55
56private:
57 template <typename Entry>
58 std::string format_entry(const Entry& entry)
59 {
60 std::ostringstream oss;
61
62 auto time = std::chrono::system_clock::now();
63 auto time_t = std::chrono::system_clock::to_time_t(time);
64 oss << "[" << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S") << "]";
65
66 oss << "[" << Utils::enum_to_string(entry.severity) << "]"
67 << "[" << Utils::enum_to_string(entry.component) << "]"
68 << "[" << Utils::enum_to_string(entry.context) << "] ";
69
70 if constexpr (std::is_same_v<Entry, JournalEntry>) {
71 oss << entry.message;
72 if (entry.location.file_name() != nullptr) {
73 oss << " (" << entry.location.file_name()
74 << ":" << entry.location.line() << ")";
75 }
76 } else {
77 oss << entry.message;
78 if (entry.file_name != nullptr) {
79 oss << " (" << entry.file_name
80 << ":" << entry.line << ")";
81 }
82 }
83
84 return oss.str();
85 }
86
87 std::unique_ptr<IO::TextFileWriter> writer_;
88};
89
90} // namespace MayaFlux::Journal
std::string format_entry(const Entry &entry)
Definition FileSink.hpp:58
bool is_available() const override
Check if sink is available/healthy.
Definition FileSink.hpp:51
void flush() override
Flush any buffered writes.
Definition FileSink.hpp:44
void write(const RealtimeEntry &entry) override
Write a realtime entry to this sink.
Definition FileSink.hpp:35
FileSink(const std::string &filepath, size_t max_file_size_mb=10)
Definition FileSink.hpp:10
void write(const JournalEntry &entry) override
Write a journal entry to this sink.
Definition FileSink.hpp:26
std::unique_ptr< IO::TextFileWriter > writer_
Definition FileSink.hpp:87
@ IO
Networking, file handling, streaming.
A log entry structure to encapsulate log message details.
Lightweight entry for lock-free ring buffer.