Linux / C ++ Log Rotation Scheme

I have a logging system which basically is a fancy way to write my data to std :: clog in safe streaming mode.

I also redirect std::clogto the file as follows:

int main() {
    std::ofstream logfile(config::logname, std::ios::app);
    std::streambuf *const old_buffer = std::clog.rdbuf(logfile.rdbuf());

    // .. the guts of the application

    std::clog.rdbuf(old_buffer);
}

This works fine ... however, my application also creates a very large number of logs. I was wondering what would be a good way to rotate my log files correctly. Is there a safe way to switch a file using the cron task? I think no.

The only thing I can think of would definitely work if I myself opened the application for a new file and redirected rdbuf clog to it while holding the log mutexes. But this seems like a cheap solution, and I will need to check if it is time to rotate the magazines often so that they are effective. There has to be a better way.

+3
source share
3 answers

You can use the built-in log rotation method configured in the /etc/logrotate.conf and / or / etc / logrotate.d / file - this is the usual way to make logrotate send your SIGUSR1 application as a signal, open all your log files.

+14
source

syslog , logrotate. - , , / .

+6

You can use something similar to the following and transfer the log file regardless of the path (logrotate, cron script, etc.) (providing a Cish sample should be easily convertible)

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

void logworker()
{
    ino_t inode = 0;
    FILE *logfile;

    logfile = fopen(logfilename, "a+");
    while(running)
    {
        struct stat mystat;

        if (stat(logfilename, &mystat)!=0 || mystat.st_ino != inode)
        {
            logfile = freopen(logfilename, "a+", logfile);
            inode = mystat.st_ino;
        }

        while (stuff_in_buffer)
        {
            fwrite(); /* etc */
        }
        fflush(logfile);

        /* sleep until something interesting happens */
    }
}

It is safe to write to a file after moving it, so there is no need for special care

0
source

Source: https://habr.com/ru/post/1702253/


All Articles