Spring 依赖配置文件的 log4j2 配置

Profile-dependent log4j2 configuration with Spring

我正在尝试在 Spring 引导应用程序中使用 log4j2 和 Gradle。我有 4 个不同的配置文件:it, dev, mac, was。相应地,我有 4 个不同的 log4j2 配置文件:log4j2-it.xml, log4j2-dev.xml, log4j2-mac.xml, log4j2-was.xml。根据 selected 配置文件,我想选择正确的 log4j2 配置文件,以便对其进行相应配置。

首先,为了让 log4j2 正常工作,我排除了 spring-boot-starter-logging 并包含在内 spring-boot-starter-log4j2。在执行此操作之前,log4j2 根本不起作用。

我调查了 , but I could not get the accepted answer to work. According to ,设置 logging.config 属性 不行。此外,我的项目没有启动脚本,所以我无法传递带有 -D 标志的参数。

我已经能够 select 通过添加一个配置文件 log4j2.component.properties 文件并指定要在那里使用的配置文件 (see here),但是我还没有找到使这个配置文件依赖的方法。

此外,如果我有一个名为 log4j2.xml 的文件,它会按预期被发现并加载。

经过大量搜索后,我看到了很多 logback 的解决方案,并试了一下它们是否适用于 log4j2,但不出所料 none 其中成功了。

我有办法做到这一点吗?例如,当 运行 测试 it 配置文件时 selected 并且 log4j2-it.xml 文件应该用于配置日志记录。也许我遗漏了什么,因为我希望配置文件特定的 log4j2 配置应该是可能的,但到目前为止我还没有找到任何有效的东西。

我最终添加了一个 @Component 和一个 @PostConstruct 方法,其中我做了

LoggerContext context = (LoggerContext)LogManager.getContext(false);
context.setConfigLocation(URI.create("path to file"));
context.reconfigure();

感谢alan7678的回答