aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/logger/reopen.h
blob: 47f44be11b6acf18b9098c182e35f399259e1d83 (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
#pragma once

#include "log.h"
#include "backend.h"

#include <util/generic/fwd.h>
#include <util/generic/ptr.h>
#include <util/generic/size_literals.h>

#include <atomic>

class TReopenLogBackend: public TLogBackend {
public:
    explicit TReopenLogBackend(THolder<TLogBackend>&& backend, ui64 bytesWrittenLimit = 1_GB)
        : Backend_(std::move(backend)), BytesWrittenLimit_(bytesWrittenLimit), BytesWritten_(0) {
            Y_ENSURE(BytesWrittenLimit_ > 0);
    }

    void WriteData(const TLogRecord& rec) override {
        const ui64 prevWritten = BytesWritten_.fetch_add(rec.Len);
        if (prevWritten < BytesWrittenLimit_ && prevWritten + rec.Len >= BytesWrittenLimit_) {
            try {
                ReopenLog();
            } catch (...) {
            }
        }
        Backend_->WriteData(rec);
    }

    void ReopenLog() override {
        BytesWritten_.store(0);
        Backend_->ReopenLog();
    }

private:
    const THolder<TLogBackend> Backend_;

    const ui64 BytesWrittenLimit_;
    std::atomic<ui64> BytesWritten_;
};