简体   繁体   English

如何指定 Log4J 2.x 配置位置?

[英]How to specify Log4J 2.x config location?

Is there any way to specify Log4J 2.x log4j2.xml file location manually (like DOMConfigurator in Log4J 1.x), without messing with classpath and system properties?有没有办法手动指定 Log4J 2.x log4j2.xml文件位置(如 Log4J 系统属性中的DOMConfigurator和混乱系统属性)?

You could use the static method #initialize(String contextName, ClassLoader loader, String configLocation) (see source here ) in org.apache.logging.log4j.core.config.Configurator .您可以在org.apache.logging.log4j.core.config.Configurator使用静态方法#initialize(String contextName, ClassLoader loader, String configLocation) (请参阅此处的源代码)。 (You can pass null for the class loader.) (您可以为类加载器传递 null。)

Be aware that this class is not part of the public API so your code may break with any minor release .请注意,此类不是公共 API 的一部分,因此您的代码可能会因任何次要版本而中断

For completeness, you can also specify the location of the configuration file with this system property:为了完整起见,您还可以使用此系统属性指定配置文件的位置:

-Dlog4j.configurationFile=path/to/log4j2.xml

在 Windows 中,请注意您需要使用带有log4j.configurationFile属性的 URI

-Dlog4j.configurationFile=file://C:\path\to\log4j2.xml

If you are using log4j2 and properties are in defined in log4j2.properties file then use this.如果您使用的是 log4j2 并且属性在 log4j2.properties 文件中定义,则使用它。

-Dlog4j2.configurationFile=file:/home/atul/log4j2.properties -Dlog4j2.configurationFile=file:/home/atul/log4j2.properties

Using the LoggerContext allows to setConfigLocation .使用 LoggerContext 允许setConfigLocation

File f = new File(this.logConfigFile);
URI fc = f.toURI();         
System.out.println("Loading logging config file: " + fc);
Logger l = (Logger) LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
l.getContext().setConfigLocation(fc);

or alternatively或者

LoggerContext.getContext().setConfigLocation(java.net.URI);

You can initialize like below as well您也可以像下面这样初始化

ConfigurationSource source = new ConfigurationSource(new FileInputStream(log4j file Path));
XmlConfiguration xmlConfig = new XmlConfiguration(source);
Logger logger = (Logger) LogManager.getLogger(); 
logger.getContext().start(xmlConfig); 

In each class you can get logger instance as below在每个类中,您都可以获得如下记录器实例

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

private final Logger logger = LogManager.getLogger(ABC.class);

For log4j version 2.12.1, you can find how to reconfigure log4j2 here .对于 log4j 版本 2.12.1,您可以在此处找到如何重新配置​​ log4j2。

Below is an example下面是一个例子

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;

File file = new File("C:\\Path for Windows OS\\yourConfig.xml");
    
LoggerContext context = (LoggerContext) LogManager.getContext(false);
context.setConfigLocation(file.toURI());
    
Logger log  = LogManager.getLogger(YourClass.class);

It seems to me that way of configuring log4j2 is changing with new releases, so you should be aware of that.在我看来,配置 log4j2 的方式正在随着新版本而改变,所以你应该意识到这一点。

Step: 1 - Get ready with your log4J.xml file with the appender details (Mostly under the resource folder)步骤:1 - 准备好带有附加程序详细信息的 log4J.xml 文件(主要在资源文件夹下)

Step: 2 - Following code should be added to the configuration class (In the previous log4J we had PropertyConfigurator and now we need to go with LoggerContext )步骤:2 - 应将以下代码添加到配置类(在以前的 log4J 中,我们有PropertyConfigurator ,现在我们需要使用LoggerContext

String log4JFilePath = "file path of your log4J.xml file";
LoggerContext loggerContext = (LoggerContext)LoggerManager.getContext(false);
File file = new File(log4JFilePath);
loggerContext.setConfigLocation(file.toURI());

Step: 3 - Add the following line to utilise the logger in any classes步骤:3 - 添加以下行以在任何类中使用记录器

private static final Logger logger = LogManager.getLogger(yourClassName.class);

logger.info("log here");

 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;

public class Foo {
    public static void main(String[] args) {

     Configurator.initialize(null, "src/main/config/log4j2.xml"); //path specify

     Logger logger = LogManager.getLogger(APITestToolMain.class);
     logger.info("working");
    }
}
void initializeLogger()
{      
    try
        {
            String basepath=checkpath();
            File f = new File(basepath+"\\config\\log4j2.properties");
            URI fc = f.toURI(); 
            LoggerContext context = (LoggerContext) LogManager.getContext(false);
            context.setConfigLocation(f.toURI());
        }
        catch (Exception e)
        {
            errorlog="Unable to load logging property:";
            System.out.println(errorlog+": "+e.getMessage());
        }   
}

This is the way I initialize my log4j2 properties file from a different location, so what I simply do is to call the initializeLogger() method in my main method.这是我从不同位置初始化 log4j2 属性文件的方式,所以我只需在我的 main 方法中调用 initializeLogger() 方法。

And it works perfectly.而且效果很好。

Perhaps you need to see what the checkpath() blocks looks like, I added the function below.也许你需要看看 checkpath() 块是什么样子的,我在下面添加了 function。

String checkpath()
    {
        String parentpath="";
        try
        {
           URL url=getClass().getProtectionDomain().getCodeSource().getLocation();
           File f=new File(url.toURI());
           parentpath=f.getParent();
        }
        catch(Exception ex)
        {
            //logger.error("unable to retrieve application parent path");
        }
        return parentpath;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM