File: rotatingstreambuf.h

package info (click to toggle)
natlog 3.01.00-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,912 kB
  • sloc: cpp: 3,691; fortran: 201; sh: 133; ansic: 123; makefile: 110
file content (92 lines) | stat: -rw-r--r-- 2,275 bytes parent folder | download | duplicates (3)
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
87
88
89
90
91
92
#ifndef INCLUDED_ROTATABLESTREAMBUF_
#define INCLUDED_ROTATABLESTREAMBUF_

#include <streambuf>
#include <fstream>
#include <iosfwd>
#include <thread>
#include <bobcat/semaphore>

class RotatingStreambuf: public std::streambuf
{
    std::mutex d_mutex;
    bool d_locked = false;
    volatile bool d_content = false;

    std::ofstream d_out;
    std::string d_name;

    int (RotatingStreambuf::*d_overflow)(int ch);
    void (*d_header)(std::ostream &);

    struct RotationInfo
    {
        RotatingStreambuf *rotationStreambuf;
        size_t lastRotation = 0;
        std::mutex rotationMutex;
    };

    static RotationInfo s_stdRotate;
    static RotationInfo s_dataRotate;

    static FBB::Semaphore s_semaphore;
    static std::thread s_rotateThread;
  
    public:
        RotatingStreambuf(void (*header)(std::ostream &) = 0);
        ~RotatingStreambuf() override;

        void open(std::string const &name, bool stdLog);
        static void notify();

        static void startThread();

        static void logRotate();                                        // .h
        static void dataRotate();                                       // .h

    private:
        int unlockedOverflow(int ch);
        int lockedOverflow(int ch);

                                                // called by rotateSthread at
                                                // --log-rotate time intervals 
        static void rotate();                                           // 1

        void rotate(size_t nRotations);                                 // 2

                                                // rotates the 'info' log-file
        static void rotate(RotationInfo &info);                         // 3

        static void rotateThread();

        static bool rotationsRequested();                               // .ih

        int overflow(int ch)    override;
        int sync()              override;
};

inline RotatingStreambuf::RotatingStreambuf(void (*header)(std::ostream &))
:
    d_header(header)
{}

// static
inline void RotatingStreambuf::logRotate()      // rotate the std. log file
{
    rotate(s_stdRotate);
}

// static
inline void RotatingStreambuf::dataRotate()     // rotate the data log file
{
    rotate(s_dataRotate);
}

#endif