Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1529188
  • 博文数量: 290
  • 博客积分: 3468
  • 博客等级: 中校
  • 技术积分: 3461
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-28 22:21
文章分类

全部博文(290)

文章存档

2016年(13)

2015年(3)

2014年(42)

2013年(67)

2012年(90)

2011年(75)

分类: C/C++

2014-12-21 16:12:49


点击(此处)折叠或打开

  1. #include <iostream>
  2. #include <cstdarg>
  3. #include <cstdio>

  4. using namespace std;


  5. int ImplLogPrint(int iLogLevel, const char *format, va_list argList);

  6. #define ERROR 0
  7. #define WARNING 1
  8. #define INFO 2
  9. #define DEBUG 3

  10. #define _IMPL_LOGPRINT(LogLevel) \
  11.         void LogPrint##LogLevel(const char *format, ...) \
  12.         { \
  13.             va_list argList; \
  14.             va_start(argList, format); \
  15.             ImplLogPrint(LogLevel, format, argList); \
  16.             va_end(argList);\
  17.         }

  18. #define IMPL_LOGPRINT(x) _IMPL_LOGPRINT(x) //跳板宏,用于展开ERROR 等宏

  19. IMPL_LOGPRINT(ERROR) //展开之后为LogPrint0
  20. IMPL_LOGPRINT(WARNING)
  21. IMPL_LOGPRINT(INFO)
  22. IMPL_LOGPRINT(DEBUG)

  23. #define Logging(LogLevel) (LogLevel <= GetLogLevel())

  24. #define _LogEvent(LogLevel, x) \
  25. do { \
  26.     if (Logging(LogLevel)) \
  27.     { \
  28.         LogPrint##LogLevel x ; \
  29.     } \
  30. } while(0)

  31. #define LogEvent(LogLevel, x) _LogEvent(LogLevel, x) //跳板宏,用于展开ERROR 等宏

  32. #define LogError(x) LogEvent(ERROR, x)
  33. #define LogWarning(x) LogEvent(WARNING, x)
  34. #define LogInfo(x) LogEvent(INFO, x)
  35. #define LogDebug(x) LogEvent(DEBUG, x)

  36. int g_LogLevel = 0;

  37. int GetLogLevel()
  38. {
  39.     return g_LogLevel;
  40. }

  41. int SetLogLevel(int iLevel)
  42. {
  43.     g_LogLevel = iLevel;

  44.     return 0;
  45. }

  46. int ImplLogPrint(int iLogLevel, const char *format, va_list argList)
  47. {
  48.     char buf[1024];

  49.     int ret = vsprintf(buf, format, argList);

  50.     switch(iLogLevel)
  51.     {
  52.     case ERROR:
  53.         cout << "Error:"<< buf << endl;
  54.         break;
  55.     case WARNING:
  56.         cout << "Warning:"<< buf << endl;
  57.         break;
  58.     case INFO:
  59.         cout << "Info:"<< buf << endl;
  60.         break;
  61.     case DEBUG:
  62.         cout << "Debug:"<< buf << endl;
  63.         break;
  64.     default:
  65.         break;
  66.     }

  67.     return ret;
  68. }

  69. int main()
  70. {
  71.     SetLogLevel(3);
  72.     LogError(("hello %s", "world"));
  73.     LogWarning(("hello %s", "world"));
  74.     LogInfo(("hello %s", "world"));
  75.     LogDebug(("hello %s", "world"));

  76.     SetLogLevel(1);
  77.     LogError(("hello %s", "world"));
  78.     LogWarning(("hello %s", "world"));
  79.     LogInfo(("hello %s", "world"));
  80.     LogDebug(("hello %s", "world"));

  81.     return 0;
  82. }
预编译展开后的代码 
# g++ -E debug_level.cpp  -o debug_level.i




阅读(1226) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~