Wednesday, January 4, 2017

Sitecore Custom Logs

Hi All,

Sometimes we need a custom logger that report the error or some information about the flow of our Sitecore.
By using that we can found where we lack our flow. At first, we have many ways to do that.
But I only focus on 2 that are below:
1. By using Sitecore Log class of Sitecore.Diagnostics.
ex: Log.Error("message", exception, "logger name");
ex: Log.Error("CustomError", model.Exception, "CustomError.Intranet");
2. By using Log4net.
For that, you have to add log4net node in config. we can implement by adding in web config or add custom config recommended is add custom path like CustomError.config under include folder.
That have the code as:

<?xml version="1.0"?>
<configuration>
  <sitecore>
    <settings>
      <setting name="" value="" />
         </settings>
    <log4net>
      <appender name="IntranetIntegrationLogFileAppender" type="log4net.Appender.SitecoreLogFileAppender, Sitecore.Logging">
        <file value="$(customLogFolder)/logs/Extranet.log.{date}.txt" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%4t %d{ABSOLUTE} %-5p %m%n" />
        </layout>
        <encoding value="utf-8" />
      </appender>
      <logger name="CustomError.Intranet" additivity="false">
        <level value="INFO" />
        <appender-ref ref="IntranetIntegrationLogFileAppender" />
      </logger>
    </log4net>
  </sitecore>
  <system.web>

  </system.web>
</configuration>

Now you can use this in anywhere in a project like in code file you have to use this as below:

ex: Here model.Exception is a variable which I use in my code you can change according to your code.
              ILog _serviceLog;
            _serviceLog = LogManager.GetLogger("CustomError.Intranet");
            _serviceLog.Info("-- Start Intraner Custom error logger-- ");
            _serviceLog.Error("-- Error Message, " + model.Exception.Message + " -- ");
            _serviceLog.Error("-- Error , " + model.Exception + " -- ");
            _serviceLog.Info("-- End Intraner Custom error logger-- ");

When you look into your Website root folder you found $(customLogFolder)/logs
under this folder, you found your custom logs but unfortunately this is the blank log.
I investigate more and I found a solution from below reference:
https://blog.horizontalintegration.com/2015/10/02/empty-sitecore-custom-log-files/

Add reference of Sitecore.Logging.dll instead of log4net.dll directly

Now I get my custom log.

References:
https://blog.horizontalintegration.com/2015/10/02/empty-sitecore-custom-log-files/
http://firebreaksice.com/write-to-a-custom-sitecore-log-with-log4net/
http://sitecoreblog.blogspot.in/2011/05/write-you-messages-in-separated-file.html

Enjoy :)

No comments:

Post a Comment