You may be done with this, but I just need to find a way to set the dynamic addresses to “and” this question will lead me to this path (thanks to the idea of @gresdiplitude about system properties and MDC values), so I'm sharing my solution.
I use SMTPAppenderto send small progress reports, but they need to be sent to different mailboxes. The solution seems to be futile, or at least I am very pleased with the result.
My logback.xml:
<conversionRule conversionWord="smtpTo" converterClass="com.example.logback.MyConverter" />
<appender name="SMTP" class="ch.qos.logback.classic.net.SMTPAppender">
<filter class="com.example.logback.MyFilter" />
<evaluator class="com.example.logback.MyEvaluator">
<limit>25</limit>
</evaluator>
<discriminator class="com.example.logback.MyDiscriminator" />
<cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTrackerImpl">
<bufferSize>25</bufferSize>
</cyclicBufferTracker>
<smtpHost>${smtp.host}</smtpHost>
<smtpPort>${smtp.port}</smtpPort>
<SSL>${smtp.ssl}</SSL>
<username>${smtp.username}</username>
<password>${smtp.password}</password>
<from>${smtp.from}</from>
<to>%smtpTo</to>
<subject>my subject</subject>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date: %message%n%xThrowable{full}</pattern>
</layout>
</appender>
MyFilter.java:
public FilterReply decide(ILoggingEvent event) {
return event.getMarker() != null
&& event.getMarker().contains("REPORT") ? FilterReply.ACCEPT
: FilterReply.DENY;
}
MyDiscriminator.java:
public String getDiscriminatingValue(ILoggingEvent e) {
Marker marker = e.getMarker();
if (marker == null || !(marker instanceof MyMarker)) {
return null;
}
return ((MyMarker) marker).getDiscriminatingValue();
}
MyConverter.java:
public class MyConverter extends ClassicConverter {
@Override
public String convert(ILoggingEvent event) {
Marker marker = event.getMarker();
if (marker == null || !(marker instanceof MyMarker)) {
return null;
}
return ((MyMarker) marker).getSmtpTo();
}
}
MyMarker.java:
public interface MyMarker extends Marker {
String getSmtpTo();
String getDiscriminatingValue();
}
I just created an implementation for MyMarkerand used several instances of this in every registration application that should be reported:
Marker marker1 = new MyMarkerImpl(
"REPORT",
"me@company.com, joe@company.com",
"alertGroup");
logger.warn(marker1, "SNAFU");
Marker marker2 = new MyMarkerImpl(
"REPORT", "boss@company.com, ceo@company.com", "phbGroup");
logger.info(marker2, "Everything is fine");
Marker marker3 = new MyMarkerImpl(
"REPORT", "me@company.com, joe@company.com", "bugFixingGroup");
logger.error(marker3, "Why things gone bad", exception);
Hope this can be helpful.