Java concepts in C: logging


One will always run into the problem that one needs more detailed output from a section at some time, and less verbose output at another time. Or the whole output should be more verbose, or you want to investigate a segfault.

There are some logging libraries (log4c for example). I however use the following approach:



debug.h:

#ifdef DEBUG

#define IFDEBUG if(1)

#else

#define IFDEBUG if(0)

#endif

#ifdef SEGV

#define IFSEGV if(1)

#else

#define IFSEGV if(0)

#endif

#define debug(str)        IFDEBUG { printf("\tDEBUG[%s]: %s\n", AT, str); fflush(NULL); }

#define dump_i(str, var)  IFDEBUG { printf("\tDEBUG[%s]: %s: %i\n", AT, str, var); fflush(NULL); }

#define dump_p(str, var)  IFDEBUG { printf("\tDEBUG[%s]: %s: %p\n", AT, str, var); fflush(NULL); }

in your code:

		debug("we are now doing foo ");

		IFSEGV

			dump_p("m\n", (void*)m);

		IFDEBUG

			printf("\t\tn_par=%d; status=%d\n", get_n_par(m), status);

Example output:

	DEBUG[tests/tests.c:196]: add starting points, ...

This allows you to recompile your code with -DDEBUG -DSEGV and enable/disable verbosity levels without constant code changes.

  1. #1 by JohannesBuchner on August 1st, 2010

    REPLY:
    Thanks, I never got around to look at variable arguments in the preprocessor

  2. #2 by panzi on April 18th, 2009

    I prefer something like this (requires C99):

    debug.h:

    #ifndef DEBUG_H__
    #define DEBUG_H__
    #include <stdio.h>
    #ifdef DEBUG
    #   define debugf(fmt, ...) \
    fprintf(stderr, "%s:%d: %s: " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)
    #else
    #   define debugf(fmt, ...)
    #endif
    #endif
    

    main.c:

    #include "debug.h"
    int main() {
    debugf("foo %s bar %d baz %f", "...", 42, 3.1415);
    return 0;
    }

    stderr should be unbuffered anyway, so I don’t need a fflush(stderr).

(will not be published)

  1. No trackbacks yet.