-
I hope to dynamically configure log4j at some point and output logs without interfering with the core logging (log4j2-spring.xml). But after I did this, I also closed the core log. What should I do? Here is my example code: @RestController
public class SampleController {
private static final Logger LOGGER = LogManager.getLogger();
@RequestMapping("log")
public String log() throws IOException {
LOGGER.info("start");
Set<Map<String, Object>> set = new HashSet<>();
for (int i = 0; i < 1; i++) {
HashMap<String, Object> map = new HashMap<>();
map.put("name", i);
map.put("age", i);
set.add(map);
}
this.logMetadata(set);
// There is no output because it is closed.
LOGGER.info("finish!");
return "ok";
}
public void logMetadata(Set<Map<String, Object>> set) throws IOException {
try (LoggerContext loggerContext = this.buildMetadataLogContext()) {
for (Map<String, Object> map : set) {
String content = new ObjectMapper().writeValueAsString(map);
Logger logger = loggerContext.getLogger(SampleController.class);
logger.info(content);
}
}
}
private LoggerContext buildMetadataLogContext() {
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
// PatternLayout
AppenderComponentBuilder console = builder.newAppender("console", "Console");
LayoutComponentBuilder patternLayout = builder.newLayout("PatternLayout");
console.add(patternLayout);
builder.add(console);
// Root Logger
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.INFO);
rootLogger.add(builder.newAppenderRef("console"));
builder.add(rootLogger);
Configuration configuration = builder.build(false);
Configurator.reconfigure(configuration);
return Configurator.initialize(configuration);
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
ppkarwasz
Mar 12, 2025
Replies: 1 comment 2 replies
-
I understand, we need to create a new LoggerContext ourselves |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, if you wish to have an entirely separate set of loggers, you need to create a new
LoggerContext
:The fact that
LoggerContext
can be used withtry-with-resources
is a bug: you should close the context at the appropriate moment, e.g. when your application closes.Remarks
Hardcoded config
I would not recommend using a hardcoded configuration, since your users might want to modify that. Unless explicitly configured, each logger context looks for configuration files named
log4j2-<contextName>.<extension>
(see c…