Logback-spring.xml配置中的参数property如何从数据库动态获取?

有个需求,利用Logback的SMTPAppender监控error级别日志,一旦有error级别日志就发出告警邮件,邮件接收者配置在mailTo的参数中,这个参数想实现利用数据库动态配置,以下是配置:

<configuration>

<define name="mailTo" class="com.xxx.xxx.common.config.MyPropertyDefiner"/>

<appender name="MAIL" class="ch.qos.logback.classic.net.SMTPAppender">

<smtpHost>${smtpHost}</smtpHost>

<smtpPort>465</smtpPort>

<username>${username}</username>

<password>${password}</password>

<SSL>true</SSL>

<asynchronousSending>true</asynchronousSending>

<from>${username}</from>

<to>${mailTo}</to>

<subject>${mailSubject}: %logger{0}</subject>

<charsetEncoding>UTF-8</charsetEncoding>

<cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker">

<bufferSize>1</bufferSize>

</cyclicBufferTracker>

<!--HTML展示-->

<layout class="ch.qos.logback.classic.html.HTMLLayout">

<pattern>%X%ip%date%level%thread%logger{0}%message</pattern>

</layout>

<filter class="ch.qos.logback.classic.filter.ThresholdFilter">

<level>ERROR</level>

</filter>

</appender>

<root level="info">

<appender-ref ref="MAIL"/>

</root>

</configuration>

@Component

public class MyPropertyDefiner extends PropertyDefinerBase {

@Override

public String getPropertyValue() {

System.out.println("自定义的PropertyDefinerBase的getPropertyValue方法");

try {

mailTo = // 从数据库获取

} catch (Exception e) {

e.printStackTrace();

}

return mailTo;

}

public static void updateProperty(String propertyName, String propertyValue) {

LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

loggerContext.putProperty(propertyName, propertyValue);

loggerContext.reset();

}

}

设想是通过自定义的方式从数据库获取mailTo配置信息,数据库更新时会调用一遍getPropertyValue()方法以达到更新目的,但显然不行,只能使用服务初次启动加载时获取到的初始值,比如服务启动时数据库中mailTo='xxx@163.com'后续即使修改成其他如:yyy@163.com也无用,依然发送到初始的xxx@163.com邮箱,也就是这种方法是行不通的,并不能更新Logback初始的缓存配置,那么请教有没有其他方法能满足动态更新?


回答:

public void updateMailTo(String newMailTo) {

LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {

for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders(); index.hasNext(); ) {

Appender<ILoggingEvent> appender = index.next();

if (appender instanceof SMTPAppender) {

SMTPAppender smtpAppender = (SMTPAppender) appender;

smtpAppender.addTo(newMailTo);

}

}

}

}

**

以上是 Logback-spring.xml配置中的参数property如何从数据库动态获取? 的全部内容, 来源链接: utcz.com/p/945237.html

回到顶部