aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/logger/rotating_file.cpp
blob: 3391d2600258b6b3b4833a59ae7c74271b64acec (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "rotating_file.h"
#include "file.h"
#include "record.h"

#include <util/string/builder.h> 
#include <util/system/fstat.h>
#include <util/system/rwlock.h>
#include <util/system/fs.h>
#include <util/system/atomic.h>
#include <util/generic/string.h>

/*
 * rotating file log
 * if Size_ > MaxSizeBytes 
 *    Path.(N-1) -> Path.N 
 *    Path.(N-2) -> Path.(N-1) 
 *    ... 
 *    Path.1     -> Path.2 
 *    Path       -> Path.1 
 */
class TRotatingFileLogBackend::TImpl {
public:
    inline TImpl(const TString& path, const ui64 maxSizeBytes, const ui32 rotatedFilesCount) 
        : Log_(path) 
        , Path_(path) 
        , MaxSizeBytes_(maxSizeBytes) 
        , Size_(TFileStat(Path_).Size) 
        , RotatedFilesCount_(rotatedFilesCount) 
    { 
        Y_ENSURE(RotatedFilesCount_ != 0); 
    } 
 
    inline void WriteData(const TLogRecord& rec) {
        if (static_cast<ui64>(AtomicGet(Size_)) > MaxSizeBytes_) {
            TWriteGuard guard(Lock_);
            if (static_cast<ui64>(AtomicGet(Size_)) > MaxSizeBytes_) {
                TString newLogPath(TStringBuilder{} << Path_ << "." << RotatedFilesCount_); 
                for (size_t fileId = RotatedFilesCount_ - 1; fileId; --fileId) { 
                    TString oldLogPath(TStringBuilder{} << Path_ << "." << fileId); 
                    NFs::Rename(oldLogPath, newLogPath); 
                    newLogPath = oldLogPath; 
                } 
                NFs::Rename(Path_, newLogPath); 
                Log_.ReopenLog();
                AtomicSet(Size_, 0);
            }
        }
        TReadGuard guard(Lock_);
        Log_.WriteData(rec);
        AtomicAdd(Size_, rec.Len);
    }

    inline void ReopenLog() {
        TWriteGuard guard(Lock_);

        Log_.ReopenLog();
        AtomicSet(Size_, TFileStat(Path_).Size); 
    }

private:
    TRWMutex Lock_;
    TFileLogBackend Log_;
    const TString Path_; 
    const ui64 MaxSizeBytes_;
    TAtomic Size_;
    const ui32 RotatedFilesCount_; 
};

TRotatingFileLogBackend::TRotatingFileLogBackend(const TString& path, const ui64 maxSizeByte, const ui32 rotatedFilesCount) 
    : Impl_(new TImpl(path, maxSizeByte, rotatedFilesCount)) 
{ 
} 
 
TRotatingFileLogBackend::~TRotatingFileLogBackend() {
}

void TRotatingFileLogBackend::WriteData(const TLogRecord& rec) {
    Impl_->WriteData(rec);
}

void TRotatingFileLogBackend::ReopenLog() {
    TAtomicSharedPtr<TImpl> copy = Impl_;
    if (copy) {
        copy->ReopenLog();
    }
}