views:

58

answers:

2

Hi. I have some trouble. My application could be divided to 3 logical parts (import, processing and export). There are some parts of code which are used in several parts of my application. How can I determine which part of code called my log4net object?

What is best practice to log info in parts of code which are called from several places in the application?

I want to turn on and off the ability to log parts of my application from a config file. If I turn off logging for the processing part of my app, how could I log info in the export part of my app when both of them use one method, in which I initialize my logger object?

A: 

log4net provides contexts for this purpose. I would suggest using a context stack like this:

using(log4net.ThreadContext.Stacks["Part"].Push("Import"))
    log.Info("Message during importing");

using(log4net.ThreadContext.Stacks["Part"].Push("Processing"))
    log.Info("Message during processing");

using(log4net.ThreadContext.Stacks["Part"].Push("Export"))
    log.Info("Message during exporting");

The value on the stack can be shown in the logs by including %property{Part} in a PatternLayout.

GraemeF
I mean next: For example there're PrepareGift() method in my class. Before processing and export data I call this method. In the body of the method I'll write: log.Info("Message during smth."); Then if I'll process my gifts I'll execute PrepareGifts() method and write log. Same with export part in the app. Now I want to log only processing part of the app(could it be switched in config file?) and if there're will be executed export part it shouldn't be logged. Is there're any solution?
Akim Khalilov
A: 

You could add a separate logger for each section of your app that you want to log and then turn them off and on as needed. They would all be independent from one another and this can all be setup via the config.

By setting the additivity property to false, the loggers will all be independent of one another. Here's an example of the config portion:

<logger name="Logger1" additivity="false">
      <level value="INFO" />
      <appender-ref ref="Logger1File" />
</logger>

To use it in your code, reference it like this:

private static ILog _Logger1= LogManager.GetLogger("Logger1");

Anything you log to Logger1 will be separate from any other logger, including the root one.

TskTsk