Branch data Line data Source code
1 : : // Copyright 2026 HPActor Contributors
2 : : //
3 : : // Licensed under the Apache License, Version 2.0 (the "License");
4 : : // you may not use this file except in compliance with the License.
5 : : // You may obtain a copy of the License at
6 : : //
7 : : // http://www.apache.org/licenses/LICENSE-2.0
8 : : //
9 : : // Unless required by applicable law or agreed to in writing, software
10 : : // distributed under the License is distributed on an "AS IS" BASIS,
11 : : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : : // See the License for the specific language governing permissions and
13 : : // limitations under the License.
14 : :
15 : : #include <fstream>
16 : : #include <hpactor/log/log_sink.hpp>
17 : : #include <mutex>
18 : :
19 : : namespace hpactor::log {
20 : :
21 : : class FileSink : public ILogSink {
22 : : public:
23 : 3 : explicit FileSink(const std::string& path)
24 : 3 : : file_(path, std::ios::app | std::ios::out) {}
25 : :
26 : 3 : result<void> write(std::string_view line) noexcept override {
27 : 3 : std::lock_guard<std::mutex> lock(mutex_);
28 : 3 : if (!file_.is_open())
29 : 0 : return result<void>::make(error(errors::unknown, "file sink not "
30 : 0 : "open"));
31 : 3 : file_.write(line.data(), static_cast<std::streamsize>(line.size()));
32 : 3 : file_.put('\n');
33 : 3 : if (file_.fail())
34 : 0 : return result<void>::make(error(errors::unknown, "file sink write "
35 : 0 : "failed"));
36 : 3 : return result<void>::make();
37 : 3 : }
38 : :
39 : 2 : result<void> flush() noexcept override {
40 : 2 : std::lock_guard<std::mutex> lock(mutex_);
41 : 2 : if (file_.is_open())
42 : 2 : file_.flush();
43 : 2 : return result<void>::make();
44 : 2 : }
45 : :
46 : : private:
47 : : std::ofstream file_;
48 : : std::mutex mutex_;
49 : : };
50 : :
51 : 3 : std::unique_ptr<ILogSink> make_file_sink(const std::string& path) {
52 : 3 : return std::make_unique<FileSink>(path);
53 : : }
54 : :
55 : : } // namespace hpactor::log
|