Sometimes it is difficult to troubleshoot errors in Sitecore’s standard log file due to the lack of some key pieces of information… namely: context user, context item id and the raw requested url. However, since Sitecore uses Log4Net, we can easily inject this information into our log entries. Alex Shyba has a great post that details exactly how to get this information into your logs… IF you are logging to a SQL database that is.
In my case, I wanted to just add this information into the existing (default) LogFileAppender. To do this, I extended Sitecore’s “SitecoreLogFileAppender” class as follows:
public class SitecoreLogFileAppenderEx : log4net.Appender.SitecoreLogFileAppender
{
protected override void Append(LoggingEvent loggingEvent)
{
var properties = loggingEvent.Properties;
properties["scuser"] = string.Empty;
properties["scitemid"] = string.Empty;
properties["rawurl"] = string.Empty;
// Only log ERRORS or higher level events
if (Sitecore.Context.Site != null && loggingEvent.Level >= Level.ERROR)
{
if (Sitecore.Context.User != null)
try { properties["scuser"] = Sitecore.Context.User.Name; }
catch { }
if (Sitecore.Context.Item != null)
try { properties["scitemid"] = Sitecore.Context.Item.ID.ToString(); }
catch { }
try { properties["rawurl"] = Sitecore.Web.WebUtil.GetServerUrl() + Sitecore.Web.WebUtil.GetRawUrl(); }
catch { }
}
base.Append(loggingEvent);
}
}
Then i modified the web.config log4net configuration to use my appender and added the custom properties to the PatternLayout as follows.:
<appender name="LogFileAppender" type="log4net.Appender.SitecoreLogFileAppenderEx, Sitecore.Drexel.Logging">
<file value="$(dataFolder)/logs/log.{date}.txt"/>
<appendToFile value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%4t %d{ABSOLUTE} %-5p %c [%P{scuser} %P{scitemid} %P{rawurl}] %m%n"/>
</layout>
</appender>
It is important to note that when specifying the parameters in the PatternLayout, you must use a capital “P”.