Created
September 5, 2017 08:55
-
-
Save yangl/6957d8527cb63e24cfb0181e3a300249 to your computer and use it in GitHub Desktop.
使用disconf动态配置log4j2.xml(由于新项目第一次启动还没有下载到disconf配置中心的配置,故会使用log4j2的默认配置DefaultConfiguration)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1.bean初始化时加载; | |
2.配置更改时重新加载; | |
https://logging.apache.org/log4j/2.0/faq.html#reconfig_from_code | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.xxx.conf; | |
import com.baidu.disconf.client.common.annotations.DisconfFile; | |
import com.baidu.disconf.client.common.annotations.DisconfUpdateService; | |
import com.baidu.disconf.client.common.update.IDisconfUpdate; | |
import java.net.URISyntaxException; | |
import java.net.URL; | |
import org.apache.logging.log4j.LogManager; | |
import org.apache.logging.log4j.core.LoggerContext; | |
import org.springframework.beans.factory.InitializingBean; | |
import org.springframework.stereotype.Component; | |
/** | |
* 自动加载log4j2.xml配置(由于新项目第一次启动还没有下载到disconf配置中心的配置,故会使用log4j2的默认配置DefaultConfiguration) | |
* | |
* 在disconf统一配置中心后台改动会自动重新加载最新配置 | |
* | |
* @author YANGLiiN 2017-09-05 13:41 | |
*/ | |
@Component | |
@DisconfFile(filename = Log4j2Disconf.LOG4J2_CONFIG_NAME) | |
@DisconfUpdateService(classes = {Log4j2Disconf.class}) | |
public class Log4j2Disconf implements InitializingBean, | |
// ApplicationListener<ContextStartedEvent>, | |
IDisconfUpdate { | |
public static final String LOG4J2_CONFIG_NAME = "log4j2.xml"; | |
@Override | |
public void afterPropertiesSet() throws Exception { | |
loadProperties(); | |
} | |
// @Override | |
// public void onApplicationEvent(ContextStartedEvent event) { | |
// loadProperties(); | |
// } | |
@Override | |
public void reload() throws Exception { | |
loadProperties(); | |
} | |
private void loadProperties() { | |
URL url = Log4j2Disconf.class.getResource("/" + LOG4J2_CONFIG_NAME); | |
LoggerContext context = (LoggerContext) LogManager.getContext(false); | |
try { | |
// this will force a reconfiguration | |
context.setConfigLocation(url.toURI()); | |
} catch (URISyntaxException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment