So I'm really new to Logback and have a question about how I should go about implement开发者_如何学Cing something.
Say I have two appenders: and I want appender "a" to accept markers that are only 1 or 2, but I want appender "b" to accept markers that are only 1 or 3. What type of filter should I use? Is there anything for this?
One option is to use the Event Evaluator. You can also write your own Filter; in fact the built-in example does (almost) what you want.
The filter below should be close to what you are looking for.
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import java.util.ArrayList;
import java.util.List;
public class OneTwoMarkerFilter extends Filter
{
private final List<Marker> markers = new ArrayList<Marker>();
public MarkerFilter()
{
markers.add(MarkerFactory.getMarker("1"));
markers.add(MarkerFactory.getMarker("2"));
}
@Override
public FilterReply decide(Object event)
{
if (!isStarted())
{
return FilterReply.NEUTRAL;
}
LoggingEvent logEvent = (LoggingEvent) event;
Marker eventMarker = logEvent.getMarker();
if (eventMarker != null && markers.contains(eventMarker))
{
return FilterReply.NEUTRAL;
}
else
{
return FilterReply.DENY;
}
}
}
Please note I have not tested this.
Uriah's answer is great!
And I think to extend AbstractMatcherFilter may be a better beginning.
public class MarkerFilter extends AbstractMatcherFilter<ILoggingEvent> {
private Marker markerToMatch = null;
@Override
public void start() {
if (null != this.markerToMatch)
super.start();
else
addError("!!! no marker yet !!!");
}
@Override
public FilterReply decide(ILoggingEvent event) {
Marker marker = event.getMarker();
if (!isStarted())
return FilterReply.NEUTRAL;
if (null == marker)
return onMismatch;
if (markerToMatch.contains(marker))
return onMatch;
return onMismatch;
}
public void setMarker(String markerStr) {
if(null != markerStr)
markerToMatch = MarkerFactory.getMarker(markerStr);
}
}
<filter class="your.pkg.MarkerFilter">
<marker>YOUR_MARKER</marker>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
You should override decide in AbstractMatcherFilter, just replace markerToMatch.contains(marker) with your logic, and decide which marker is matched(i.e., accepted).
usage:
log.info(MarkerFacotry.getMarker("YOUR_MARKER"), "---msg---");
精彩评论