0

我试图让 log4j2 在 fatjar 中工作。在 intellij 中运行时一切正常,但是在构建我的 fatjar 时运行它就像

java -jar dx.jar

只有错误被记录到控制台,而没有任何东西被记录到滚动文件中。它接缝忽略了我的配置。

配置:

        String logFile = logPath + "dxpos.log";
        String logFilePattern = logPath + "dxpos-%d{yyyy-MM-dd}.log";

        LogManager.shutdown();

        var builder = ConfigurationBuilderFactory.newConfigurationBuilder();

        var layout = builder.newLayout("PatternLayout")
                .addAttribute("pattern", "%d{yyyy-MM-dd HH:mm:ss} %-5p [%t] %c: %m%n");

        var console = builder.newAppender("console", "Console")
                .addAttribute("target", "SYSTEM_OUT")
                .addAttribute("immediateFlush", true)
                .add(layout);

        var triggeringPolicy = builder.newComponent("Policies")
                .addComponent(builder.newComponent("TimeBasedTriggeringPolicy"))
                .addComponent(builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", "100M"));
        var rollingFile = builder.newAppender("rollingFile", "RollingFile")
                .addAttribute("fileName", logFile)
                .addAttribute("filePattern", logFilePattern)
                .addAttribute("immediateFlush", true)
                .addAttribute("append", true)
                .addComponent(triggeringPolicy)
                .add(layout);

        var rootLogger = builder.newRootLogger(Level.INFO)
                .add(builder.newAppenderRef("console"))
                .add(builder.newAppenderRef("rollingFile"));

        builder.add(console);
        builder.add(rollingFile);
        builder.add(rootLogger);
        
        Configurator.initialize(builder.build());
4

1 回答 1

0

搜索文件后,我从编程配置方法切换到 XML

要让它工作,你必须声明记录器

public static Logger logger = null; 

添加一些类似的变量

MDC.put("logFile", logFile);
MDC.put("LogFilePattern", logFilePattern);

并创建记录器

logger = LoggerFactory.getLogger(MainForm.class);
于 2021-09-09T13:28:05.247 回答