Chinaunix首页 | 论坛 | 博客
  • 博客访问: 219473
  • 博文数量: 28
  • 博客积分: 398
  • 博客等级: 一等列兵
  • 技术积分: 1109
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-07 22:28
文章分类
文章存档

2017年(1)

2014年(3)

2013年(7)

2012年(4)

2011年(13)

分类: LINUX

2011-04-25 17:53:31

下面是一个头文件,在写代码时,#include "debug_log.h",
然后使用 DEBUG_PRINT( "debug information: %s", "hello world" );
输出:[file: ps_push.c, func: main, line: 151 ] debug information: hello world
调试信息中包含了,代码文件名,函数名,行号,调试信息,有了这些信息可以很快定位到
代码的位置,方便检查错误。
适合调试不方便的工程,当不需要调试信息时,
只要注释掉 /* #define DEBUG_LOG_ENABLE */
就不会对生产代码有任何影响。
  1. // file debug_log.h
  2. #ifndef __DEBUG_LOG_H
  3. #define __DEBUG_LOG_H

  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include <stdarg.h>

  8. #define DEBUG_LOG_ENABLE

  9. #ifdef DEBUG_LOG_ENABLE
  10. # define DEBUG_PRINT(format,args...) \
  11.     log_message(__FILE__, __LINE__, __FUNCTION__, format, ##args);
  12. #else
  13. # define DEBUG_PRINT(format,args...)
  14. #endif

  15. static void log_message(char* file, int line, const char* func,
  16.         const char* format,...)
  17. {
  18.     if ( format == NULL )
  19.         return;

  20.     int size = strlen(format) + 1024;
  21.     char *new_format = (char *) malloc( sizeof(char) * size );
  22.     if ( new_format == NULL )
  23.         return;

  24.     memset( new_format, 0x00, size);
  25.     snprintf( new_format, size, "[file: %s, func: %s, line: %d ] %s ",
  26.             file, func, line, format );

  27.     va_list va;
  28.     va_start(va, format);
  29.     vfprintf( stderr, new_format, va );
  30.     va_end( va );

  31.     free( new_format );
  32. }

  33. #endif // __DEBUG_LOG_H
阅读(1938) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~