Log4j.xml injecting Evaluator

可紊 提交于 2020-01-06 21:21:48

问题


My project is using log4j 1.2.17. I have successfully injected my custom "Evaluator" into the SMTPAppender, using setEvaluatorClass :

<appender name="email" class="org.apache.log4j.net.SMTPAppender">
  <param name="EvaluatorClass" value="path.to.my.Evaluator" />

However, I would like to pass some params to my Evaluator, to make it configurable. I would like to use SMTPAppender.setEvaluator, but I cannot figure out how to set that up in log4j.xml. Another option would be the other SMTPAppender constructor, which I have also been unsuccessful in using via log4j.xml

Cheers


回答1:


Quoting the API doc of SMTPAppender:

The triggering criteria can be modified by setting the evaluatorClass property with the name of a class implementing TriggeringEventEvaluator, setting the evaluator property with an instance of TriggeringEventEvaluator or nesting a triggeringPolicy element where the specified class implements TriggeringEventEvaluator.

Basically, I can use a nested triggeringPolicy element to emulate the behavior of an evaluator. The added advantage is that, I can pass arguments to the triggeringPolicy element.

I had a use case of sending email digest for every n - messages. For that I used the following TriggeringPolicy:

package org.email;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.TriggeringEventEvaluator;


public class MyEvaluator implements TriggeringEventEvaluator {

    private volatile int num = 1;

    private int quotient = 1;

    @Override
    public boolean isTriggeringEvent(LoggingEvent event) {
        return num++ % quotient == 0;
    }

    public void setQuotient(int quotient) {
        this.quotient = quotient;
    }
}

My log4j.xml configuration, which sends one mail for every two log events is given below:

<appender name="ErrorEmailAppender"     class="org.apache.log4j.net.SMTPAppender">
    <param name="SMTPHost" value="myHost" />
    <param name="From" value="xxxxx@yyy.com" />
    <param name="To" value="xxxxx@yyy.com" />
    <param name="Subject" value="Log of messages" />
    <triggeringPolicy class="org.email.MyEvaluator">
        <param name="quotient" value="2" />
   </triggeringPolicy>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%t %m%n"/>
    </layout>
</appender>

Hope this helps!



来源:https://stackoverflow.com/questions/34931650/log4j-xml-injecting-evaluator

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