userver: userver/utest/default_logger_fixture.hpp Source File
Loading...
Searching...
No Matches
default_logger_fixture.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utest/default_logger_fixture.hpp
4/// @brief @copybrief utest::DefaultLoggerFixture
5
6#include <vector>
7
8#include <userver/logging/log.hpp>
9#include <userver/utils/assert.hpp>
10
11USERVER_NAMESPACE_BEGIN
12
13namespace utest {
14
15/// @brief Fixture that allows to set the default logger and manages its
16/// lifetime.
17template <class Base>
18class DefaultLoggerFixture : public Base {
19 public:
20 static void TearDownTestSuite() {
21 Base::TearDownTestSuite();
22 once_used_loggers_.clear();
23 }
24
25 protected:
26 /// Set the default logger and postpone its destruction till the coroutine
27 /// engine stops
28 void SetDefaultLogger(logging::LoggerPtr new_logger) {
29 UASSERT(new_logger);
30 BackUpDefaultLogger();
31 logging::impl::SetDefaultLoggerRef(*new_logger);
32
33 // Logger could be used by the ev-thread, so we postpone the
34 // destruction of logger for the lifetime of coroutine engine.
35 once_used_loggers_.emplace_back(std::move(new_logger));
36 }
37
38 /// Set the default logger level
40 BackUpDefaultLogger();
42 }
43
44 ~DefaultLoggerFixture() override { RestoreDefaultLogger(); }
45
46 private:
47 void BackUpDefaultLogger() {
48 if (!logger_initial_) {
49 logger_initial_ = &logging::GetDefaultLogger();
50 level_initial_ = logging::GetLoggerLevel(*logger_initial_);
51 }
52 }
53
54 void RestoreDefaultLogger() noexcept {
55 if (logger_initial_) {
56 logging::impl::SetDefaultLoggerRef(*logger_initial_);
57 logging::SetLoggerLevel(*logger_initial_, level_initial_);
58 }
59 }
60
61 logging::impl::LoggerBase* logger_initial_{nullptr};
62 logging::Level level_initial_{};
63
64 static inline std::vector<logging::LoggerPtr> once_used_loggers_;
65};
66
67} // namespace utest
68
69USERVER_NAMESPACE_END