Print logs (C language) in different levels according to requirements.
When a program encounters a problem in debugging, it sometimes needs to print some intermediate variables. After the debugging is complete, you need to comment out the printing, which is very troublesome. So I wrote a small program that can set the log printing level.
Set the Log Level debug to be printed in the main program, and all the logs of the corresponding level are displayed for observation.
The program uses va_list (in the C language to solve the problem of variable parameters of a set of macros), the relevant knowledge can refer to the http://www.cnblogs.com/hanyonglu/archive/2011/05/07/2039916.html (pay attention to the link to the correct article in the comments ).
Directly run the main program: main. cpp
1 # include "log. h "2 # include <stdio. h> 3 int debug = 2; // 10 indicates that 1-9 logs are fully played, and only corresponding levels of log 4 int main () 5 {6 SetDebugLevel (); 7 char s [] = "abc"; 8 int k = 7; 9 double kk = 11.5; 10 WriteLog (1, "1-log is: % s \ n ", "abc"); 11 WriteLog (2, "2-log is: % s, k: % d \ n", s, k); // WriteLog (log level, formatted string, variable of an indefinite number) 12 WriteLog (3, "3-log is: % s, k: % d \ n", s, k); 13 WriteLog (4, "4-log is: % s, k: % d \ n", s, k); 14 WriteLog (5, "5-log is: % s, k: % d \ N ", s, k); // If debug is 5, only this one is printed. 15 WriteLog (6, "6-log is: % s, k: % d, kk = % lf \ n", s, k, kk ); 16 printf ("\ n"); 17 return 0; 18}
If the log print level is debug 2, only 11th lines are printed.
If the log print level is debug 6, Only 15th lines are printed.
If debug is 10, all logs are printed.
If the log printing level is 0 (not 1-10), no printing is performed (printing by calling WriteLog ).
The called program directly posts code:
Log. h
1 void WriteLog(int , char * ,... );2 void SetDebugLevel();
Specific implementation code:
Log. cpp
1 # include <stdio. h> 2 # include <stdarg. h> 3 4 extern int debug; 5 int debug_flag = 0; 6 void WriteLog (int I, va_list va_alist ,...) 7 {8 va_list args; 9 int level = I; 10 va_start (args, va_alist); 11 if (debug_flag & 1 <(level-1 )) // Note & <Priority 12 {13 vfprintf (stderr, va_alist, args); 14} 15 va_end (args); 16} 17 void SetDebugLevel () 18 {19 if (debug> = 1 & debug <= 9) 20 {21 debug_flag | = 1 <(debug-1 ); 22} 23 else if (debug = 10) 24 {25 debug_flag = 255; 26} 27}
So far, the first article has ended. Hope you can give me more meaningful advice.