Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 247
Cratylus Avatar asked Jan 31 '12 09:01

Cratylus


2 Answers

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.

like image 199
jalopaba Avatar answered Oct 12 '22 23:10

jalopaba


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.

like image 30
Gustav Karlsson Avatar answered Oct 13 '22 00:10

Gustav Karlsson