Log4j2 error loading XML configuration file

I am trying to use the XML configuration file for Log4j2, which is built into my Java application, but does not work.

The code:

ConfigurationSource source = new ConfigurationSource(Main.class.getResourceAsStream("/in/gunbound/prelauncher/server/log4j2/log4j2.xml"));
ConfigurationFactory factory = (ConfigurationFactory) XMLConfigurationFactory.getInstance().getConfiguration(source);
ConfigurationFactory.setConfigurationFactory(factory);

Error:

An exception in the thread "main" java.lang.ClassCastException: org.apache.logging.log4j.core.config.XMLConfiguration cannot be added to org.apache.logging.log4j.core.config.ConfigurationFactory on in.gunbound.prelauncher. server.Main.main (Main.java:62)

+5
source share
4 answers

When using an XML configuration file you do not need to use ConfigurationFactory. Just make sure your XML file is configured correctly.

The file name must be log4j2.xml

The file must be added to classPath.

, , XML , .

+2

. , : https://svn.apache.org/repos/asf/logging/log4j/log4j2/trunk/core/src/test/java/org/apache/logging/log4j/FormatterLoggerManualExample.java

:

URI configuration = Main.class.getResource("/in/gunbound/prelauncher/server/log4j2/log4j2.xml").toURI();
Configurator.initialize("config", null, configuration);
+2

, :

import java.io.InputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory.ConfigurationSource;
import org.apache.logging.log4j.core.config.XMLConfigurationFactory;

public class Log
{

    private Logger logger;

    public Log(String name)
    {
        InputStream is = Application.class.getResourceAsStream("log-config.xml");
        ConfigurationSource source = new ConfigurationSource(is);
        Configuration config = XMLConfigurationFactory.getInstance().getConfiguration(source);
        LoggerContext ctx = (LoggerContext) LogManager.getContext(true);

        ctx.stop();
        ctx.start(config);

        logger = ctx.getLogger(name);
    }

    public Logger getLog()
    {
        return logger;
    }

}

log4j2 beta 9 databaseAppender ora db.

+2

( factory, URL-):

Configurator.initialize("configName", "logging.xml");

This works even if the configuration file is not named "log4j2. *".

0
source

All Articles