Take the 2-minute tour ×

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.


share|improve this question

3 Answers 3

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 );

            log_fp = fopen( file1, "a" );

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

I hope that helps.


share|improve this answer
That's rolling logging not circular logging. Also log_fp = 0; should probably be log_fp = -1; but that doesn't matter hugely since it will always get overwritten. –  Douglas Leeder Mar 4 '09 at 10:30
In fact you might have a problem if log_fp = fopen( file1, "a" ); ever returns 0 as the file descriptor. –  Douglas Leeder Mar 4 '09 at 10:31
I think you are confusing open(2) and fopen(3) –  David Allan Finch Mar 4 '09 at 10:33
I would think that using an static int and mod any one should be able to change this to a circular logging. –  David Allan Finch Mar 4 '09 at 10:35
Also this code can be improved in lots of ways. But if should help some one start to do it themselves ;) –  David Allan Finch Mar 4 '09 at 10:38

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


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?

share|improve this answer
why not? on running on a development enviroment you can quickly running out of disk-space of you are producing large logs. at my workplace we use rolling logs because of the large number of processes and debug output –  hhafez Mar 4 '09 at 9:52
He's asking for circular logging, and I think he probably should want rolling logging. I don't understand why you ask "why not?". –  Douglas Leeder Mar 4 '09 at 10:25

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.

share|improve this answer

Your Answer

