How to LOg efficiently in c

hercules

Disciple
Hi,
I have some c/c++ source codes available from open sources.
I need to put some logs in the files to debug.
Its in linux env.
Can anyone suggest me how to log ? printfs are not displayed properly on screen everytime.

Can i directly log into sytem log..may be in var/log , is that the right way ?

thanks......
 
You can use the following code to log messages to a file:

Code:
#define LOG_FILE    "my_log.log"

/* Function to log the messages */

void log_message(char *filename, char *message)

{

    FILE *logFile;

    logFile=fopen(filename,"a");

    if (!logFile) {

        return;

    }

    fprintf(logFile,"%s\n",message);

    fclose(logFile);

}

void signal_handler(int sig)

{

    switch (sig) {

        case SIGHUP:

            log_message(LOG_FILE,"hangup signal catched");

            break;

        case SIGTERM:

            log_message(LOG_FILE,"terminate signal catched");

            exit(0);

            break;

    }

}
 
Even I would suggest montylee's method of using fprintf() and printing to a file the way you want. You can use specify the complete path in fopen() if you want to create the file somewhere else apart from the default output directory.
 
hercules said:
Hi,

I have some c/c++ source codes available from open sources.

I need to put some logs in the files to debug.

Its in linux env.

Can anyone suggest me how to log ? printfs are not displayed properly on screen everytime.

Can i directly log into sytem log..may be in var/log , is that the right way ?

thanks......

if it's Unix/Linux just use 'echo'

like:

<some condition>

echo > checkpoint.log

<some condition>

echo >> checkpoint.log

if it makes sense to you
 
Back
Top