1、通过两个 printf 函数
#define PRINT_INFO (printf("[%s][%d]Info: ", __FILE__, __LINE__), printf)
#define PRINT_WARRING (printf("[%s][%d]Warring: ", __FILE__, __LINE__), printf)
#define PRINT_ERROR (printf("[%s][%d]Error: ", __FILE__, __LINE__), printf)
#define PRINT_DEBUG (printf("[%s][%d]Debug: ", __FILE__, __LINE__), printf)
2、打印并输出到 linux 的 syslog
/*
* Function: LogMessage(const char *, ...)
*
* Purpose: Print a message to stdout or with logfacility.
*
* Arguments: format => the formatted error string to print out
* ... => format commands/fillers
*
* Returns: void function
*/
void LogMessage(const char *format,...)
{
char buf[STD_BUF+1];
va_list ap;
va_start(ap, format);
if(pv.daemon_flag)
{
vsnprintf(buf, STD_BUF, format, ap);
syslog(LOG_DAEMON | LOG_NOTICE, "%s", buf);
}
else
{
vfprintf(stderr, format, ap);
}
va_end(ap);
return;
}
3、通过可变参数实现
enum _PRINT_LEVEL_ {
INFO,
DEBUG,
WARRING,
ERROR
};
#define MY_PRINT(format, level, ...)\
do { \
time_t t = time(NULL);\
char *pTimeStr = ctime(&t);\
const char *pLevelStr[] = { \
"INFO", \
"DEBUG", \
"WARRING", \
"ERROR" \
}; \
printf("[%s][%s][%s][%d]%s: "format"", pTimeStr, __FILE__, __FUNCTION__, __LINE__, pLevelStr[level], ##__VA_ARGS__);\
} while(0);
#define PRINT_INFO(format, ...) MY_PRINT(format, INFO, ##__VA_ARGS__)
#define PRINT_DEBUG(format, ...) MY_PRINT(format, DEBUG, ##__VA_ARGS__)
#define PRINT_WARRING(format, ...) MY_PRINT(format, WARRING, ##__VA_ARGS__)
#define PRINT_ERROR(format, ...) MY_PRINT(format, ERROR, ##__VA_ARGS__)