Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Monday 14 January 2019

Log4j SMTP Appender Using System Environment Variables

Hey friends!

Earlier last week, I was stuck for a short while in a what should've been an easy task, but took my more than expected working hours to completely solve that: SMTP appender for Log4j.

So as we all know, SMTP or Simple Mail Transfer Protocol is used to send emails from your java program, generally when a particular level of exception occurs in your code. Log4j is a well known Java logging utility, but this particular appender wasn't discussed as about much as I expected earlier. 


Earlier I was using log4j2.yml file for logging but due to some versioning reasons, it wasn't picking up the Log4j keywords properly from the version of Log4j that I added. So eventually I had to shift to using the XML version.

So the version that I am using is:


Here's my version of log4j.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
        <Console name="Console1" target="SYSTEM_OUT">
                pattern="%highlight{%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n}{FATAL=red, ERROR=red, WARN=cyan, INFO=white, DEBUG=yellow, TRACE=green}"/>

            <HtmlLayout charset="UTF-8" locationInfo="true" />
            <ThresholdFilter level="ERROR"/>
        <Root level="INFO">
            <AppenderRef ref="Console1"/>
            <AppenderRef ref="Mail1"/>

One different feature that you would observe about the code is that I am not hard-coding the login info and other params in my code. Instead I am picking them up from the environment variables. Your dev-ops team would have no complaints now :)

I hope you were able to use this code directly without any further hiccups. Needless to say you can always ping me via the comments below if you face any trouble in using this SMTP appender in log4j. Adios till my next post!

Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: