运行时添加log4j2的appender

0

实例

比如在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


如果觉得我的文章对你有用,请随意赞赏

你可能感兴趣的

载入中...