Setting to, from, subject values from properties at Runtime in log4j2 SMTPAppender

1.2k views Asked by At

I'm using log4j 2.0-beta9. I have a question about the SMTP appender. I need to configure the subject, from and to values from properties. I'm logging a MapMessage and my config is as below -

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="DEBUG">

    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d [%t] %-5p %c  - %m%n"/>
        </Console>

        <SMTP name="Mail" subject="Error Log for ${env:HOSTNAME}" to="${sys:mail.to}" from="${sys:mail.from}"
              smtpHost="${sys:mail.host}" smtpPort="${sys:mail.port}" smtpDebug="true" bufferSize="1">
            <PatternLayout>
                <pattern>%d [%t] %-5p %c - %m%n</pattern>
            </PatternLayout>
        </SMTP>

        <Async name="AsyncMail">
            <appender-ref ref="Mail" />
        </Async>
    </appenders>

    <loggers>
        <root level="info">
            <appender-ref ref="Console"/>
            <appender-ref ref="AsyncMail">
                <MapFilter onMatch="ACCEPT" onMismatch="DENY">
                    <KeyValuePair key="throwable.class" value="java.lang.RuntimeException" />
                </MapFilter>
            </appender-ref>
        </root>
    </loggers>
</configuration>


// Java Code to log the msg
Throwable throwable; // this is the exception that is thrown by the app.
MapMessage message = new MapMessage();
message.put("throwable.message", throwable.getMessage());
message.put("throwable.class", throwable.getClass().getName());
message.put("throwable.stacktrace", ExceptionUtils.getStackTrace(throwable)); // ExceptionUtils from apache-commons
LOGGER.error(message, throwable); // org.apache.logging.log4j.Logger

The problem is that none of these values are replaced dynamically. Is there any way to do this?

Thanks in advance.

1

There are 1 answers

0
mbmast On

You need to set the mail.to and mail.from System properties. The problem you're having might be that you're running in a Servlet 3.0 environment, in which case the Log4j2.xml file is being processed before your code that sets the properties is executed.

If that is the case, you can create a servlet container initializer that you configure in your web.xml file to load before Log4j2's servlet container initializer is loaded.