Unify the log format and use macros to call printf

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.