import org.apache.log4j.spi.Filter; import org.apache.log4j.spi.LoggingEvent; /** This is a very simple filter based on filtering by MDC key and value. */ public class MDCFilter extends Filter { /** Do we return ACCEPT when a match occurs. Default is false, so that later filters get run by default */ boolean acceptOnMatch = false; String regexToMatch; String mdcKey; /** Return the decision of this filter. */ public int decide(LoggingEvent event) { String mdcValue = (String) event.getMDC(mdcKey); boolean matches = mdcValue.matches(regexToMatch); if ((matches && acceptOnMatch) || (!matches && !acceptOnMatch)) { return Filter.ACCEPT; } else { return Filter.DENY; } } public String getRegexToMatch() { return regexToMatch; } public void setRegexToMatch(String regexToMatch) { this.regexToMatch = regexToMatch; } public String getMDCKey() { return mdcKey; } public void setMDCKey(String mdcKey) { this.mdcKey = mdcKey; } /** Get the value of the AcceptOnMatch option. */ public boolean getAcceptOnMatch() { return acceptOnMatch; } /** Set the AcceptOnMatch option. */ public void setAcceptOnMatch(boolean acceptOnMatch) { this.acceptOnMatch = acceptOnMatch; } }