summaryrefslogtreecommitdiffstats
path: root/yql/essentials/utils/log/tls_backend.h
blob: 802a73aae90df9acaa9a4acf2c082cc05d4e25d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#pragma once

#include <library/cpp/logger/backend.h>

#include <util/generic/ptr.h>

#include <utility>


namespace NYql {
namespace NLog {

/**
 * @brief Dispatches all invocations to default logger backend configured
 *        for current thread. Must be used in conjunction with
 *        SetLogBackendForCurrentThread() function or TScopedBackend class.
 */
class TTlsLogBackend: public TLogBackend {
public:
    TTlsLogBackend(TAutoPtr<TLogBackend> defaultBackend)
        : DefaultBackend_(defaultBackend)
    {
        Y_DEBUG_ABORT_UNLESS(DefaultBackend_, "default backend is not set");
    }

    void WriteData(const TLogRecord& rec) override;
    void ReopenLog() override;
    ELogPriority FiltrationLevel() const override;

private:
    TAutoPtr<TLogBackend> DefaultBackend_;
};

/**
 * @brief Sets given backend as default for current thread. Must be used in
 *        conjunction with TTlsLogBackend.
 *
 * @param backend - pointer to logger backend
 * @return previous default logger backend
 */
TLogBackend* SetLogBackendForCurrentThread(TLogBackend* backend);

/**
 * @brief Sets itself as default for current thread on instantiation
 *        and restores previous one on destruction. Must be used in
 *        conjunction with TTlsLogBackend.
 */
template <typename TBackend>
class TScopedBackend: public TBackend {
public:
    template <typename... TArgs>
    TScopedBackend(TArgs&&... args)
        : TBackend(std::forward<TArgs>(args)...)
        , PrevBacked_(SetLogBackendForCurrentThread(this))
    {
    }

    ~TScopedBackend() {
        SetLogBackendForCurrentThread(PrevBacked_);
    }

private:
    TLogBackend* PrevBacked_;
};

} // namspace NLog
} // namspace NYql