userver: userver/utest/log_capture_fixture.hpp Source File
Loading...
Searching...
No Matches
log_capture_fixture.hpp
Go to the documentation of this file.
1#pragma once
2
6
7#include <iosfwd>
8#include <optional>
9#include <string>
10#include <string_view>
11#include <utility>
12#include <vector>
13
14#include <gtest/gtest.h>
15
16#include <userver/logging/impl/logger_base.hpp>
21#include <userver/utils/impl/internal_tag.hpp>
22#include <userver/utils/impl/source_location.hpp>
25
26USERVER_NAMESPACE_BEGIN
27
28namespace utest {
29
30namespace impl {
31class ToStringLogger;
32} // namespace impl
33
40class LogRecord final {
41public:
44 const std::string& GetText() const;
45
48 const std::string& GetTag(std::string_view key) const;
49
51 std::optional<std::string> GetTagOptional(std::string_view key) const;
52
54 const std::string* GetTagOrNullptr(std::string_view key) const;
55
57 const std::string& GetLogRaw() const;
58
61
63 // For internal use only.
64 LogRecord(utils::impl::InternalTag, logging::Level level, std::string&& log_raw);
66
67private:
68 logging::Level level_;
69 std::string log_raw_;
70 std::vector<std::pair<std::string, std::string>> tags_;
71};
72
73std::ostream& operator<<(std::ostream&, const LogRecord& data);
74
75std::ostream& operator<<(std::ostream&, const std::vector<LogRecord>& data);
76
78class NotSingleLogError final : public std::runtime_error {
79public:
80 using std::runtime_error::runtime_error;
81};
82
87 const utils::impl::SourceLocation& source_location = utils::impl::SourceLocation::Current()
88);
89
92std::vector<LogRecord> ParseTskvLogRecords(std::string_view tskv_log_contents);
93
101class LogCaptureLogger final {
102public:
103 explicit LogCaptureLogger(logging::Format format = logging::Format::kRaw);
104
106 logging::TextLoggerPtr GetLogger() const;
107
110 std::vector<LogRecord> GetAll() const;
111
114 std::vector<LogRecord> Filter(
115 std::string_view text_substring,
116 utils::span<const std::pair<std::string_view, std::string_view>> tag_substrings = {}
117 ) const;
118
121 std::vector<LogRecord> Filter(utils::function_ref<bool(const LogRecord&)> predicate) const;
122
124 void Clear() noexcept;
125
127 template <typename T>
128 std::string ToStringViaLogging(const T& value) {
129 Clear();
130 LOG_CRITICAL() << value;
131 auto text = GetSingleLog(GetAll()).GetText();
132 Clear();
133 return text;
134 }
135
136private:
138};
139
147template <typename Base = ::testing::Test>
148class LogCaptureFixture : public DefaultLoggerFixture<Base> {
149protected:
150 LogCaptureFixture() { DefaultLoggerFixture<Base>::SetDefaultLogger(logger_.GetLogger()); }
151
153 LogCaptureLogger& GetLogCapture() { return logger_; }
154
155private:
156 LogCaptureLogger logger_;
157};
158
159} // namespace utest
160
161USERVER_NAMESPACE_END