如何使用 Log4J SMTPAppender 动态更改电子邮件主题?

发布于 2024-11-28 16:08:36 字数 1125 浏览 0 评论 0原文

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

我正在使用上面提到的 log4j 属性文件来发送 当我这样做时,

log.error("Error message");

我如何才能使其动态化,以便 消息主题可以根据机器名称(环境名称)动态更改。

例如:

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

我想根据机器名称动态使用主题 1,2 和 3。

任何帮助将不胜感激。 谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

冰葑 2024-12-05 16:08:36

您应该只需要使用主机名变量,例如:

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

根据您的特定配置和操作系统,您可能需要使用 -Dhostname='machinename' 或 -Dhostname=$HOST 在 statrup 处将此变量提供给您的 JVM

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

心意如水 2024-12-05 16:08:36

在下面的代码中,我读出了 log4j.properties 文件,将属性 log4j.appender.ERROREMAIL.Subject 设置为 emailRecipients 并重置log4j 配置。可以在应用程序启动时完成,您只需正确设置 emailRecepients 字符串即可。

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

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);
青萝楚歌 2024-12-05 16:08:36

设置用户名或 ENV 变量

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

To set a username or over ENV variable

log4j.appender.smtp.Subject=SYNC PROJECTS (${user.name}) Error Log ...
街角卖回忆 2024-12-05 16:08:36
///////////////////////////////////////////////////////////////////////////
// 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");

    }
}
///////////////////////////////////////////////////////////////////////////
// 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");

    }
}
記柔刀 2024-12-05 16:08:36

我可以想到 2 个解决方案:

  1. 编写自己的记录器,它将使用 SMTPAppender 并以编程方式设置属性。

  2. 使用 MDC 放置代码中的动态值。您可以使用 %X 从 log4j.xml 中的 MDC 获取值。

前任:

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

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}
会傲 2024-12-05 16:08:36

如果我们正在读取属性并添加主题抛出java代码,我们将遇到并发请求问题。

如果第一个用户在发送邮件之前修改了主题并进行了一些其他操作。同时第二个用户添加了不同的主题。第一个用户也获得第二个用户的主题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文