开发者

Extending log4net - Adding additional data to each log

开发者 https://www.devze.com 2023-02-18 14:43 出处:网络
We\'re working on logging in our applications, using log4net.We\'d like to capture certain information automatically with every call.The code calling log.Info or log.Warn should call them normally, wi

We're working on logging in our applications, using log4net. We'd like to capture certain information automatically with every call. The code calling log.Info or log.Warn should call them normally, without specify this information.

I'm looking for a way to create something we can plug into log4net. Something between the ILog applications use to log and the appenders, so that we can put this information into the log message somehow. Either into ThreadContext, or the LogEventInfo.

The information we're looking to capture is asp.net开发者_开发问答 related; the request url, user agent, etc. There's also some information from the apps .config file we want to include (an application id).

I want to get between the normal ILog.Info and appender so that this information is also automatically included for 3rd party libraries which also use log4net (Nhibernate, NServiceBus, etc).

Any suggestions on where the extensibility I want would be?

Thanks


What you are looking for is called log event context. This tutorial explains how it works:

http://www.beefycode.com/post/Log4Net-Tutorial-pt-6-Log-Event-Context.aspx

In particular the chapter 'Calculated Context Values' will interesting for you.

Update:

My idea was to use the global context. It is easy to see how this works for something like application ID (in fact there you do not even need a calculated context object). Dynamic information like request url could be done like this:

public class RequestUrlContext
{
    public override string ToString()
    {
        string url;
        // retrieve url from request
        return url;
    }
}

The object is global but the method is called on the thread that handles the request and thus you get the correct information. I also recommend that you create one class per "information entity" so that you have a lot of flexibility with the output in the log destination.

0

精彩评论

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