简体   繁体   English

在log4j2 SMTPAppender中的运行时设置属性的主题值

[英]Setting to, from, subject values from properties at Runtime in log4j2 SMTPAppender

I'm using log4j 2.0-beta9. 我正在使用log4j 2.0-beta9。 I have a question about the SMTP appender. 我对SMTP附加程序有疑问。 I need to configure the subject, from and to values from properties. 我需要配置主题,以及属性的值。 I'm logging a MapMessage and my config is as below - 我正在记录MapMessage,其配置如下所示-

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="DEBUG">

    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d [%t] %-5p %c  - %m%n"/>
        </Console>

        <SMTP name="Mail" subject="Error Log for ${env:HOSTNAME}" to="${sys:mail.to}" from="${sys:mail.from}"
              smtpHost="${sys:mail.host}" smtpPort="${sys:mail.port}" smtpDebug="true" bufferSize="1">
            <PatternLayout>
                <pattern>%d [%t] %-5p %c - %m%n</pattern>
            </PatternLayout>
        </SMTP>

        <Async name="AsyncMail">
            <appender-ref ref="Mail" />
        </Async>
    </appenders>

    <loggers>
        <root level="info">
            <appender-ref ref="Console"/>
            <appender-ref ref="AsyncMail">
                <MapFilter onMatch="ACCEPT" onMismatch="DENY">
                    <KeyValuePair key="throwable.class" value="java.lang.RuntimeException" />
                </MapFilter>
            </appender-ref>
        </root>
    </loggers>
</configuration>


// Java Code to log the msg
Throwable throwable; // this is the exception that is thrown by the app.
MapMessage message = new MapMessage();
message.put("throwable.message", throwable.getMessage());
message.put("throwable.class", throwable.getClass().getName());
message.put("throwable.stacktrace", ExceptionUtils.getStackTrace(throwable)); // ExceptionUtils from apache-commons
LOGGER.error(message, throwable); // org.apache.logging.log4j.Logger

The problem is that none of these values are replaced dynamically. 问题是这些值都没有动态替换。 Is there any way to do this? 有什么办法吗?

Thanks in advance. 提前致谢。

You need to set the mail.to and mail.from System properties. 您需要设置mail.tomail.from系统属性。 The problem you're having might be that you're running in a Servlet 3.0 environment, in which case the Log4j2.xml file is being processed before your code that sets the properties is executed. 您遇到的问题可能是您正在Servlet 3.0环境中运行,在这种情况下,在执行设置属性的代码之前 ,正在处理Log4j2.xml文件。

If that is the case, you can create a servlet container initializer that you configure in your web.xml file to load before Log4j2's servlet container initializer is loaded. 在这种情况下,您可以创建一个在web.xml文件中配置的servlet容器初始化程序,以在Log4j2的servlet容器初始化程序被加载之前加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM