How to enable custom logger in Sitecore
Below are the steps to enable a custom logger:
1. Install Sitecore.Logging assembly in Project form Nuget Package manager. Please select Dependency Behavior as Ignore Dependencies.
Create CustomLogger.config file in AppSetting/Include/Project folder with below content.You can change log folder and log file name by changing value in config file .
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<log4net>
<logger name="CustomLogger" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="CustomLogFile"/>
</logger>
<appender name="CustomLogFile">
<patch:attribute name="type">log4net.Appender.SitecoreLogFileAppender, Sitecore.Logging</patch:attribute>
<file>
<patch:attribute name="value">$(dataFolder)/logs/CustomLog/Custom.Log.{date}.txt</patch:attribute>
</file>
<encoding value="utf-8" />
<staticLogFileName value="false"/>
<datePattern value="_yyyyMMdd" />
<rollingStyle value="Date" />
<!--<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />-->
<appendToFile value="true" />
<preserveLogFileNameExtension value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d (%-5p) %n%m%n%n" />
</layout>
</appender>
</log4net>
</sitecore>
</configuration>
Create log helper class with below code:
LogHelper.cs
using log4net;
namespace Sitecore.Demo.Web.Helper
{
public class LogHelper
{
public static readonly ILog Logger = LogManager.GetLogger("CustomLogger");
}
}
The custom logger is ready to use, below is a sample implementation:
AboutController.cs
using Sitecore.Demo.Web.Helper;
using Sitecore.Demo.Web.Models;
using Sitecore.Mvc.Presentation;
using System;
using System.Web.Mvc;
namespace Sitecore.Demo.Web.Controllers
{
public class AboutController : Controller
{
public ActionResult Index()
{
//1. Pass the Item to the view
var model = new AboutViewModel()
{
Item = RenderingContext.Current?.Rendering.Item
};
//Error Logger
LogHelper.Logger.Error("Error Log: AboutController: Index method " + DateTime.Now.ToString());
//Info Logger
LogHelper.Logger.Info("Info Log: AboutController: Index method " + DateTime.Now.ToString());
return View(model);
}
}
}
Below is log generated by above process:
The benefit of enabling a custom logger is that we can create separate log folders as per our requirements.
Comments
Post a Comment