Less
Less

Reputation: 3207

Logging from base and extended classes with log4j?

I'm using slf4j with log4j and I have the following situation:

package x.y.z.base;
public class FTPOperationsBase {

    private final Logger log = LoggerFactory.getLogger(FTPOperationsBase.class);
    protected FTPClient ftp;
    // some more fields

    public void connect() {
        ...
        // log all connect exceptions
    }
    public void disconnect() {
        ...
        // log all disconnect exceptions
    };
}

As it can be seen, package is x.y.z.base. Now I have several classes which extend this base class (these classes are currently in packages x.y.z.classA, x.y.z.clasB,... etc).

I want separate log file for each of these classes, as they act as separate modules. But what I also want is to somehow put log from base class to these separate logs, depending on which class is being used, that is I don't want log form base class in all logs if only one subclass is executing. For example, if I have extended class:

public class FTPExtendedClass1 
extends FTPOperationsBase {
    public void doSomething() {...}
}

and make the following code sequence:

FTPExtendedClass1 obj1 = new FTPExtendedClass1();
obj1.connect();
obj1.doSomething();
obj1.disconnect();

I'd like to have the log file for this case as follows:

This should be the case for all extended classes, where doSomething() is class-specific method. Any way to organize packages / configure log4j for this behavior ?

Thanks.

Upvotes: 1

Views: 3718

Answers (1)

Cygnusx1
Cygnusx1

Reputation: 5409

You have to create different Appender in your log4j.xml.

One for each different class.

<logger name="yourBaseClassName" additivity="false">
    <level value="INFO" />
    <appender-ref ref="BasefileAppender" />
</logger>

<appender name="BasefileAppender" 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>

<logger name="yourExtendedClassName" additivity="false">
    <level value="INFO" />
    <appender-ref ref="ExtendOnefileAppender" />
</logger>

<appender name="ExtendOnefileAppender" class="org.apache.log4j.FileAppender">
<param name="File" value="/path/ExtendOnefileAppender.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 each of your class (Base and extended) you do:

Logger mylogger = Logger.getLogger(MyClass.class.getName())

I don't think it cover your second requirement (But what I also want is to somehow put log from base class to these separate logs, depending on which class is being used)

but its a start... ;-) with this you should be able to log in different file based on the name of the class.

Hope it help

Upvotes: 2

Related Questions