"); //-->
C实现日志等级控制
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <time.h> #define SJXC_LOG_DEBUG(level, format, arg...) SJXC_log_msg_print(level, __FILE__, __func__, __LINE__, format, ##arg) #ifdef SJXC_DISABLE_DEBUG #define SJXC_REAL_DEBUG_LEVEL 0 #else #define SJXC_REAL_DEBUG_LEVEL SJXC_DEBUG_LEVEL #endif #define SJXC_ERROR (1 << 0) #define SJXC_WARN (1 << 1) #define SJXC_INFO (1 << 2) #define SJXC_DEBUG (1 << 3) int SJXC_DEBUG_LEVEL = 1; struct SJXC_gdb { int level; const char *msg; }; struct SJXC_gdb SJXC_gdb_table[] = { {SJXC_ERROR, "Config the log level as error."}, {SJXC_WARN, "Config the log level as warn."}, {SJXC_INFO, "Config the log level as info."}, {SJXC_DEBUG, "Config the log level as DEBUG."} }; void SJXC_print_debuf_usage(void) { struct SJXC_gdb *p_gdb; fprintf(stderr, " To calculate the debug level, logically 'or'\n" " some of the following values together to get a bebug level:\n"); for (p_gdb = SJXC_gdb_table; p_gdb < SJXC_gdb_table + (sizeof(SJXC_gdb_table) / sizeof(struct SJXC_gdb)); p_gdb++) { fprintf(stderr, "\t%d:\t%s\n", p_gdb->level, p_gdb->msg); } fprintf(stderr, "\n"); } void SJXC_log_msg_print(int level, const char *file, const char *func, const int line, char *fmt, ...) { char *status; switch (level) { case SJXC_ERROR: status = "ERROR"; break; case SJXC_WARN: status = "WRAN"; break; case SJXC_INFO: status = "INFO"; break; case SJXC_DEBUG: status = "DEBUG"; break; default: printf("Debug message level ERROR!\n"); } if (SJXC_REAL_DEBUG_LEVEL & level) { char msg_buf[20*1024]; char *ascii_time_buf; time_t tnow = time(NULL); va_list ap; ascii_time_buf = asctime(localtime(&tnow)); ascii_time_buf[strlen(ascii_time_buf) - 1] = '\0'; va_start(ap, fmt); sprintf(msg_buf, " ------> [ %s %s:%s:%d ] %s ", ascii_time_buf, file, func, line, status); vsprintf(msg_buf + strlen(msg_buf), fmt, ap); fprintf(stderr, "%s\n", msg_buf); va_end(ap); } } #if 1 int main(void) { int i = 0; printf("%d\n", SJXC_REAL_DEBUG_LEVEL); SJXC_print_debuf_usage(); while( i != 32) { SJXC_log_msg_print(SJXC_ERROR, __FILE__, __func__, __LINE__, "1234567890"); i++; } return 0; } #endif
*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。