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
3/// @file userver/utest/log_capture_fixture.hpp
4/// @brief @copybrief utest::LogCaptureFixture
5
6#include <userver/concurrent/variable.hpp>
7#include <userver/logging/impl/logger_base.hpp>
8#include <userver/utest/default_logger_fixture.hpp>
9#include <userver/utest/utest.hpp>
10
11USERVER_NAMESPACE_BEGIN
12
13namespace utest {
14
15namespace impl {
16
17/// @brief Thread-safe logger that allows to capture and extract log.
18class ToStringLogger : public logging::impl::LoggerBase {
19 public:
20 ToStringLogger() noexcept : logging::impl::LoggerBase(logging::Format::kRaw) {
21 logging::impl::LoggerBase::SetLevel(logging::Level::kInfo);
22 }
23
24 void Log(logging::Level level, std::string_view str) override {
25 auto locked_ptr = log_.Lock();
26 *locked_ptr += fmt::format("level={}\t{}", logging::ToString(level), str);
27 }
28
29 std::string ExtractLog() {
30 auto locked_ptr = log_.Lock();
31 return std::exchange(*locked_ptr, std::string{});
32 }
33
34 private:
35 concurrent::Variable<std::string, std::mutex> log_;
36};
37
38} // namespace impl
39
40/// @brief Fixture that allows to capture and extract log.
41template <typename Base = ::testing::Test>
42class LogCaptureFixture : public utest::DefaultLoggerFixture<Base> {
43 protected:
44 LogCaptureFixture() : logger_(std::make_shared<impl::ToStringLogger>()) {
45 utest::DefaultLoggerFixture<Base>::SetDefaultLogger(logger_);
46 }
47
48 /// Extract and clear current log
49 std::string ExtractRawLog() { return logger_->ExtractLog(); }
50
51 private:
52 std::shared_ptr<impl::ToStringLogger> logger_;
53};
54
55} // namespace utest
56
57USERVER_NAMESPACE_END