开发者

Log4net - log parts of code, used in a couple of methods

开发者 https://www.devze.com 2022-12-14 11:47 出处:网络
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 deter

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 a开发者_运维问答nd 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消