Home
Manage Your Code
Snippet: log4net usage (C#)
Title: log4net usage Language: C#
Description: from: http://haacked.com/archive/2005/03/07/ConfiguringLog4NetForWebApplications.aspx Views: 530
Author: kyong kwak Date Added: 11/7/2007
Copy Code  
1////////////////////////////// TWO WAYS TO INITIALIZE //////////////////////////////

2
3// make sure assemblyinfo.cs is located under /App_Code for websites 

4[assembly: log4net.Config.XmlConfigurator( ConfigFile="Log4Net.config",Watch=true )]
5
6// Global.asax | Application_Start()

7string path = HttpRuntime.AppDomainAppPath;
8System.IO.FileInfo l_LogFile = new System.IO.FileInfo( path + "log4net.config" );
9//set configuraration - allow changes in the .config during runtime

10log4net.Config.XmlConfigurator.ConfigureAndWatch( l_LogFile );
11
12///////////////////////// USAGE: Global.asax | Application_Error() /////////////////////////

13
14// GetLastError() is the "Unhandled Exception" exception, which isn't helpful at all..

15Exception l_lastException = Server.GetLastError();
16
17// DO NOT SWAP OUT FOR STRINGBUILDER. This is faster as it is just one string ( compiler does that )

18string l_format = "Application_Error " + Environment.NewLine + Environment.NewLine
19                + "Source: {0}" + Environment.NewLine
20                + "-------------------------------- Full Exception Trace --------------------------------" 
21                + Environment.NewLine;
22
23// DO NOT SWAP OUT FOR STRINGBUILDER. This is faster as it is just one string ( compiler does that )

24string l_subFormat = "Message: {0}" + Environment.NewLine
25                   + "Stack Trace: " + Environment.NewLine
26                   + "{1}" + Environment.NewLine + Environment.NewLine;
27
28StringBuilder l_exceptionTrace = new StringBuilder();
29l_exceptionTrace.Append(string.Format(l_format, l_lastException.Source));
30
31// List the whole exception hierarchy

32do
33{
34    l_exceptionTrace.Append( string.Format(l_subFormat, l_lastException.Message, l_lastException.StackTrace));
35    l_lastException = l_lastException.InnerException;
36}
37while( l_lastException != null );
38
39m_log.Fatal( l_exceptionTrace.ToString() );
40// http://support.microsoft.com/kb/306355

41// Server.ClearError(); // if this is handled ( i.e. not commented out ) we must redirect to an Error page.

42// Since we don't, we can have web.config handle the redirection.
Usage
// for each class
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);