Search code examples
clinuxmacrosoutput-redirect

Why and how do we redirect debug statements?


I want to know why is it preferred to redirect the debug statements to stderr like it is done here:

#ifdef DEBUG_TEST
  #define DEBUG_TEST 1
  #else
  #define DEBUG_TEST 0
  #endif

  #define DEBUG_PRINT(fmt, ...) \
             do { if (DEBUG_TEST) fprintf(stderr, fmt, ##__VA_ARGS__); } while (0)

Also: How can we redirect these debug statements to a separate log file with a timestamp on that file? I want to do this using a macro in my code.

Platform: Linux, gcc compiler


Solution

  • I can give you two examples of why you would do this: You could then easily redirect standard output to a file while keeping standard error in your terminal (and this seems to be exactly what you want to do in your second question). Your tool(s) might highlight messages sent to stderr making them easier to spot right away.

    You could use the command line version to redirect stderr, as thesamet suggests. To get a timestamp in the filename, you could do something like this when you run your program:

    ./program 2>"logfile-`date`.txt"
    

    If you want to do it in the program itself, one way is to simply use fopen to open another file and write to that. Here is a fully working example you can play with:

    #include <time.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <stdbool.h>
    
    #define DEBUG_TEST true
    
    FILE *debug_file;
    
    #define DEBUG_PRINT(fmt, ...) \
            do { if (DEBUG_TEST) fprintf(debug_file, fmt, ##__VA_ARGS__); } while (false);
    
    
    
    int main()
    {
            time_t timestamp = time(NULL);
            char * s = malloc(snprintf(NULL, 0, "debug-%d.txt", timestamp));
            sprintf(s, "debug-%d.txt", timestamp);
    
            debug_file=fopen(s, "w");
    
            DEBUG_PRINT("YEAH\n");
    
            fclose(debug_file);
    
            return EXIT_SUCCESS;
    }