Skip to content

Instantly share code, notes, and snippets.

@akatakritos
Created October 26, 2017 15:36
Show Gist options
  • Save akatakritos/a78f065a77ace92dcbf06ec5818c43ae to your computer and use it in GitHub Desktop.
Save akatakritos/a78f065a77ace92dcbf06ec5818c43ae to your computer and use it in GitHub Desktop.
Log4Net Config
protected void Application_Start()
{
log4net.Config.XmlConfigurator.Configure();
log4net.GlobalContext.Properties["userid"] = new Log4NetUserIdResolver();
}
internal sealed class Log4NetUserIdResolver
{
public override string ToString()
{
var userId = (HttpContext.Current?.User as WhateverPrincipal)?.AccountId;
return userId ?? "none";
}
}
<!-- all the way at the top, just inside the configuration node. The section has to be defined before the parser
encounters the log4net node -->
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections
<!-- this can be somewhere down below appSettings -->
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<!-- logs to App_Data/logs/log.txt, but stores a copy and restarts the file every day -->
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value=".\\App_Data\\logs\\log.txt" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value=".yyyyMMdd.txt" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<!-- line layout includes the property{userid} to get from GlobalContext. See Global.asax.cs -->
<conversionPattern value="%date %-5level &lt;%-7property{userid}&gt; %-30logger - %message%newline" />
</layout>
</appender>
</log4net>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment