Cratylus
Cratylus

Reputation: 54074

java log4j choose which file to log to

I need to log debugging messages from the same class into different files.
What I mean is that from the same class I need a specific debug statement to go to fileA while another specific debug statement to go to fileB.

In case it is not clear, what I am trying to do is to log network messages to a completely separate file than other loggin messages that this class outputs.

If I do

<logger name="com.test.modules" additivity="false" >
    <priority value="debug"/>
    <appender-ref ref="netWorkCommunication"/>  
    <appender-ref ref="generalDebug"/>  
  </logger>  

Then the logging from my class will go to both files (since it is from the same package).

How can I configure log4j so that I can select which logging statement from classes under com.test.modules go to which file appender?

Upvotes: 5

Views: 1471

Answers (2)

Gustav Karlsson
Gustav Karlsson

Reputation: 1221

This really looks a scenario where multiple loggers should be used. Configure a separate logger for networking and just specify a different appender for it.

Upvotes: 2

jalopaba
jalopaba

Reputation: 8119

Use a separate Logger for each file:

private static Logger log = Logger.getLogger(YourClass.class);
private static Logger networkLog = Logger.getLogger("network." + YourClass.class.getName());
private static Logger httpLog = Logger.getLogger("http." + YourClass.class.getName());

and define the appender for each Logger as usual.

Upvotes: 7

Related Questions