Circular file logging

2019-06-27 10:12发布

I would like to know if there are any logger libraries for C , that can do circular file logging?

I am currently looking at log4C, But cant find enough docs on it that can say it will do circular logging.

if anyone has done this. kindly let me know.

Thanks

标签: c logging
3条回答
Juvenile、少年°
2楼-- · 2019-06-27 10:19

It seems Log4C is not painfully well documented at this point. They do point at the Log4J page though, which mentioned "rolling" logs, is that perhaps what you want? It could be just a question of terminology confusion.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-27 10:26

Are you really sure you want circular logging? I think you would be better off with rolling logs.

i.e.

circular logging: log to log.1 then log.2 then log.3 then log.4 then back log.1

rolling logging: have four log files, where log.1 is always the most recent, and log.2,3,4 are older log entries?

查看更多
仙女界的扛把子
4楼-- · 2019-06-27 10:27

here is an example

This is a cut down version. In ours we use vargs and format them before calling log_it.


typedef const char* c_str;
FILE* log_fp = 0;
const int max_log_size = 4 * 1024 * 1024;
const int max_no = 5;
c_str prefix = "logs_";
c_str postfix = ".txt";

void log_it( c_str str )
    {
    char file1[100], file2[100];

    if( ! log_fp )
        {
        sprintf( file1 "%s%d%s", prefix, 0, postfix );
        log_fp = fopen( file1, "a" );
        }

    if( log_fp )
        {
        if( ftell( log_fp ) > max_log_size )
            {
            fclose( log_fp );
            log_fp = 0;

            for( int i = (max_no - 1); i >= 0; i-- )
                {
                sprintf( file1 "%s%d%s", prefix, i, postfix );
                sprintf( file1 "%s%d%s", prefix, i+1, postfix );
                rename( file1, file2 );
                }

            sprintf( file1 "%s%d%s", prefix, 0, postfix );
            log_fp = fopen( file1, "a" );
            }

        fputs( str, log_fp );
        fflush( log_fp );
        }
    }

I hope that helps.

dave

查看更多
登录 后发表回答