views:

51

answers:

2

Hi, Currently i am working on log4j stuff for my application. I have a specific requirement of logging. I need to define a logger for a specific call hierarchy. Meaning all the log messages of a specific call hierarchy should go to a specific appeneder.

Example

AddFormAction(method1) ---|--- FormBusinessObject(method4) --|-- FormDAOObject(method5)

EditFormAction(method2) -----|---- FormBusinessObject(method4) --|-- FormDAOObject(method5)

DeleteFormAction(method3)----|--- FormBusinessObject(method4) --|-- FormDAOObject(method5)

I want to define a logger for a specific call hierarchy 1 - 4 -5. These messages should goto addform.log.

I don't want the messages from 2-4-5 or 3-4-5 call hierarchies to go to addform.log.

Hope iam clear on my requirement. Any help is highly appreciated. Thanks all in advance for your replies.

A: 

I don´t know that much about log4j, but this sounds like a perfect case for AspectJ.

Eyvind
A: 

One method would be to use injection to give the dependencies their logger instance.

 public bool addFormAction( .... form data .... ) {
     Logger logger = LogManager.getLogger( "AddFormLogger" );
     FormBusinessObject form = new FormBusinessObject( logger );
     form.setProperty1( parameter1 );
     form.save();
 }

...

 public class FormBusinessObject
 {
      private Logger logger;

      public FormBusinessObject() {
          logger = LogManager.GetLogger( "DefaultLogger" );
      }

      public FormBusinessObject( Logger logger ) {
          logger = logger;
      }

      ...

      public void save() {
           logger.info( "Saving form" );
           ...
      }
}
tvanfosson
Thanks for your reply, but iam injecting the businessobjects through spring so i can't instantiate manually the BO Objects. Any other way to achieve this using Log4j.
Venkata Sirish
I'm not sure. Essentially, what you'd need to do is somehow set a global context that would allow you to use a factory of some sort inside your business and DAO objects to obtain the proper logger. The factory could be injected with Spring. I'd be tempted to use a singleton context that the factory could just access and return the proper logger. This would really only work if the application is single-threaded or if the singleton kept track of the context per thread.
tvanfosson
FWIW, everyone I've talked to does logger/class not logger/activity. Usually, I simply rely on the stack trace to give me the context if I need to know what activity I'm performing.
tvanfosson