本文介绍了如何使用Log4J SMTPAppender动态更改电子邮件主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正在使用上面提到的log4j属性文件来发送
电子邮件

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

log.error("Error message");

我如何使其动态化,以便
邮件主题可以动态更改取决于机器名称(env名称)。

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

例如:

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

我想使用主题1, 2和3动态取决于机器名称。

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

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

Any help will be appreciated.Thanks

推荐答案

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

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

这篇关于如何使用Log4J SMTPAppender动态更改电子邮件主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 12:44