views:

179

answers:

2

Consider this scenario:

I have a project with two modules and one common module as below (the package structure):

com.mysite.moduleone
com.mysite.moduletwo
com.mysite.commonmodule

In the above, the commonmodule classes can be used by other two modules.

The question:

I need to configureLog4J such a way that the log messages from moduleone and moduletwo goes to different log file. I can always do this using using category.

But the real problem is when I want to log the messages from the commonmodule also. So, when the commonmodule classes are called from moduleone the commonmodule log messages should go to the moduleone log file. If the commonmodule is accesse from moduletwo the commonmodule log messages should go to moduletwo log file.

Is it possible to configure Log4J in this fashion? Any comments?

PS: I think I made my question clear. If any confusion, leave a comment, wil try to clear it. :)

A: 

Is it possible to configure Log4J in this fashion?

In short, it is not with log4j unless you write a custom filter. And that filter would need to capture and analyse the call stack for each log event that makes it to each log appender ... which would be expensive.

Stephen C
A: 

I'm in agreement with @Stephen C about not being able to do so with Log4j without an expensive custom logger.

Another similar logging framework called Logback supports two options which may be enough to remove the need for a custom appender. They are called MDC (Mapped Diagnostic Contexts) and Markers.

Markers provide a way to add a custom piece of information to a logging statement, and you could (depending on how the common package is used) pass in a Marker to use depending on which module is using it.

MDCs could be used by setting them just before going into code in the common module and then unsetting them when leaving.

It also has a filter which can filter by appender on either.

deterb