Friday, December 30, 2022

How to create custom logger in Sitecore application?

 By default, Sitecore creates its own log files and puts all the information together. Sometimes you may require a special log where the entries would be specific to your features/functionality. 

This blog will help you to create your own custom logger in the Sitecore application. Please follow the steps to create the custom logger.

Step 1: Create class 'Log.cs'- it includes the set of required methods.

using System.Web;

using Sitecore.Security.Authentication;

namespace XYZ.Foundation.Logging.Log

{

    public class Log

    {

        private readonly string loggerName;

        public Log(string logName)

        {

            loggerName = logName;

        }


        /// <summary>

        /// Debug with message

        /// </summary>

        /// <param name="message">message text</param>

        public void Debug(string message)

        {

            if (Sitecore.Diagnostics.Log.IsDebugEnabled)

            {

                Sitecore.Diagnostics.Log.Debug(FormattedLogMessage(message), loggerName);

            }

        }

        /// <summary>

        /// Writes info message

        /// </summary>

        /// <param name="message">message</param>

        public void Info(string message)

        {

            Sitecore.Diagnostics.Log.Info(FormattedLogMessage(message), loggerName);

        }


        /// <summary>

        /// Information with the Message text and exception

        /// </summary>

        /// <param name="message">Message text</param>

        /// <param name="exception">Exception</param>

        public void Info(string message, System.Exception exception)

        {

            Sitecore.Diagnostics.Log.Info(FormattedLogMessage(message), loggerName);

        }


        /// <summary>

        /// Warning with message

        /// </summary>

        /// <param name="message">message text</param>

        public void Warn(string message)

        {

            Sitecore.Diagnostics.Log.Warn(FormattedLogMessage(message), loggerName);

        }


        /// <summary>

        /// Error with the Message text

        /// </summary>

        /// <param name="message">Message text</param>

        public void Error(string message)

        {

            Sitecore.Diagnostics.Log.Error(FormattedLogMessage(message), null, loggerName);

        }

        /// <summary>

        /// Error with the Message text and exception

        /// </summary>

        /// <param name="message">Message text</param>

        /// <param name="exception">Exception</param>

        public void Error(string message, System.Exception exception)

        {

            Sitecore.Diagnostics.Log.Error(FormattedLogMessage(message), exception, loggerName);

        }


        string FormattedLogMessage(string message)

        {

            var userName = HttpContext.Current?.User?.Identity != null && HttpContext.Current.User.Identity.IsAuthenticated ?

                AuthenticationManager.GetAuthenticationData("fullname") :

                "Anonymous";

            var sessionId = HttpContext.Current?.Request?.Cookies != null ?

                HttpContext.Current.Request.Cookies.Get("ASP.NET_SessionId")?.Value :

                "NotFound";


            return $"USER : {userName} - Session :{sessionId} - MESSAGE - {message}";

        }

    }

}


Step 2: Create class 'Logger.cs'- it instantiates the Log object by specifying the logger name.

using System.Linq;

namespace XYZ.Foundation.Logging.Log
{
    public static class Logger
    {
        public static Log ABCLog => new Log("ABC.Logs");
    }
}


Step 3: Create a patch config file.

<?xml version="1.0"?>
<configuration>
	<sitecore>
		<log4net>
			<root>
				<priority value="INFO" />
				<appender-ref ref="LogFileAppender" />
			</root>

			<appender name="ABCLogFileAppender" type="log4net.Appender.SitecoreLogFileAppender, Sitecore.Logging">
				<file value="$(dataFolder)/logs/ABC_LogFile.{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="ABC.Logs" additivity="false">
				<level value="INFO"/>
				<appender-ref ref="ABCLogFileAppender"/>
			</logger>
		</log4net>

	</sitecore>
</configuration>




No comments:

Post a Comment

How to Create a Public Link Using the Sitecore Content Hub REST API

Creating a public link using the Sitecore Content Hub REST API is a straightforward process that enables you to share content externally whi...