What is getCurrentLoggers's analog in log4j2 - java

How can i get all loggers used used in log4j2? In log4j i could use getCurrentLoggers like described here: Number of loggers used

get all loggers used in log4j2:
LoggerContext logContext = (LoggerContext) LogManager
.getContext(false);
Map<String, LoggerConfig> map = logContext.getConfiguration()
.getLoggers();
Attention:
use org.apache.logging.log4j.core.LoggerContext
not org.apache.logging.log4j.spi.LoggerContext

looks like i've found the way:
File configFile = new File("c:\\my_path\\log4j2.xml");
LoggerContext loggerContext = Configurator.initialize("my_config", null, configFile.toURI());
Configuration configuration = loggerContext.getConfiguration();
Collection<LoggerConfig> loggerConfigs = configuration.getLoggers().values();

YuriR's answer is incomplete in that it does not point that LoggerConfig objects are returned, not Logger. This is the fundamental difference between Log4j1 and Log4j2 - Loggers cannot be dirrectly manipulated in Log4j2. See Log4j2 Architecture for details.

If you are running in a web app, you may have multiple LoggerContexts.
Please take a look at how LoggerConfigs are exposed via JMX in the org.apache.logging.log4j.core.jmx.Server class.

LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Collection<? extends Logger> loggers = ctx.getLoggers();

It's important to note that LoggerConfig objects are being returned by getLoggers() and NOT the loggers themselves. As vacant78 pointed out, this is only good for setting the configuration for loggers that have yet to be instantiated. If you already have a bunch of loggers already instantiated, changing the configuration using this method does no good.
For example, to change the level of logging at runtime, refer to this link, which utilizes an undocumented API within Apache (no surprise there) that will change all your currently instantiated logger levels: Programmatically change log level in Log4j2

Related

Equivalent programmatic logger initialization for log4j to log4j2 migration

I am trying to understand the programmatic side of log4j2, as I am migrating a lot of log4j 1.2 code. The following seems to be very different and more complicated to accomplish:
org.apache.log4j.Logger.getRootLogger().setLevel(Level.FATAL);
org.apache.log4j.Logger.getRootLogger().addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "System.err"));
Can someone with plenty of log4j2 experience explain to me what the simple way to migrate the 2 above lines is?
EDIT: This is what I have so far:
LoggerContext context = (LoggerContext) LogManager.getContext(false);
Configuration config = context.getConfiguration();
config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(Level.FATAL);
PatternLayout patternLayout = PatternLayout.createLayout(PatternLayout.TTCC_CONVERSION_PATTERN, config, null, null, true, true, null, null);
Layout<? extends Serializable> layout = patternLayout;
ConsoleAppender consoleAppender = ConsoleAppender.createAppender(layout , null, "SYSTEM_ERR", "System.err", null, null);
consoleAppender.start();
config.addAppender(consoleAppender);
context.updateLoggers();
There is no way it is that complicated, right?
Unfortunately creating programmatic configuration wasn't the main concern of Log4j2. You may check on their AbstractConfiguration class sources line 580 to see how default configuration is set programmatically internally.
Log4j2 library have good support for different types of configuration files (xml, json, properties, yaml) or you can build composite configuration out of several sources. Also it tracks configuration files and is capable of dynamic reloading.
I would remmend you evaluating features mentioned above to update configuration from code. E.g.
final URL log4j = Resources.getResource("log4j2-test.xml");
ConfigurationSource configurationSource = new ConfigurationSource(
Resources.asByteSource(log4j).openStream(), log4j);
LoggerContext context = LoggerContext.getContext(false);
XmlConfiguration xmlConfiguration = new XmlConfiguration(context, configurationSource);
context.start(xmlConfiguration);
Seem easier to manage than programmatic way with larger configurations.

Logback: Load groovy config

How can I programmatically load custom named groovy config (logback-config.groovy) config?
When I tries:
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(loggerContext);
configurator.doConfigure(this.getClass().getResource("/logback-config.groovy"));
Got expt:
ch.qos.logback.core.joran.spi.JoranException: Problem parsing XML
document. See previously reported errors.
What's wrong?
The issue here is that the JoranConfigurator is specific only for XML configurations; for Groovy config files, logback uses a different class GafferConfigurator. (Unfortunately, the logback documentation does not do a good job of advertising this fact.) But rather than reference the GafferConfigurator directly, it would be better to use the ContextInitializer class instead:
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
new ContextInitializer(loggerContext).configureByResource(this.getClass().getResource("/logback-config.groovy"));
This allows you to handle both XML and Groovy filetypes simultaneously, as well as take advantage of some of logback's built-in error checking.

Shutting up log4j for good

Im using a 3rd party jar that uses log4j and spams really way too much (makes eclipse crash), is there a way to wipe all logging as if log4j never existed in the first place? programmatically or by project setup anything is fine as long as it stfu.
i tried
List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for ( Logger logger : loggers ) {
logger.setLevel(Level.OFF);
}
But doesnt compile in my setup:
LogManager.getCurrentLoggers() and
LogManager.getRootLogger() do not exist.
Log4j2 uses multiple contexts. Adapting the above code:
LoggerContext ctx = (LoggerContext) LogManager.getContext();
Configuration config = ctx.getConfiguration();
Collection<LoggerConfig> loggers = config.getLoggers().values();
for(LoggerConfig cfg: loggers) {
cfg.setLevel(Level.OFF);
}

How to add appender to Logger in Log4j2

In Log4j 1.2, you could simply take a logger and add an appender at runtime. This was handy for test purposes for instance. We used to create a mock appender and add it to the logger. Subsequently we could make different assertions.
What is the equivalent thing with log4j2?
This example for instance shows how other people were adding test appenders.
The log4j2 page shows a few examples on how to add appenders. However, they add appenders to the overall context. Which seems different from adding appenders for one specific logger.
Another observation is that if you use org.apache.logging.log4j.core.Logger as opposed to org.apache.logging.log4j.Logger, you can still add appenders. However most people use org.apache.logging.log4j.Logger. And in fact, LogManager returns an instance of org.apache.logging.log4j.Logger. So, I am not sure how to connect these two classes and whether they should be connected at all.
Another observation is that if I call
LogManager.getContext().getConfiguration().getLoggers()
I can get a ist of all LoggerConfig objects in the context. I subsequently add appenders to any LoggerConfig object. The question however is, how do I get the LoggerConfig related to an instance of org.apache.logging.log4j.Logger?
This is confusing me.
org.apache.logging.log4j.Logger is an interface located in the log4j-api module. org.apache.logging.log4j.core.Logger is a concrete class (implementing the above interface) which lives in the log4j-core module.
LogManager (also in the log4j-api module) returns something that implements the org.apache.logging.log4j.Logger interface, and if the log4j-core module is in the classpath this will be an instance of org.apache.logging.log4j.core.Logger.
So you can cast the returned Logger to org.apache.logging.log4j.core.Logger and add the Appender.
Each core Logger has a LoggerConfig (1-to-1 relationship). You can find the LoggerConfig that corresponds to the desired Logger because they have the same name.

What is an equivalent of LoggerRepository in log4j2

I want to migrate from Log4j 1.x to log4j2 so I read this article:
http://logging.apache.org/log4j/2.x/manual/migration.html
In our application we are using LoggerRepository:
Logger.getRootLogger().getLoggerRepository().getCurrentLoggers();
what is the equivalent of this piece of code in log4j2. Because in article they said we can't access to this method but they don't mention how should I replace it
If I understand your need correctly, you can go via LogManager to get the LoggerContext's configuration and retrieve the Loggers from that:
LoggerContext ctx = LogManager.getContext();
Configuration cfg = ctx.getConfiguration();
Map<String, LoggerConfig> loggers = cfg.getLoggers();

Categories