您的位置:9159金沙官网 > 9159金沙官网 > 9159金沙官网ABP .Net Core 日志组件集成使用NLog

9159金沙官网ABP .Net Core 日志组件集成使用NLog

发布时间:2019-10-16 20:54编辑:9159金沙官网浏览(89)

    一、说明

    1. NLog介绍和使用说明官网:http://nlog-project.org/
    2. 9159金沙官网ABP .Net Core 日志组件集成使用NLog。9159金沙官网ABP .Net Core 日志组件集成使用NLog。NLog和Log4net对比:9159金沙官网ABP .Net Core 日志组件集成使用NLog。https://www.cnblogs.com/qinjin/p/5134982.html

    二、NLog集成步骤

    1. 9159金沙官网ABP .Net Core 日志组件集成使用NLog。下载模板项目,下载地址:https://aspnetboilerplate.com/Templates 选择.Net Core项目
    2. 新建一个.NET Standard类库项目Abp.Castle.NLog
      9159金沙官网 1
    3. 添加NuGet包Castle.Core, Castle.LoggingFacility, NLog
      9159金沙官网 2
    4. 参考abp log4net(ABP源码)添加class NLogLogger继承MarshalByRefObject并实现接口Castle.Core.Logging.ILogger

        1 using System;
        2 using System.Globalization;
        3 using ILogger = Castle.Core.Logging.ILogger;
        4 using NLogCore = NLog;
        5 
        6 namespace Abp.Castle.Logging.NLog
        7 {
        8     [Serializable]
        9     public class NLogLogger :
       10         MarshalByRefObject,
       11         ILogger
       12     {
       13         protected internal NLogCore.ILogger Logger { get; set; }
       14         //protected internal NLogLoggerFactory Factory { get; set; }
       15 
       16         public NLogLogger(NLogCore.ILogger logger)
       17         {
       18             Logger = logger;
       19         }
       20 
       21         internal NLogLogger()
       22         {
       23         }
       24 
       25         public bool IsDebugEnabled => Logger.IsEnabled(NLogCore.LogLevel.Debug);
       26 
       27         public bool IsErrorEnabled => Logger.IsEnabled(NLogCore.LogLevel.Error);
       28 
       29         public bool IsFatalEnabled => Logger.IsEnabled(NLogCore.LogLevel.Fatal);
       30 
       31         public bool IsInfoEnabled => Logger.IsEnabled(NLogCore.LogLevel.Info);
       32 
       33         public bool IsWarnEnabled => Logger.IsEnabled(NLogCore.LogLevel.Warn);
       34 
       35         public ILogger CreateChildLogger(string loggerName)
       36         {
       37             return new NLogLogger(NLogCore.LogManager.GetLogger(Logger.Name + "." + loggerName));
       38         }
       39 
       40         public void Debug(string message)
       41         {
       42             Logger.Debug(message);
       43         }
       44 
       45         public void Debug(Func<string> messageFactory)
       46         {
       47             Logger.Debug(messageFactory);
       48         }
       49 
       50         public void Debug(string message, Exception exception)
       51         {
       52             Logger.Debug(exception, message);
       53         }
       54 
       55         public void DebugFormat(string format, params object[] args)
       56         {
       57             Logger.Debug(CultureInfo.InvariantCulture, format, args);
       58         }
       59 
       60         public void DebugFormat(Exception exception, string format, params object[] args)
       61         {
       62             Logger.Debug(exception, CultureInfo.InvariantCulture, format, args);
       63         }
       64 
       65         public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
       66         {
       67             Logger.Debug(formatProvider, format, args);
       68         }
       69 
       70         public void DebugFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
       71         {
       72             Logger.Debug(exception, formatProvider, format, args);
       73         }
       74 
       75         public void Error(string message)
       76         {
       77             Logger.Error(message);
       78         }
       79 
       80         public void Error(Func<string> messageFactory)
       81         {
       82             Logger.Error(messageFactory);
       83         }
       84 
       85         public void Error(string message, Exception exception)
       86         {
       87             Logger.Error(exception, message);
       88         }
       89 
       90         public void ErrorFormat(string format, params object[] args)
       91         {
       92             Logger.Error(CultureInfo.InvariantCulture, format, args);
       93         }
       94 
       95         public void ErrorFormat(Exception exception, string format, params object[] args)
       96         {
       97             Logger.Error(exception, CultureInfo.InvariantCulture, format, args);
       98         }
       99 
      100         public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
      101         {
      102             Logger.Error(formatProvider, format, args);
      103         }
      104 
      105         public void ErrorFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
      106         {
      107             Logger.Error(exception, formatProvider, format, args);
      108         }
      109 
      110         public void Fatal(string message)
      111         {
      112             Logger.Fatal(message);
      113         }
      114 
      115         public void Fatal(Func<string> messageFactory)
      116         {
      117             Logger.Fatal(messageFactory);
      118         }
      119 
      120         public void Fatal(string message, Exception exception)
      121         {
      122             Logger.Fatal(exception, message);
      123         }
      124 
      125         public void FatalFormat(string format, params object[] args)
      126         {
      127             Logger.Fatal(CultureInfo.InvariantCulture, format, args);
      128         }
      129 
      130         public void FatalFormat(Exception exception, string format, params object[] args)
      131         {
      132             Logger.Fatal(exception, CultureInfo.InvariantCulture, format, args);
      133         }
      134 
      135         public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args)
      136         {
      137             Logger.Fatal(formatProvider, format, args);
      138         }
      139 
      140         public void FatalFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
      141         {
      142             Logger.Fatal(exception, formatProvider, format, args);
      143         }
      144 
      145         public void Info(string message)
      146         {
      147             Logger.Info(message);
      148         }
      149 
      150         public void Info(Func<string> messageFactory)
      151         {
      152             Logger.Info(messageFactory);
      153         }
      154 
      155         public void Info(string message, Exception exception)
      156         {
      157             Logger.Info(exception, message);
      158         }
      159 
      160         public void InfoFormat(string format, params object[] args)
      161         {
      162             Logger.Info(CultureInfo.InvariantCulture, format, args);
      163         }
      164 
      165         public void InfoFormat(Exception exception, string format, params object[] args)
      166         {
      167             Logger.Info(exception, CultureInfo.InvariantCulture, format, args);
      168         }
      169 
      170         public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args)
      171         {
      172             Logger.Info(formatProvider, format, args);
      173         }
      174 
      175         public void InfoFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
      176         {
      177             Logger.Info(exception, formatProvider, format, args);
      178         }
      179 
      180         public void Warn(string message)
      181         {
      182             Logger.Warn(message);
      183         }
      184 
      185         public void Warn(Func<string> messageFactory)
      186         {
      187             Logger.Warn(messageFactory);
      188         }
      189 
      190         public void Warn(string message, Exception exception)
      191         {
      192             Logger.Warn(exception, message);
      193         }
      194 
      195         public void WarnFormat(string format, params object[] args)
      196         {
      197             Logger.Warn(CultureInfo.InvariantCulture, format, args);
      198         }
      199 
      200         public void WarnFormat(Exception exception, string format, params object[] args)
      201         {
      202             Logger.Warn(exception, CultureInfo.InvariantCulture, format, args);
      203         }
      204 
      205         public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args)
      206         {
      207             Logger.Warn(formatProvider, format, args);
      208         }
      209 
      210         public void WarnFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
      211         {
      212             Logger.Warn(exception, formatProvider, format, args);
      213         }
      214     }
      215 }
      
    5. 添加工厂类NLogLoggerFactory并实现抽象类Castle.Core.Logging.AbstractLoggerFactory

       1 using Castle.Core.Logging;
       2 using System;
       3 using System.IO;
       4 using NLogCore = NLog;
       5 
       6 namespace Abp.Castle.Logging.NLog
       7 {
       8 
       9     public class NLogLoggerFactory : AbstractLoggerFactory
      10     {
      11         internal const string DefaultConfigFileName = "nlog.config";
      12         //private readonly ILoggerRepository _loggerRepository;
      13 
      14         public NLogLoggerFactory()
      15        : this(DefaultConfigFileName)
      16         {
      17 
      18         }
      19 
      20         public NLogLoggerFactory(string configFileName)
      21         {
      22             if (!File.Exists(configFileName))
      23             {
      24                 throw new FileNotFoundException(configFileName);
      25             }
      26             NLogCore.LogManager.Configuration = new NLogCore.Config.XmlLoggingConfiguration(configFileName);
      27         }
      28 
      29         public override ILogger Create(string name)
      30         {
      31             if (name == null)
      32             {
      33                 throw new ArgumentNullException(nameof(name));
      34             }
      35             return new NLogLogger(NLogCore.LogManager.GetLogger(name));
      36         }
      37 
      38         public override ILogger Create(string name, LoggerLevel level)
      39         {
      40             throw new NotSupportedException("Logger levels cannot be set at runtime. Please review your configuration file.");
      41         }
      42     }
      43 }
      
    6. 添加LoggingFacility的扩展方法UseAbpNLog

       1 using Castle.Facilities.Logging;
       2 
       3 namespace Abp.Castle.Logging.NLog
       4 {
       5     public static class LoggingFacilityExtensions
       6     {
       7         public static LoggingFacility UseAbpNLog(this LoggingFacility loggingFacility)
       8         {
       9             return loggingFacility.LogUsing<NLogLoggerFactory>();
      10         }
      11     }
      12 }
      
    7. 移除Abp.Castle.Log4Net包,添加Abp.Castle.NLog到Host项目
      9159金沙官网 3

    8. 添加配置文件nlog.config

       1 <?xml version="1.0" encoding="utf-8" ?>
       2 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
       3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       4       autoReload="true"
       5       internalLogLevel="Warn"
       6       internalLogFile="App_DataLogsnlogs.txt">
       7 
       8   <variable name="logDirectory" value="${basedir}log"/>
       9 
      10   <!--define various log targets-->
      11   <targets>
      12 
      13     <!--write logs to file-->
      14     <target xsi:type="File" name="allfile" fileName="${logDirectory}nlog-all-${shortdate}.log"
      15                  layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
      16 
      17     <target xsi:type="File" name="ownFile-web" fileName="nlog-my-${shortdate}.log"
      18                  layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
      19 
      20     <target xsi:type="Null" name="blackhole" />
      21 
      22   </targets>
      23 
      24   <rules>
      25     <!--All logs, including from Microsoft-->
      26     <logger name="*" minlevel="Trace" writeTo="allfile" />
      27 
      28     <!--Skip Microsoft logs and so log only own logs-->
      29     <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
      30     <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
      31   </rules>
      32 </nlog>
      
    9. 修改Startup, 将原来的日志组件log4net替换为nlog

      注释using Abp.Castle.Logging.Log4Net; 添加using Abp.Castle.Logging.NLog;

      1 //using Abp.Castle.Logging.Log4Net;
      2 using Abp.Castle.Logging.NLog;
      

      修改ConfigureServices方法

       1  // Configure Abp and Dependency Injection
       2  return services.AddAbp<AbpBasicWebHostModule>(
       3      // Configure Log4Net logging
       4      //options => options.IocManager.IocContainer.AddFacility<LoggingFacility>(
       5      //    f => f.UseAbpLog4Net().WithConfig("log4net.config")
       6      //)
       7 
       8      // Configure Nlog Logging
       9       options => options.IocManager.IocContainer.AddFacility<LoggingFacility>(
      10       f => f.UseAbpNLog().WithConfig("nlog.config")
      11       )
      12   );
      
    10. 测试

       1 public IActionResult Index()
       2 {
       3       //nlog test
       4        Logger.Info("信息日志");
       5        Logger.Debug("调试日志");
       6        Logger.Error("错误日志");
       7        Logger.Fatal("异常日志");
       8        Logger.Warn("警告日志");
       9        return Redirect("/swagger");
      10 }
      

      测试结果

    ![](https://images2017.cnblogs.com/blog/1011466/201801/1011466-20180106094535034-1400611252.png)
    
     
    

    本文由9159金沙官网发布于9159金沙官网,转载请注明出处:9159金沙官网ABP .Net Core 日志组件集成使用NLog

    关键词:

上一篇:没有了

下一篇:Android模拟器运行慢的解决方案