The software usually outputs logs to facilitate troubleshooting and tracking of running conditions. The format of all log files should be improved to avoid time and effort when searching for key information.
Therefore, log functions must support:
1. Time and place. That is, when and where the information is reported.
2. To facilitate the call, multiple formats of output must be supported. Therefore, the printf format is the best.
Below is a log function I wrote:
# Include <stdarg. h> # include <stdio. h> # include <time. h> # define LOG_FILE ". /. log "# define log_default (FMT ,...) log_out (LOG_FILE, _ file __, _ line __, FMT, ##__va_args _) # define log_toxfile (flog, FMT ,...) log_out (flog, _ file __, _ line __, FMT, ##__va_args _) int log_out (char * flog, char * file, int line, char * FMT ,...) {va_list ARG; charpre [128], TMP [1024]; longclock; structtm * c_ptr; file * FP; time (& C Lock); c_ptr = localtime (& clock); sprintf (PRE, "[% 04d % 02d % 02d % 02d % 02d % 02d _ % S. % d] ", c_ptr-> maid + 1900, c_ptr-> tm_mon + 1, c_ptr-> tm_mday, c_ptr-> tm_hour, c_ptr-> tm_min, c_ptr-> tm_sec, file, line); va_start (ARG, FMT); vsprintf (TMP, FMT, ARG); va_end (ARG); // log to stdoutif (! Flog) {printf ("%-32.32 S % s", pre, TMP); Return 0 ;}// log to fileif (! (FP = fopen (flog, "at") Return-1; fprintf (FP, "%-32.32 S % s", pre, TMP); fclose (FP ); return 0 ;}
Call method:
Log_default outputs logs to the default Log File
Log_toxfile outputs a specified log file. If the parameter is 0, the log is printed to the standard output.