1

我正在尝试编写一个宏来简化 LOG4CPLUS 的使用。但是在编写宏时遇到了一些麻烦。

这是我的 cpp 文件中的内容:

Logger logger = Logger::getInstance("ManagerServer");

之后,我可以像这样记录一行:

LOG4CPLUS_ERROR(logger, logEvent);

我只想写一个宏,而不是我可以将 logEvent 更改为一些变量参数。并像这样使用:

LogErr("failed");
LogErr("failed times %d", iTimes);

所以,我这样写:

#define LogErr(fmt, args...)\
    do {\
        char szBuf[MAX_LOG_BUFFER_SIZE];\
        memset(szBuf, 0, MAX_LOG_BUFFER_SIZE);  \
        vsnprintf(szBuf, MAX_LOG_BUFFER_SIZE, fmt, ##args); \
        LOG4CPLUS_ERROR(logger, szBuf);\
    } while(0)

但是当我编译时。g++ 给我这个信息:

错误:“)”标记之前的预期主表达式

有没有人可以帮助我?对此,我真的非常感激。

4

4 回答 4

2

Oops ... C tag has been removed

The problem is with the expansion of the macro when not enough parameters are supplied (LogErr("failed")). That does not work in C.

Try adding a dummy parameter

LogErr("failed", 0);
/* or better */
LogErr("%s", "failed");

Also you cannot use v* functions inside a macro like you're trying to: the preprocessor does not know about variable arguments ad can't create objects of type va_list.


In C99, one way to do what it appears you're trying to do is

#include <stdio.h>
#include <string.h>

#define MAX_LOG_BUFFER_SIZE 100

#define LogErr(fmt, ...)                                      \
  do {                                                        \
    char szBuf[MAX_LOG_BUFFER_SIZE];                          \
    memset(szBuf, 0, MAX_LOG_BUFFER_SIZE);                    \
    snprintf(szBuf, MAX_LOG_BUFFER_SIZE, fmt, ##__VA_ARGS__); \
    /* LOG4CPLUS_ERROR(logger, szBuf); */                     \
  } while(0)

int main(void) {
  LogErr("err %d", 4);
  /*LogErr("failed");*/
  LogErr("%s", "failed");
  return 0;
}

Note: snprintf and ##__VA_ARGS

于 2011-06-25T13:48:23.417 回答
1

You're missing a comma after the args parameter.

#define LogErr(fmt, args, ...)\
                        ^

Also, I don't know if g++ currently supports variadic macros, it's a C++11 feature. (I believe the C compiler supports them, though).

于 2011-06-25T13:46:21.470 回答
1

感谢pmg、Ferruccio和你们所有人。你们真的救了我!

这些代码在我的电脑上运行良好。看来我确实错过了 vsnprintf 和 snprintf。

#define Log(fmt, args...) \
    do {\
        char szBuf[MAX_LOG_BUFFER_SIZE];\
        snprintf(szBuf, MAX_LOG_BUFFER_SIZE-1, fmt, ##args);\
        LOG4CPLUS_ERROR(logger, szBuf);\
    } while(0)

int main() {
    Log("Hello macro.");
    Log("Hello macro %d", 1);
    Log("Hello macro %s, %d", "foo", 2);

    return 0;
}

再次感谢!

于 2011-06-25T16:06:14.633 回答
0

Recent (1.1.0+) version of Log4cplus do support logging using printf-style macros. Your example in OP would look like this:

LOG4CPLUS_ERROR_FMT(logger, "failed");
LOG4CPLUS_ERROR_FMT(logger, "failed times %d", iTimes);

See loggingmacros.h for implementation details if you still want to reimplement it differently.

于 2012-09-20T13:24:18.217 回答