How do I add a custom filter in log4cplus?

我怕爱的太早我们不能终老 提交于 2019-12-19 04:20:23

问题


This is a followup to this question on conditional logging.

I found examples in the log4cplus test directory of how to configure filters in the properties file (so using the XML is unnecessary) I have created my own filter but I am having trouble using it. Here are the changes I made:

In spi/filter.h:

class LOG4CPLUS_EXPORT InstructionNumberFilter : public Filter {
    public:
      // ctors
        InstructionNumberFilter();
        InstructionNumberFilter(const log4cplus::helpers::Properties& p);

        /**
         * Returns {@link #NEUTRAL} is there is no string match.
         */
        virtual FilterResult decide(const InternalLoggingEvent& event) const;

    private:
      // Methods
        LOG4CPLUS_PRIVATE void init();

      // Data
        /** Do we return ACCEPT when a match occurs. Default is <code>true</code>. */
        uint instructionNumberToMatch;

};

In spi/filter.cxx:

InstructionNumberFilter::InstructionNumberFilter()
{
    init();
}

InstructionNumberFilter::InstructionNumberFilter(const helpers::Properties& properties)
{
    init();
    properties.getUInt(instructionNumberToMatch, LOG4CPLUS_TEXT("InstructionNumber"));    
}    

void
InstructionNumberFilter::init()
{
    instructionNumberToMatch = 0;
}    

FilterResult
InstructionNumberFilter::decide(const InternalLoggingEvent& event) const
{
    const uint currentInstructionNumber = 4; // TODO get number from MDC

    if( currentInstructionNumber == instructionNumberToMatch ){
        return ACCEPT;
    }

    return NEUTRAL;
}

In factory.cxx:

LOG4CPLUS_REG_FILTER (reg3, InstructionNumberFilter);

In the properties file:

# Set up logging to standard output stream.

log4cplus.appender.AP1=log4cplus::ConsoleAppender
log4cplus.appender.AP1.layout=log4cplus::PatternLayout
log4cplus.appender.AP1.layout.ConversionPattern=Rabble %-5p MDC(instructionNumber):%-10X{instructionNumber} [%d{%Q}](%l): %m

log4cplus.appender.AP1.filters.1=log4cplus::spi::InstructionNumberFilter
log4cplus.appender.AP1.filters.1.InstructionNumberToMatch=4
log4cplus.appender.AP1.filters.2=log4cplus::spi::DenyAllFilter

When I run I get the error:

log4cplus:ERROR Appender::ctor()- Cannot find FilterFactory: log4cplus::spi::InstructionNumberFilter

I tried to base all my changes on the implementation of the StringMatchFilter. Am I missing something else I need to do to get my filter to be recognized?

Thanks for your help.


回答1:


The error was a result of mislocating the libraries built from log4cplus.

So, the example above is the way to implement a custom filter in log4cplus. Unless anyone objects I will leave this here as there are very few examples of log4cplus filters on the web.



来源:https://stackoverflow.com/questions/22921728/how-do-i-add-a-custom-filter-in-log4cplus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!