Programming Languages Hacks

Importanti regole per linguaggi di programmazione rilevanti come Java, C, C++, C#…

  • Subscribe

  • Lettori

    I miei lettori abituali

  • Twitter

Archive for November, 2013

Log4Net Custom Properties

Posted by Ricibald on 8th November 2013

Log4Net Log Custom Properties

From Tim Lewis’s answer on stackoverflow:

Since ASP.NET does not guarantee that the entire page request will be processed on the same thread, I prefer getting the answer from HttpContext.Current as log4net processes the logging event.

The following GetCurrentPage class implements what the log4net manual calls an “Active Property Value” by overriding its ToString method:

public class GetCurrentPage
  public override string ToString()
      if (null != HttpContext.Current)
          return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;
      return string.Empty; // or "[No Page]" if you prefer

Register this class in Global.asax’s Application_Start in log4net’s GlobalContext.

protected void Application_Start(object sender, EventArgs e)
    GlobalContext.Properties["page"] = new GetCurrentPage();

When log4net writes the %property{page} part of the line it will call the ToString method of our GetCurrentPage class which will lookup the value in the current request.

The same is possible to log the current HttpContext.

Posted in .net | No Comments »