Log4j: programmatically change the log level that works for generated logs

I declare registrars in my code as follows:

Logger logger = LoggerFactory.getLogger(MyClass.class); 

I want that at runtime I can change the log level of my registrars. I tried iterating over the registrars in the repository through LogManager, but it only applies the new log level to the registrars that are created in the code. If a new journal instance is created, it does not use the new journal level. My requirement is that the log level in my web application should be configured using the administrative GUI, and this new log level should apply to all loggers in my code (excluding third-party logging, such as JSF, Spring, Hibernate, etc. .).

This is what I am doing now that does not meet my requirements as it does not apply the log level for newly created logs:

 Enumeration<Logger> currentLoggers = LogManager.getCurrentLoggers(); while(currentLoggers.hasMoreElements()) { Logger logger = currentLoggers.nextElement(); if (StringUtils.startsWith(logger.getName(), "com.my.company")) { logger.setLevel(logLevel); } } 

I am using Log4j 1.2.17.

+6
source share
1 answer

I didn’t find the resource anymore, but as for my faded memory LogManager.getLogger("com.my.company").setLevel(whateverloglevel) , then it should complete the task.

All logs created using LogManager.getLogger(MyClass.class) , where MyClass is in com.my.company or in a subtree, will be affected.

whateverloglevel is one of the Level :

<L> ALL ALL has the lowest possible rank and is intended to include all logging. DEBUG Level> ERROR Level < FATAL Level n = INFO Level OFF OFF has the highest possible rank and is designed to disable registration. TRACE Level & WARN The security level WARNING indicates potentially dangerous situations. Dd> For>
+10
source

Source: https://habr.com/ru/post/974369/


All Articles