Log4cplus: How can I integrate string into patternLayout?

989 views Asked by At

I want to configure Log4cplus appender, using configuration file, to log messages that include parameters from my application (For example: logging the name of the current function that call the log4cplus logger).

I know that Log4cplus has the patternLayout property that uses conversion patterns to log messages. But I can not see a way to integrate my own string inside the conversion pattern (there is nothing like %s in C that can take any generic string). so, what I would like to know is:

Is there actually a away to integrate a generic string (not literal text) into a Log4Cplus patternLayout?

1

There are 1 answers

0
Vardit On

You could configure patternLayout directly from code:

#include <log4cplus/consoleappender.h>

SharedObjectPtr<Appender> _append(new  ConsoleAppender());
_append->setName("Test");

std::string tmp = "literal text:";

std::string  pattern =  tmp + "%d{%m/%d/%y  %H:%M:%S}  - %m [%l]%n";
std::auto_ptr<Layout>  _layout(new  PatternLayout(pattern));

_append->setLayout(_layout);
_logger =  Logger::getInstance("test_logger.subtest");
_logger.addAppender(_append);

LOG4CPLUS_DEBUG(_logger,  "log example");

This will give you some freedom in defining generic string in the pattern layout.

Specifically for function name, according to log4cplus API documentation, you could also use %M:

Used to output function name using __FUNCTION__ or similar macro.
NOTE The __FUNCTION__ macro is not standard 
but it is common extension provided by all compilers (as of 2010). 
In case it is missing or in case this feature 
is disabled using the LOG4CPLUS_DISABLE_FUNCTION_MACRO macro, M expands to an empty string.