Blog

Sitecore things

Sitecore best practices, architectures, EXM, SPEAK...

Forward Sitecore logs to NLog

In my current project, I need to use an in-house logging system that was built on NLog in the Sitecore project.

Since Sitecore uses log4net for logging and we don’t want to replace all of it with another logging system, the easiest way would be to create a custom log4net appender that can forward the log messages to another logger.

Firstly, let’s define the NLog loggers in NLog.config file. In the following example, I defined 6 loggers that each of them maps to a log4net logger in Sitecore. I was using NLog 4.1, so I was able to use JSON as the log file format.

Then I created an appender that inherited from log4net.Appender.AppenderSkeleton. It overrode the Append method. What it does is:

  • Finding the correct NLog logger based on the log4ne logger name in the log4net.spi.LogEventInfo.
  • Converting the LogEventInfo from log4net to NLog
  • Writing the converted LogEventInfo by using the NLog logger.

Last step was to define this appender in the < log4net> section in the Web.config file.

Now we are able to append this NLogAppender to any section that we want the log message be forwarded to Nlog. In this example, I put it to all the Sitecore loggers. By doing this, besides the default Sitecore log files, we also get the log files generated by NLog.