Popular Posts

Sunday, March 27, 2016

Wrapper around NLog for DI

Using NLog with Dependency Injection | Tony Sneed's Blog



Example:



Log File:



<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile=".\nlog-internal.log" >
 
 
  <!-- optional, add some variabeles
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <!--<variable name="myvar" value="myvalue"/>-->
 
  <!-- 
  See https://github.com/nlog/nlog/wiki/Configuration-file 
  for information on customizing logging rules and outputs.
   -->
  <targets>
 
    <!-- 
    add your targets here 
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->
 
    
    <target xsi:type="File" name="file" fileName="${basedir}/logs/${shortdate}.log"
            layout="Server-Date: ${longdate}; Level: ${level}; Log-Message: ${message}; Error-Source: ${event-context:item=error-source}; Error-Class: ${event-context:item=error-class}; Error-Method: ${event-context:item=error-method}; Error-Message: ${event-context:item=error-message}; Inner-Error-Message: ${event-context:item=inner-error-message}" 
            />
 
     <!--Log to Sentinel logger--> 
    <target xsi:type="NLogViewer" name="Sentinel" address="udp://127.0.0.1:9999"
            layout="Server-Date: ${longdate}; Level: ${level}; Log-Message: ${message}; Error-Source: ${event-context:item=error-source}; Error-Class: ${event-context:item=error-class}; Error-Method: ${event-context:item=error-method}; Error-Message: ${event-context:item=error-message}; Inner-Error-Message: ${event-context:item=inner-error-message}" 
            />
    
  </targets>
 
  <rules>
    <!-- add your logging rules here -->
 
    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    -->
    <logger name="*" minlevel="Debug" writeTo="file" />
    <logger name="*" minlevel="Debug" writeTo="Sentinel" />
 
  </rules>
</nlog>


Nlogger class:


using System;
using System.Diagnostics;
using System.Globalization;
using NLog;
 
namespace WatchAndAct
{
    public interface ILoggingService
    {
        void Debug(Exception exception);
        void Debug(string format, params object[] args);
        void Debug(Exception exception, string format, params object[] args);
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming""CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
        void Error(Exception exception);
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming""CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
        void Error(string format, params object[] args);
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming""CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Error")]
        void Error(Exception exception, string format, params object[] args);
        void Fatal(Exception exception);
        void Fatal(string format, params object[] args);
        void Fatal(Exception exception, string format, params object[] args);
        void Info(Exception exception);
        void Info(string format, params object[] args);
        void Info(Exception exception, string format, params object[] args);
        void Info(string info);
        void Trace(Exception exception);
        void Trace(string format, params object[] args);
        void Trace(Exception exception, string format, params object[] args);
        void Warn(Exception exception);
        void Warn(string format, params object[] args);
        void Warn(Exception exception, string format, params object[] args);
    }
 
    public class LoggingService : ILoggingService
    {
        private const string LoggerName = "NLogLogger";
        private static readonly Logger logger;
 
        static LoggingService()
        {
            logger = GetLogger();
        }
 
        public static Logger GetLogger()
        {
            var log = LogManager.GetLogger("NLogLogger"typeof(LoggingService));
            return log;
        }
 
        public void Debug(string format, params object[] args)
        {
            this.Debug(null, format, args);
        }
 
        public void Debug(Exception exception, string format, params object[] args)
        {
            if (!logger.IsDebugEnabled) return;
            var logEvent = GetLogEvent(LoggerName, LogLevel.Debug, exception, format, args);
            logger.Log(typeof(LoggingService), logEvent);
        }
 
        public void Error(string format, params object[] args)
        {
            this.Error(null, format, args);
        }
 
        public void Error(Exception exception, string format, params object[] args)
        {
            if (!logger.IsErrorEnabled) return;
            var logEvent = GetLogEvent(LoggerName, LogLevel.Error, exception, format, args);
            logger.Log(typeof(LoggingService), logEvent);
        }
 
        public void Fatal(string format, params object[] args)
        {
            this.Fatal(null, format, args);
        }
 
        public void Fatal(Exception exception, string format, params object[] args)
        {
            if (!logger.IsFatalEnabled) return;
            var logEvent = GetLogEvent(LoggerName, LogLevel.Fatal, exception, format, args);
            logger.Log(typeof(LoggingService), logEvent);
        }
 
        public void Info(string format, params object[] args)
        {
            this.Info(null, format, args);
        }
 
        public void Info(Exception exception, string format, params object[] args)
        {
            if (!logger.IsInfoEnabled) return;
            var logEvent = GetLogEvent(LoggerName, LogLevel.Info, exception, format, args);
            logger.Log(typeof(LoggingService), logEvent);
        }
 
        public void Info(string info)
        {
            logger.Info(info);
        }
 
        public void Trace(string format, params object[] args)
        {
            this.Trace(null, format, args);
        }
 
        public void Trace(Exception exception, string format, params object[] args)
        {
            if (!logger.IsTraceEnabled) return;
            var logEvent = GetLogEvent(LoggerName, LogLevel.Trace, exception, format, args);
            logger.Log(typeof(LoggingService), logEvent);
        }
 
        public void Warn(string format, params object[] args)
        {
            this.Warn(null, format, args);
        }
 
        public void Warn(Exception exception, string format, params object[] args)
        {
            if (!logger.IsWarnEnabled) return;
            var logEvent = GetLogEvent(LoggerName, LogLevel.Warn, exception, format, args);
            logger.Log(typeof(LoggingService), logEvent);
        }
 
        public void Debug(Exception exception)
        {
            this.Debug(exception, string.Empty);
        }
 
        public void Error(Exception exception)
        {
            this.Error(exception, string.Empty);
        }
 
        public void Fatal(Exception exception)
        {
            this.Fatal(exception, string.Empty);
        }
 
        public void Info(Exception exception)
        {
            this.Info(exception, string.Empty);
        }
 
        public void Trace(Exception exception)
        {
            this.Trace(exception, string.Empty);
        }
 
        public void Warn(Exception exception)
        {
            this.Warn(exception, string.Empty);
        }
 
        private LogEventInfo GetLogEvent(string loggerName, LogLevel level, Exception exception, string format, object[] args)
        {
            string assemblyProp = string.Empty;
            string classProp = string.Empty;
            string methodProp = string.Empty;
            string messageProp = string.Empty;
            string innerMessageProp = string.Empty;
 
            var logEvent = new LogEventInfo
                (level, loggerName, string.Format(CultureInfo.InvariantCulture, format, args));
 
            if (exception != null)
            {
                var targetSite = exception.TargetSite;
                if (targetSite != null)
                {
                    if (targetSite.DeclaringType != null)
                        classProp = targetSite.DeclaringType.FullName;
                    methodProp = targetSite.Name;
                }
 
                messageProp = exception.Message;
                assemblyProp = exception.Source;
                logEvent.Message = messageProp;
                logEvent.Exception = exception;
 
                if (exception.InnerException != null)
                {
                    innerMessageProp = exception.InnerException.Message;
                }
            }
 
            logEvent.Properties["error-source"] = assemblyProp;
            logEvent.Properties["error-class"] = classProp;
            logEvent.Properties["error-method"] = methodProp;
            logEvent.Properties["error-message"] = messageProp;
            logEvent.Properties["inner-error-message"] = innerMessageProp;
 
            return logEvent;
        }
    }
 
}

No comments:

Post a Comment