我正在使用 log4j 1.2.17 。
我需要以编程方式添加过滤器。我正在使用来自 log4j API 的 StringMatchFilter。但它们似乎不起作用。当我添加一个 log4j.properties 文件时,多个过滤器工作,我能够抑制日志。
以下是代码:
package logging;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.varia.StringMatchFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ProgrammaticallyAddingFilters {
public static void main(String[] args) {
/**
* Related to FileAppenders
*/
String APPN_LAYOUT_PATTERN = "%d{MM-dd@HH:mm:ss}%-4r %-5p [%t] %37c %3x - %m%n";
Level DEFUALT_DEBUG_THRESHOLD = Level.WARN;
Log LOG = LogFactory.getLog(ProgrammaticallyAddingFilters.class);
ConsoleAppender consoleAppn = new ConsoleAppender();
//configure the appender
consoleAppn.setLayout(new PatternLayout(APPN_LAYOUT_PATTERN));
consoleAppn.setThreshold(DEFUALT_DEBUG_THRESHOLD);
consoleAppn.activateOptions();
try {
List<StringMatchFilter> filterList = getStringMatchFilters();
for (StringMatchFilter stringMatchFilter : filterList) {
consoleAppn.addFilter(stringMatchFilter);
}
} catch (Exception e) {
LOG.warn("exception adding the supress log filters", e);
}
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(consoleAppn);
LOG.debug("Things will fall in line soon. there is way out of every problem");
LOG.debug("Keep Cool 123");
LOG.debug("Hey there , Hello World");
}
private static List<StringMatchFilter> getStringMatchFilters() {
List<StringMatchFilter> stringMatchFilterList = new ArrayList<>();
StringMatchFilter smf = new StringMatchFilter();
smf.setStringToMatch("Keep Cool 123");
smf.setAcceptOnMatch(false);
StringMatchFilter smf2 = new StringMatchFilter();
smf2.setStringToMatch("Things will fall in line soon");
smf2.setAcceptOnMatch(false);
stringMatchFilterList.add(smf2);
stringMatchFilterList.add(smf);
stringMatchFilterList.add(smf2);
return stringMatchFilterList;
}
}