Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically change the email subject using Log4J SMTPAppender?

Tags:

java

log4j

log4j.appender.ERROREMAIL=org.apache.log4j.net.SMTPAppender
log4j.appender.ERROREMAIL.SMTPHost=www.company.com
log4j.appender.ERROREMAIL.Threshold=ERROR
[email protected],[email protected],[email protected]
log4j.appender.ERROREMAIL.From=some.emailaddress.com
log4j.appender.ERROREMAIL.Subject=messagesubject1

I am using the above mentioned log4j property file to send email when I do

log.error("Error message");

How do I be able to make it dynamic so that the message subject can change dynamically depending upon the machine name(env name).

eg:

log4j.appender.ERROREMAIL.Subject=messagesubject1, messagesubject2, messagesubject3

I want to use subjects 1,2 and 3 dynamically depending upon machine name.

Any help will be appreciated. Thanks

like image 961
user234194 Avatar asked Aug 10 '11 17:08

user234194


4 Answers

///////////////////////////////////////////////////////////////////////////
// Initial Logging configuration
///////////////////////////////////////////////////////////////////////////

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>


    <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n"/>
      </layout>
   </appender>


    <!-- BufferSize almacena un buffer de mensajes. Un evento de tipo error o 
    superior provoca el envio del correo junto con el resto de mensajes en el buffer (si los hay) -->
    <appender name="emailAppender"  class="org.apache.log4j.net.SMTPAppender">  

        <param name="BufferSize"    value="40"/> 
        <param name="SMTPHost"      value="conectores.mydomain.es" />  
        <param name="SMTPUsername"  value="weblogic" />           
        <param name="From"          value="[email protected]" />  
        <param name="To"            value="[email protected]" />  
        <param name="Subject"       value="Notificación de la aplicación" />  

        <layout class="org.apache.log4j.PatternLayout">  
            <param name="ConversionPattern" value="%n%d{yyyy-MM-dd HH:mm:ss} [%-5p] [%l] %n%m%n" />  
        </layout>  
    </appender>  

    <!-- Las trazas de nivel trace o superior las mete en el buffer, el resto las desecha -->
    <logger name="smtp.logger">  
        <level value="debug"/>
        <appender-ref ref="emailAppender" />  
    </logger>   

    <root>
        <priority value="debug"/>
        <appender-ref ref="consoleAppender"/>
    </root>

</log4j:configuration>

///////////////////////////////////////////////////////////////////////////
// Dynamic configuration of SMTAppender attributes
///////////////////////////////////////////////////////////////////////////

package es.foo.test;

import java.util.Enumeration;

import java.util.Properties;

import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.net.SMTPAppender;

public class TestSMTPAppender {

    private static Logger smtp = Logger.getLogger("smtp.logger");
    private static boolean ini_flag = false;    
    private static final Properties propiedades = new Properties(); 
    static {
        try {           
            propiedades.load(TestSMTPAppender.class.getClassLoader().getResourceAsStream("mydomainUtiles.properties"));
        } catch (Exception ioe) {
            System.err.println("error while creating properties from 'mydomainUtiles.properties': " + ioe.getMessage());    
        }
    }   

    private static void initializeLogger(){ 

        String SMTPHost = propiedades.getProperty("host");
        String SMTPUsername = propiedades.getProperty("user");
        String From = propiedades.getProperty("sender");

        Enumeration eappenders = smtp.getAllAppenders();
        while(eappenders.hasMoreElements()){
            Appender appender = (Appender) eappenders.nextElement();
            if(appender instanceof SMTPAppender){

                if(SMTPHost != null){
                    ((SMTPAppender)appender).setSMTPHost(SMTPHost);
                }

                if(SMTPUsername != null){
                    ((SMTPAppender)appender).setSMTPUsername(SMTPUsername);
                }

                if(From != null){
                    ((SMTPAppender)appender).setFrom(From);
                }

                // Place here other attributes, like Subject

                ((SMTPAppender)appender).activateOptions();
            }           
        }
    }

    public static Logger getSMTPLogger(){
        if(!ini_flag){
            initializeLogger();
            ini_flag = true;        
        }
        return TestSMTPAppender.smtp;
    }   

}

///////////////////////////////////////////////////////////////////////////
// TEST
///////////////////////////////////////////////////////////////////////////

package es.foo.test;

import java.util.Enumeration;

import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.net.SMTPAppender;

public class Test {

    private static Logger smtp = TestSMTPAppender.getSMTPLogger();

    public static void main(String[] args) {

        smtp.trace("message1");
        smtp.debug("message2");
        smtp.info("message3");
        smtp.warn("message4");
        smtp.error("message5");

    }
}
like image 168
Lael Fox Willis Avatar answered Sep 21 '22 05:09

Lael Fox Willis


You should just need to make use of the hostname variable something like:

log4j.appender.ERROREMAIL.Subject=${hostname} 

Depending on your paritcular configuration and OS you may need to supply this variable to your JVM at statrup using -Dhostname='machinename' or -Dhostname=$HOST

like image 24
Terrell Plotzki Avatar answered Oct 16 '22 06:10

Terrell Plotzki


In the following piece of code I read out the log4j.properties file, set the property log4j.appender.ERROREMAIL.Subject to emailRecipients and reset the log4j configuration. Could be done at the start of the application, you just need to set the emailRecepients string right.

    Properties props = new Properties();
    try {
         InputStream configStream = Thread.class.getResourceAsStream("/log4j.properties");
         if (configStream == null) {
             throw new RuntimeException();
         }
         props.load(configStream);
         configStream.close();
    } catch(Throwable e) {
        System.out.println("Error: Cannot load log4j configuration file ");
    }

    props.setProperty("log4j.appender.ERROREMAIL.Subject", emailRecipients);

    LogManager.resetConfiguration();
    PropertyConfigurator.configure(props);
like image 2
MarianP Avatar answered Oct 16 '22 06:10

MarianP


To set a username or over ENV variable

log4j.appender.smtp.Subject=SYNC PROJECTS (${user.name}) Error Log ...
like image 1
Nicolay Avatar answered Oct 16 '22 08:10

Nicolay