实例

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


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...


引用和评论

0 条评论