在實際開發中我們經常要通過打印Log來調試程序,經常會用到打印函數,這裏我書寫了個宏,做到有選擇的打印log。發話不多說,直接貼代碼,希望對各位同仁有所啓發。
/*
File : log.c
Breif : Define a macro to optition print log
Date : 2016-12-16
Author: Andy
*/
#include <stdio.h>
/* Define Log print macro */
#define MyLog(DebugLevel, format, ...) \
do{ \
switch (DebugLevel) \
{ \
case 1: \
printf(format, ##__VA_ARGS__); \
break; \
case 2: \
printf("Function: "__FUNCTION__", Line: %d, ---> "format"", __LINE__, ##__VA_ARGS__); \
break; \
case 3: \
printf("File: "__FILE__", Function: "__FUNCTION__", Line: %d, ---> "format"", __LINE__, ##__VA_ARGS__); \
break; \
default: \
break; \
} \
}while(0)
int main(void)
{
MyLog(1, "Simple Log print!\r\n");
MyLog(2, "Satndard Log display!\r\n");
MyLog(3, "Detail Log view!\r\n");
MyLog(1, "If debug level is not equal 1,2 or 3 that log is invisible, such as next line :\r\n");
MyLog(6, "I am invisible log!\r\n");
MyLog(1, "Now, I think you have understood how to use MyLog macro.\r\n");
return 0;
}
運行的截圖如下: