开发者

Log4J dynamic configuration

Is there any way to configure log4j loggers dynamically. I want each insta开发者_开发百科nce 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.

Is there any way to do this using log4j?


Ok, from your comment, here what i would try.

I imagine you will create your 10 instances at the start of your app.!? anyway.

In your log4j.xml, define 10 appender with name = yourUniqueId (this unique id will be sort of hard coded)

Make these appender write to 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.

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

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. all you have to do is think of a way of getting this uniqueId when you call the constructor.

Hope it help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜