Makistos
10/28/2013 - 7:51 AM

This function can be used just like printf() but it will add the file name and line number to each print making this much more useful as a l

This function can be used just like printf() but it will add the file name and line number to each print making this much more useful as a log print.

Add the MY_PRINTF() macro where you want to have a log print and it will add the file name and line number automatically to the log print.

#c-ellipsis #logging #c

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

#define MAX_PRINT_LEN 1000
#define MY_PRINTF(str, ...) my_printf(__FILE__, __LINE__, str, __VA_ARGS__)

/** Printf() like function for logging.
 *
 *  my_printf() attaches file name and line number
 *  in front of the printed string.
 *
 *  @param[in] file File name where the call was made.
 *  @param[in] line Line number where the call was made.
 *  @param[in] str printf() style formatted string.
 *
 */

void my_printf(const char *file, const int line, const char *str, ...)
{
        va_list args;
        char *tmp_buf;

        if (str == NULL) {
                return;
        }

        tmp_buf = (char *)malloc(MAX_PRINT_LEN);
        if (tmp_buf != NULL) {
                va_start(args, str);
                (void)vsnprintf(tmp_buf, MAX_PRINT_LEN, str, args);
                fprintf(stderr, "%s (%d): %s", file, line, tmp_buf);
                va_end(args);

                free(tmp_buf);
        }

        return;
}