log4cxx add filter to specific logger programmatically

126 Views Asked by At

In Log4cxx I know that its possible to add filter to appender. But what if I want to add filter only to specific logger?

LoggerPtr logger = Logger::getLogger("loggerName");
AppenderPtr appender = logger->getAppender("appenderName");
appender->addFilter(...);

From looking at the documentation I can't find a way to add a filter to specific logger, the only way I can think of is that for every specific logger I wish to apply a filter I will create a specific appender and for this appender apply the filter. Are there any other ways?

I'm looking for a way to do it programmatically, if possible.

1

There are 1 best solutions below

0
Stephen Webb On BEST ANSWER

You can use the log4cxx included LoggerMatchFilter if you want ot exclude/include a particular logger name.

Alternatively, by providing your own custom filter (which implements decide(const LoggingEventPtr &event) you can access to logger name from the LoggingEvent. For example:

auto MyCustomFilter::decide(const log4cxx::spi::LoggingEventPtr& event) const
{
    auto result = log4cxx::spi::Filter::NEUTRAL;
    if (m_loggerToMatch == event->getLoggerName()) {
       if (.....)
        result = log4cxx::spi::Filter::ACCEPT;
       else
        result = log4cxx::spi::Filter::DENY;
    }
    return result;
}