The web application on which I am working occasionally develops data integrity issues for some of the users. I\'d like to turn on trace level logging, but since we are deali
Matthew Farwell's answer (use MDC) is the one that worked for me and he mentions writing your own filter. My need was to hide logging messages in certain cases. Specifically, we have a health check call that is hit much more frequently than typical user usage and it was filling the logs unnecessarily. Matthew's solution doesn't fit my situation because it requires you to add the MDC to the actual log output. I only want to use the MDC for filtering, so I extended org.apache.log4j.spi.Filter with the following class:
/**
* Log4J filter that stops certain log messages from being logged, based on a
* value in the MDC (See Log4J docs).
*/
public class Log4JMDCFilter extends Filter
{
private String keyToMatch;
private String valueToMatch;
private boolean denyOnMatch = true;
/**
* {@inheritDoc}
*/
public int decide(LoggingEvent event)
{
if (keyToMatch != null && valueToMatch != null
&& valueToMatch.equals(event.getMDC(keyToMatch)))
{
return denyOnMatch ? DENY : ACCEPT;
}
return denyOnMatch ? ACCEPT : DENY;
}
/**
* The key on which to filter.
*
* @return key on which to filter
*/
public String getKeyToMatch()
{
return keyToMatch;
}
/**
* Sets the key on which to filter.
*
* @param keyToMatch key on which to filter
*/
public void setKeyToMatch(String keyToMatch)
{
this.keyToMatch = keyToMatch;
}
/**
* Gets the value to match.
*
* @return the value to match.
*/
public String getValueToMatch()
{
return valueToMatch;
}
/**
* Sets the value to match.
*
* @param valueToMatch the value to match.
*/
public void setValueToMatch(String valueToMatch)
{
this.valueToMatch = valueToMatch;
}
/**
* Returns true if the log message should not be logged if a match is found.
*
* @return true if the log message should not be logged if a match is found.
*/
public boolean isDenyOnMatch()
{
return denyOnMatch;
}
/**
* Set this to "true" if you do not want log messages that match the given
* key/value to be logged. False if you only want messages that match to be
* logged.
*
* @param denyOnMatch "true" if you do not want log messages that match the
* given key/value to be logged. False if you only want messages that
* match to be logged.
*/
public void setDenyOnMatch(String denyOnMatch)
{
this.denyOnMatch = Boolean.valueOf(denyOnMatch).booleanValue();
}
}
Use the following log4j.xml snippet to activate the filter ("HEALTHCHECK" is the key and "true" is the value I'm filtering on):
Then, anywhere you want to mark for filtering, put in code like this:
MDC.put("HEALTHCHECK", "true");
try
{
// do healthcheck stuff that generates unnecessary logs
}
finally
{
MDC.remove("HEALTHCHECK"); // not sure this is strictly necessary
}