简体   繁体   English

Log4J动态配置

[英]Log4J dynamic configuration

Is there any way to configure log4j loggers dynamically. 有没有办法动态配置log4j记录器。 I want each instance of a class to write to a different file (base on say some property that is unique between instances). 我希望每个类的实例都写入一个不同的文件(基于一些在实例之间唯一的属性)。 I would like to configure everything except the file from XML configuration and then for each instance to set the file. 我想配置除XML配置文件以外的所有内容,然后为每个实例配置文件。

Is there any way to do this using log4j? 有没有办法用log4j做到这一点?

Ok, from your comment, here what i would try. 好的,从你的评论,我在这里尝试。

I imagine you will create your 10 instances at the start of your app.!? 我想你会在你的应用程序开始时创建你的10个实例。 anyway. 无论如何。

In your log4j.xml, define 10 appender with name = yourUniqueId (this unique id will be sort of hard coded) 在你的log4j.xml中,使用name = yourUniqueId定义10 appender(这个唯一的id将被硬编码)

Make these appender write to yourUniqueid.log 将这些appender写入yourUniqueid.log

<logger name="yourUniqueId" additivity="false">
    <level value="INFO" />
    <appender-ref ref="fileAppender" />
</logger>

<appender name="fileAppender" class="org.apache.log4j.FileAppender">
<param name="File" value="/path/yourfile.log"/>

    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{dd MM yyyy HH:mm:ss,SSS} %m%n"/>
    </layout>
</appender>

Then in your object constructor, instantiate the right Logger with the object unique id. 然后在对象构造函数中,使用对象唯一ID实例化正确的Logger。

Something like that: 像这样的东西:

public MyClassContructor(){
     String uniqueId = getMyUniqueIdFromSomewhere();
     logger = Logger.getLogger(uniqueId);
} 

I think you don't want to mess around with log4j.xml, then you would have to use the log4j API and create your own appender based on your unique id 我想你不想乱用log4j.xml,那么你必须使用log4j API并根据你的唯一id创建自己的appender

Something like this: 像这样的东西:

public class YourClass{
Logger logger = Logger.getLogger(YourClass.class);
SimpleLayout layout = new SimpleLayout();
FileAppender appender = null;

public YourClass() {
    try {
        appender = new FileAppender(layout, "/path/tolog/yourUniqueId.log", false);
        logger.addAppender(appender);

        logger.setLevel((Level) Level.DEBUG);

    }
    catch(IOException e) {
        e.printStackTrace();
        logger.error("Printing ERROR Statements",e);
    }
}

This way each instance of YourClass would write to a different log file. 这样,YourClass的每个实例都会写入不同的日志文件。 all you have to do is think of a way of getting this uniqueId when you call the constructor. 所有你需要做的就是想一下在调用构造函数时获取这个uniqueId的方法。

Hope it help. 希望它有所帮助。

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

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