运行时添加log4j2的appender
实例
比如在root logger下新增一个自己的appender ref
public static void load(String appId,String serverAddress,int port){ final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final org.apache.logging.log4j.core.config.Configuration config = ctx.getConfiguration(); PatternLayout layout= PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss} [%t] (%F:%L) - %m%n", null, config,null, Charset.forName("UTF-8"),true,false,null,null); Appender appender= MyLog4j2Appender.createAppender("MyLog4j2Appender",layout, null, null); appender.start(); config.addAppender(appender); config.getLoggerConfig("ROOT").addAppender(appender, Level.ERROR,null); ctx.updateLoggers(config); }
其实对应的xml配置就是
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="warn" name="MyApp" packages=""> <Appenders> <Console name="Console" target="SYSTEM_OUT" ignoreExceptions="false"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] (%F:%L) - %m%n" /> </Console> <MyLog4j2Appender name="MyLog4j2Appender" > <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] (%F:%L) - %m%n" /> </MyLog4j2Appender> </Appenders> <Loggers> <Root level="debug"> <AppenderRef ref="Console" /> <AppenderRef ref="MyLog4j2Appender" level="error" /> </Root> </Loggers> </Configuration>
docs
相关推荐
chw0 2020-11-04
大唐帝国前营 2020-08-18
sdaq 2020-07-26
MrLiar 2020-07-07
sdaq 2020-06-16
CXC0 2020-06-14
丨Fanny丨Cri 2020-06-13
CXC0 2020-06-08
dongxurr 2020-06-07
sdaq 2020-06-06
MrLiar 2020-06-04
丨Fanny丨Cri 2020-06-03
MrLiar 2020-05-25
丨Fanny丨Cri 2020-05-17
MrLiar 2020-05-14
MrLiar 2020-05-12
sdaq 2020-05-11