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

…衆ロ難τιáo~ 提交于 2019-12-04 19:28:29

问题


log4j.appender.ERROREMAIL=org.apache.log4j.net.SMTPAppender
log4j.appender.ERROREMAIL.SMTPHost=www.company.com
log4j.appender.ERROREMAIL.Threshold=ERROR
log4j.appender.ERROREMAIL.To=email.address1@company.com,email.address2@company.com,email.address3@company.com
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


回答1:


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);



回答2:


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




回答3:


I can think of 2 solutions:

1) Write your own logger that will use SMTPAppender and set the properties programatically.

2) Use the MDC to put a dynamic value in your code. You can get values from the MDC in your log4j.xml with the %X.

ex: log4j.appender.ERROREMAIL.Subject=%X{key}




回答4:


To set a username or over ENV variable

log4j.appender.smtp.Subject=SYNC PROJECTS (${user.name}) Error Log ...



回答5:


///////////////////////////////////////////////////////////////////////////
// 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="no.reply@mydomain.es" />  
        <param name="To"            value="foo.bar@externos-mydomain.es" />  
        <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");

    }
}



回答6:


if we are reading the properties and adding the subject throw java code we will get concurrent request problem.

if first user modified the subject and doing some other operations before sending the mail. at the same time second user added different subject. first user is also get the second user's subject.



来源:https://stackoverflow.com/questions/7014792/how-can-i-dynamically-change-the-email-subject-using-log4j-smtpappender

标签

工具导航Map