0

下面是 consoleAppender 和 LogAppenders 的编程配置,我为 log4j 从 1 升级转换到 2.17.1 版本。

    //Programmatic configuration of ConsoleAppender  log4j2
    String pattern = "%d{DATE} [%p|%C{2}] %m%n";
    ConfigurationBuilder<BuiltConfiguration> builder = 
           ConfigurationBuilderFactory.newConfigurationBuilder();
    
    builder.setConfigurationName("DefaultLogger");
    // Create pattern layout
    LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
                            .addAttribute("pattern", pattern);
    AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
                    .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
    appenderBuilder.add(layoutBuilder);
    builder.add(appenderBuilder);
    RootLoggerComponentBuilder rootLogger
                    = builder.newRootLogger(Level.DEBUG);
    rootLogger.add(builder.newAppenderRef("Console"));
    
    builder.add(rootLogger);
    Configurator.initialize(builder.build());
    Configurator.reconfigure(builder.build());
    
    //RollingFileAppender Programmatic configuration log4j2:
    
    CdasLogger() {
        // CreateLogger takes a path for each logger from config file
        loadLog = createLogger("load.log");
        updateLog = createLogger("update.log");
        userLog = createLogger("user.log");
    }
    
    private Logger createLogger(String logType) {
    
        String pattern = "%d %M - %m%n";
        String consolePattern = "%d{DATE} [%p|%C{2}] %m%n";
        String fileLogName = "/app/app.log";
        String filePattern = "/app/app.log-%d{MM-dd-yy}.log.gz";
        System.out.println("logtype is::" + logType);
        String path = ConfigReader.getStringValue(logType);
        System.out.println(path);
        String daily = "0 0 12 1/1 * ? *";
        // Initializing the logger context
        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        ConfigurationBuilder<BuiltConfiguration> builder = 
                ConfigurationBuilderFactory.newConfigurationBuilder();
    
    
        builder.setConfigurationName("rollingFileLogger");
        //specifying the pattern layout
        LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
                    .addAttribute("pattern", pattern);
        //specifying the policy for rolling file
        ComponentBuilder triggeringPolicy = builder.newComponent("Policies")                 
    .   addComponent(builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", "10MB"));
    
    //create a rollingfile appender
    AppenderComponentBuilder appenderBuilder = builder.newAppender("rollingFile", "RollingFile")
                    .addAttribute("fileName", path)
                    .addAttribute("filePattern", path+"-%d{MM-dd-yy-HH-mm-ss}.log.")
                    .add(layoutBuilder)
                    .addComponent(triggeringPolicy);
    
    builder.add(appenderBuilder);
    RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.TRACE);
    rootLogger.add(builder.newAppenderRef("rollingFile"));
    builder.add(rootLogger);
    
    ctx = Configurator.initialize(builder.build());
    Configurator.reconfigure(builder.build());
    
    return ctx.getLogger(logType); // return the logger to the caller
}

Console Appender 首先被初始化并写入日志。在初始化 rollingfileappender 之后。所有日志都被写入rollingfile Appender。一旦 rollingfile appender 被初始化,consoleAppender 就没有日志了。

编辑1:

根据 Piotr 的评论,我进行了以下更改,以使所有附加程序具有相同的配置生成器。

 private void configureLogger() {
        ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();

        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        // create a console appender
        AppenderComponentBuilder console
            = builder.newAppender("stdout", "Console").addAttribute("target",
                    ConsoleAppender.Target.SYSTEM_OUT);


        console.add(builder.newLayout("PatternLayout").addAttribute("pattern",
                "%d{DATE} [%p|%C{2}] %m%n"));

        RootLoggerComponentBuilder rootLogger
            = builder.newRootLogger(Level.DEBUG);
        rootLogger.add(builder.newAppenderRef("stdout"));

        builder.add(console);

        // create a rolling file appender

        String pattern = "%d %M - %m%n";
        
        //specifying the pattern layout
        LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
                    .addAttribute("pattern", pattern);
        //specifying the policy for rolling file
        ComponentBuilder triggeringPolicy = builder.newComponent("Policies")
                   .addComponent(builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", "10MB"));

        String[] logTypes = {"load.log", "update.log", "user.log"};

        for (String logType : logTypes) {
            System.out.println("logtype is::" + logType);
            String path = ConfigReader.getStringValue(logType);
            System.out.println(path);
            AppenderComponentBuilder appenderBuilder = builder.newAppender(logType, "RollingFile")
                        .addAttribute("fileName", path == null ? "/app1/app.log" : path)
                        .addAttribute("filePattern", path == null ? "/app1/app.log" : path+"-%d{MM-dd-yy-HH-mm-ss}.log.")
                        .add(layoutBuilder)
                        .addComponent(triggeringPolicy);
        
            builder.add(appenderBuilder);
            rootLogger.add(builder.newAppenderRef(logType));
        }


        builder.add(rootLogger);
        Configurator.reconfigure(builder.build());

    }

日志仍然没有更新。

configureLogger()在应用程序启动期间调用方法。

在另一个类中,我有下面的代码

public class CdasLogger {

    private final Logger updateLog, loadLog, userLog;
    CdasLogger() {
        loadLog = createLogger("load.log");
        updateLog = createLogger("update.log");
        userLog = createLogger("user.log");
    }
private Logger createLogger(String logType) {

    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    return ctx.getLogger(logType);
 }
}
4

0 回答 0