Log4Net Configuration

Configs\Logging.Config

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <root>
    <level value="ALL" />
    <appender-ref ref="File" />
    <appender-ref ref="TraceAppender" />
    <!--
    <appender-ref ref="Splunk" />
    <appender-ref ref="Email" />
    <appender-ref ref="TraceAppender" />
    -->
  </root>

  <appender name="File" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="%property{LogName}" />
    <param name="AppendToFile" value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <maximumFileSize value="1000KB" />
    <maxSizeRollBackups value="20" />
    <rollingStyle value="Size" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="ENVIRONMENT=DEV APPLICATION=%P{Application} DATE=&quot;%d{dd MMM yyyy HH:mm:ss.fff}&quot; %ndc THREAD=%t LOGLEVEL=%-5p LOGGER=%logger.%M() MESSAGEID=%X{MESSAGE_ID} SessionID=[%aspnet-request{ASP.NET_SessionId}] KEYVALUES=%X{KEY_VALUES} REFERRER=%property{HttpReferer} URL=%property{Url} LOGMSG=%m%n" />
    </layout>
  </appender>

  <appender name="Splunk" type="log4net.Appender.RemoteSyslogAppender">
    <filter type="log4net.Filter.LevelRangeFilter">
      <levelMax value="FATAL" />
      <levelMin value="INFO" />
    </filter>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="ENVIRONMENT=DEV APPLICATION=%P{Application} DATE=&quot;%d{dd MMM yyyy HH:mm:ss.fff}&quot; %ndc THREAD=%t LOGLEVEL=%-5p LOGGER=%logger.%M() MESSAGEID=%X{MESSAGE_ID} SessionID=[%aspnet-request{ASP.NET_SessionId}] KEYVALUES=%X{KEY_VALUES} REFERRER=%property{HttpReferer} URL=%property{Url} LOGMSG=%m%n" />
    </layout>
    <remoteAddress value="SPLUNKSERVER.COM" />
    <remotePort value="9514" />
  </appender>

  <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="ENVIRONMENT=DEV APPLICATION=%P{Application} DATE=&quot;%d{dd MMM yyyy HH:mm:ss.fff}&quot; %ndc THREAD=%t LOGLEVEL=%-5p LOGGER=%logger.%M() MESSAGEID=%X{MESSAGE_ID} SessionID=[%aspnet-request{ASP.NET_SessionId}] KEYVALUES=%X{KEY_VALUES} REFERRER=%property{HttpReferer} URL=%property{Url} LOGMSG=%m%n" />
    </layout>
  </appender>

  <appender name="Email" type="log4net.Appender.SmtpAppender,log4net">
    <Authentication value="Basic" />
    <bufferSize value="50" />
    <evaluator type="log4net.Core.LevelEvaluator,log4net">
      <threshold value="WARN" />
    </evaluator>
    <filter type="log4net.Filter.LevelRangeFilter">
      <levelMax value="FATAL" />
      <levelMin value="WARN" />
    </filter>
    <from value="Error@YOURDOMAIN.COM" />
    <layout type="log4net.Layout.PatternLayout,log4net">
      <conversionPattern value="ENVIRONMENT=DEV APPLICATION=%P{Application} DATE=&quot;%d{dd MMM yyyy HH:mm:ss.fff}&quot; %ndc [THREAD=%t] LOGLEVEL=%-5p LOGGER=%logger.%M() MESSAGEID=%X{MESSAGE_ID} KEYVALUES=%X{KEY_VALUES} REFERRER=%property{HttpReferer} URL=%property{Url} LOGMSG=%m%n" />
    </layout>
    <lossy value="true" />
    <Port value="25" />
    <smtpHost value="SMTPSERVERNAME" />
    <subject value="Error on DEV" />
    <to value="YOUREMAIL.COM" />
  </appender>




</log4net>

ConsoleApp

App.config
<appSettings>
<add key="LogPath" value="C:\Applications\"/>
</appSettings>

AssemblyInfo.cs

// Log4net config file
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Configs\\logging.config", Watch = true)]

Program.cs

public static ILog Log;
Main()
{
	 // Set logfile name and application name variables
 GlobalContext.Properties["LogName"] = string.Format("{0}{1}", ConfigurationManager.AppSettings["LogPath"],
                                                                Assembly.GetExecutingAssembly().GetName().Name + ".log");
 
 GlobalContext.Properties["Application"] = Assembly.GetExecutingAssembly().GetName().Name;
 Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); //Instantiate the logger
 Log.Info("Starting the application..");
		
	}

WEB

AssemblyInfo.cs

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Configs/logging.config", Watch = true)]

Global.asax.cs

using log4net;
public static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected void Application_BeginRequest()
{
    HttpContext context = HttpContext.Current;
    string messageId = Guid.NewGuid().ToString();
    IDisposable loggingToken = log4net.NDC.Push("reqid=" + messageId);
    HttpContext.Current.Items["loggingToken"] = loggingToken;
 } 
//pushing a newly created request id onto the NDC Stack, to be disposed at the end of the request
 
protected void  Application_PostAcquireRequestState(object sender, EventArgs e)
{
    bool requiresSessionState = HttpContext.Current.CurrentHandler is System.Web.SessionState.IRequiresSessionState;
	if (requiresSessionState)
	{
		try
		{
			string sessionId = Session.SessionID;
			Response.AppendToLog("&Sid=" + sessionId); //add sessionid to iis log files
			IDisposable loggingToken = log4net.NDC.Push("sessid=" + sessionId);
			HttpContext.Current.Items["sessionLoggingToken"] = loggingToken;
			
			//add properties for log4net
			ThreadContext.Properties["Url"] = HttpContext.Current.Request.Url.ToString();
			ThreadContext.Properties["HttpReferer"] = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
			
			if (Log.IsDebugEnabled)
			Log.DebugFormat("Page Hit.\r\n");
		
		}
	catch (Exception ex)
	{
	
	Log.Error("Failed to acquire SessionID. This Exception is not critical, thus it will be ignored for now.", ex);
	}
    }
} //acquiring the Session ID and pushing it onto the NDC Stack, to be disposed at the end of the request

protected void Application_EndRequest(object sender, EventArgs e)
{
	try
	{
		foreach (object item in HttpContext.Current.Items.Values)
		{
		IDisposable d = item as IDisposable;
		if (d != null)
		d.Dispose();
		}
	}
	catch (Exception ex)
	{
		Log.Error("An unexpected Exception occurred, but it will be ignored", ex);
	}
} //here we’re just cleaning up the NDC by disposing all the logging tokens
 
protected void Application_Start()
{
	log4net.GlobalContext.Properties["Application"] = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
	Log.Info("Starting the application..");
}

DEBUG:

<!--<add key="log4net.Config" value="Configs\logging.config"/>
<add key="log4net.Config.Watch" value="True"/>
<add key="log4net.Internal.Debug" value="true"/>-->

<!--<system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add
          name="textWriterTraceListener"
          type="System.Diagnostics.TextWriterTraceListener"
          initializeData="C:\temp\log4net.txt" />
      </listeners>
    </trace>
  </system.diagnostics>-->