xref: /aosp_15_r20/external/webrtc/test/logging/file_log_writer.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright 2019 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 #include "test/logging/file_log_writer.h"
11 
12 #include <memory>
13 
14 #include "absl/strings/string_view.h"
15 #include "rtc_base/checks.h"
16 #include "rtc_base/logging.h"
17 #include "test/testsupport/file_utils.h"
18 
19 namespace webrtc {
20 namespace webrtc_impl {
21 
FileLogWriter(absl::string_view file_path)22 FileLogWriter::FileLogWriter(absl::string_view file_path)
23     : out_(std::fopen(std::string(file_path).c_str(), "wb")) {
24   RTC_CHECK(out_ != nullptr)
25       << "Failed to open file: '" << file_path << "' for writing.";
26 }
27 
~FileLogWriter()28 FileLogWriter::~FileLogWriter() {
29   std::fclose(out_);
30 }
31 
IsActive() const32 bool FileLogWriter::IsActive() const {
33   return true;
34 }
35 
Write(absl::string_view value)36 bool FileLogWriter::Write(absl::string_view value) {
37   // We don't expect the write to fail. If it does, we don't want to risk
38   // silently ignoring it.
39   RTC_CHECK_EQ(std::fwrite(value.data(), 1, value.size(), out_), value.size())
40       << "fwrite failed unexpectedly: " << errno;
41   return true;
42 }
43 
Flush()44 void FileLogWriter::Flush() {
45   RTC_CHECK_EQ(fflush(out_), 0) << "fflush failed unexpectedly: " << errno;
46 }
47 
48 }  // namespace webrtc_impl
49 
FileLogWriterFactory(absl::string_view base_path)50 FileLogWriterFactory::FileLogWriterFactory(absl::string_view base_path)
51     : base_path_(base_path) {
52   for (size_t i = 0; i < base_path.size(); ++i) {
53     if (base_path[i] == '/')
54       test::CreateDir(base_path.substr(0, i));
55   }
56 }
57 
~FileLogWriterFactory()58 FileLogWriterFactory::~FileLogWriterFactory() {}
59 
Create(absl::string_view filename)60 std::unique_ptr<RtcEventLogOutput> FileLogWriterFactory::Create(
61     absl::string_view filename) {
62   return std::make_unique<webrtc_impl::FileLogWriter>(base_path_ +
63                                                       std::string(filename));
64 }
65 }  // namespace webrtc
66