简体   繁体   English

如何分离 Log4j 配置?

[英]How to separate a Log4j configuration?

I've got a program that has a log4j configuration written in XML.我有一个程序,它有一个用 XML 编写的 log4j 配置。 I am trying to modify the original application, and attempting to improve upon the previous logger config.我正在尝试修改原始应用程序,并尝试改进以前的记录器配置。

Since I cannot modify the xml file itself, I want to be able to generate a new configuration through the ConfigurationBuilderFactory , and use it alongside the other config.由于我无法修改 xml 文件本身,我希望能够通过ConfigurationBuilderFactory生成新ConfigurationBuilderFactory ,并将其与其他配置一起使用。 The only issue is that, I am unable to accomplish this.唯一的问题是,我无法做到这一点。 It does not seem to want to work with both.它似乎不想与两者一起工作。

What can I do?我能做什么?

The following is my code, greatly simplified:以下是我的代码,大大简化了:

/**
 * Internally uses {@link org.apache.logging.log4j.Logger}
 */
public final class MyLogger {
    private static final LoggerContext context;

    static {
        ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
        {
            builder.setStatusLevel(WARN);

            AppenderComponentBuilder console = builder.newAppender("SysOut", "Console");
            console.addAttribute(...);
            console.add(builder.newLayout(...).addAttribute(...));
            builder.add(console);

            // ... more configuration below
        }

        context = Configurator.initialize(builder.build()); // only works if no previous config exists, but will not replace an old config
    }
}

// later on...

context.getLogger("MyLogger"); // uses the xml config, not the one written above

I think you can create your own log4j.xml .我认为您可以创建自己的log4j.xml You have to ensure that your XML will be loaded in your program.您必须确保您的 XML 将加载到您的程序中。 So just define the resource containing your XML in the Java Classpath before the resource containing the other XML.因此,只需在包含其他 XML 的资源之前在Java 类路径中定义包含您的 XML 的资源。

For creating loggers using the ConfigurationBuilder API programmatically you can refer below code.要以编程方式使用 ConfigurationBuilder API 创建记录器,您可以参考以下代码。

It creates a logger in log4j2 environment added with some layout and appenders defined :它在 log4j2 环境中创建了一个记录器,并添加了一些布局和附加器定义:

public class Log4j2Logger {

int counter = 0;

LoggerContext ctx;

Configuration config;

Logger logger;

String loggerName = "testLogger";

String appenderName = "myAppender";

static String testMessage = "This is a Test Message";

public void log() {

    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    final LoggerComponentBuilder loggerComp = builder.newLogger(loggerName, Level.ALL).addAttribute("additivity",
            false);
    builder.add(loggerComp);
    config = builder.build();
    ctx = Configurator.initialize(config);
    config = ctx.getConfiguration();
    ctx.start(config);
    ctx.updateLoggers(config);

    // To create/add the logger of the configuration specified above we can use the
    // getLogger(..) method
    logger = ctx.getLogger(loggerName);

    // Now we need to attach an appender to the logger so that our messages could be
    // logged
    logger.addAppender(addConsoleAppender(ctx.getConfiguration(), appenderName));
    while (counter < 10) {
        logger.error(testMessage + counter);
        counter++;
    }

}

private Appender addConsoleAppender(Configuration config, String appenderName) {
    Appender consoleAppender = ConsoleAppender.newBuilder().setConfiguration(config).setName(appenderName)
            .withImmediateFlush(true).build();
    consoleAppender.start();
    return consoleAppender;
    }

}

And for testing, you can have following in any test class:对于测试,您可以在任何测试类中进行以下操作:

Log4j2Logger testLogger = new Log4j2Logger();
testLogger.log();

This API helps you to handle logs in a powerful way.此 API 可帮助您以强大的方式处理日志。

You can :你可以 :

  • Create multiple loggers with your configuration使用您的配置创建多个记录器
  • Add multiple Appenders to it.向其中添加多个 Appender。
  • Configure them also.也配置它们。
  • Remove logger when the usage is over.使用结束后删除记录器。
  • Create Asynchronous Loggers also.也创建异步记录器。

PS : I have used log4j2 version 2.12.1. PS:我用的是log4j2 2.12.1版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM