一、说明

一、说明

文书档案目录

  1. NLog介绍和接纳验证官网:http://nlog-project.org/
  2. NLog和Log4net对比:https://www.cnblogs.com/qinjin/p/5134982.html
  1. NLog介绍和行使验证官网:http://nlog-project.org/
  2. NLog和Log4net对比:https://www.cnblogs.com/qinjin/p/5134982.html

本节内容:

二、NLog集成步骤

贰、NLog集成步骤

  • 服务端
    • 获取Logger
    • Logger的基类
    • 配置
    • Abp.Castle.Log4Net 包
  • 客户端
  1. 下载模板项目,下载地址:https://aspnetboilerplate.com/Templates
    选择.Net Core项目
  2. 新建1个.NET
    斯坦dard类库项目Abp.Castle.NLog
    图片 1
  3. 添加NuGet包Castle.Core,
    Castle.LoggingFacility, NLog
    图片 2
  4. 参考abp log四net(ABP源码)添加class NLogLogger继承马尔斯halByRefObject并落实接口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项目
    图片 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_Data\Logs\nlogs.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,
    将原先的日志组件log四net替换为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 }
    

    测试结果

  1. 下载模板项目,下载地址:https://aspnetboilerplate.com/Templates
    选择.Net Core项目
  2. 新建二个.NET
    Standard类库项目Abp.Castle.NLog
    图片 1
  3. 添加NuGet包Castle.Core,
    Castle.LoggingFacility, NLog
    图片 2
  4. 参考abp log四net(ABP源码)添加class NLogLogger继承马尔斯halByRefObject并落到实处接口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项目
    图片 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_Data\Logs\nlogs.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,
    将本来的日志组件log四net替换为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)

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

 

ABP使用Castle
温莎的日志记录工具,它能够和见仁见智的logginh类库同盟:Log四Net、NLog、Serilog等。Castle为全数Logger库提供1个国有接口,所以它独自于logging库,也得以在有亟待的时候很不难地更迭logging。

Log四Net是最盛行的Logging库,ABP模板与对头安插后的Log四Net1起干活,不过它只是二个单行形式的信赖(查看“配置”主旨),所以您能够替换来你兴奋的日志库。

获取Logger

无论您用哪个logging库,写日记的代码是同1的(归功于Castle的公共ILogger接口)。

第2,大家应得到四个Logger,由于ABP大批量采纳正视注入,所以我们能够用属性注入格局来注入2个Logger对象。看一下写一行日志的示例类:

using Castle.Core.Logging; //1: Import Logging namespacepublic class TaskAppService : ITaskAppService{        //2: Getting a logger using property injection    public ILogger Logger { get; set; }    public TaskAppService()    {        //3: Do not write logs if no Logger supplied.        Logger = NullLogger.Instance;    }    public void CreateTask(CreateTaskInput input)    {        //4: Write logs        Logger.Info("Creating a new task with description: " + input.Description);        //TODO: save task to database...    }}

率先,我们引用Castle的ILogger接口的命名空间。

实则,我们定义1个当着的ILogger对象,名称为Logger,这一个指标将写日记,正视注入系统将在TaskAppService对象创造之后,设置那天性情,那正是威名赫赫的性质注入情势。

其3,我们把Logger设置为NullLogger.Instance。没那行代码,系统也能做事,但那是性质注入方式的一级实践,假设都未有这一个Logger,在选拔它时会收到1个“对象引用…“的可怜。那些便是保障它为不空,所以假如未有设置这些Logger,它就是NullLogger。那就是门到户说的Null对象情势。NullLogger实质上什么样都不做,不写任何日志,所以我们的类不管是有无实质上的logger,都能做事。

末尾,我们用info级别来写一文件日志,有多少个不等的级别(查看“配置”主题)。

设若大家调用CreateTask方法,检查日志文件,大家得以见见类似以下一行日志:

INFO  2014-07-13 13:40:23,360 [8    ] SimpleTaskSystem.Tasks.TaskAppService    - Creating a new task with description: Remember to drink milk before sleeping!

Logger的基类

ABP为Mvc的控制器、Web
Api的控制器、应用服务类等提供了基类。它们声雅培(Abbott)个Logger属性,所以您能够直接使用这么些Logger写日记,不供给注入,例如:

public class HomeController : SimpleTaskSystemControllerBase{    public ActionResult Index()    {         Logger.Debug("A sample log message...");        return View();    }}

小心:SimpleTaskSystemControllerBase是我们选用特定的后续自AbpController的基类。因而,它能够平素利用Logger。同样,你也得以为您的别的类写公共基类,然后,你就不要每一遍注入Logger了。

配置

从ABP模板成立的利用已经为Log四Net达成了具备的布局。

默许配置日志格式如下所示

  • Log级别:DEBUG,INFO,WARN,ERROR,或FATAL。
  • 日子和岁月:写日记时的日期时间。
  • 线程号:写日记的线程的线程号。
  • Logger名称:常常是写日记的类名。
  • 日志文本:你实质上写日记文本。

它们在应用的log四net.config文件里定义,如下:

<?xml version="1.0" encoding="utf-8" ?><log4net>  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender" >    <file value="Logs/Logs.txt" />    <appendToFile value="true" />    <rollingStyle value="Size" />    <maxSizeRollBackups value="10" />    <maximumFileSize value="10000KB" />    <staticLogFileName value="true" />    <layout type="log4net.Layout.PatternLayout">        <conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />    </layout>  </appender>  <root>    <appender-ref ref="RollingFileAppender" />    <level value="DEBUG" />  </root>  <logger name="NHibernate">    <level value="WARN" />  </logger></log4net>

Log四net是莫斯中国科学技术大学学可配备,并有力的logging库,你能够用分裂的格式写日记并存向分裂的介质(文本文件,数据库…),你能够安装日志的最低级别,你能够写区别的日记到不一样的日志文件,当日志文件达到内定大小时,它会自行备份并成立新的日记文件(那些布局中,回滚文件每文件配置10000KB)等等,阅读它本人的陈设文书档案获取更多音信。

末尾,在Global.asax文件中,大家评释要用log四net.config文件来选择Log4Net:

public class MvcApplication : AbpWebApplication{    protected override void Application_Start(object sender, EventArgs e)    {        IocManager.Instance.IocContainer.AddFacility<LoggingFacility>(f => f.UseLog4Net().WithConfig("log4net.config"));        base.Application_Start(sender, e);    }}

那是唯一一行依赖于log4net的代码,同时,Web项目仅依赖log4net类的nuget包。所以,你能够很不难的调换另二个库,而不要改其余日志代码。

Abp.Castle.Log4Net 包

ABP使用Castle日志记录工具,它不直接注重于log四net,如上边的布道。但有3个Castle的Log四Net集成的难题,它不支持最新版的log四new。我们创制叁个nuget包,名叫Abp.Castle.Log四Net,来缓解那些题材。把这些包出席到大家缓解方案后,我们所急需做的只是在应用运维代码里这么修改代码:

public class MvcApplication : AbpWebApplication{    protected override void Application_Start(object sender, EventArgs e)    {        IocManager.Instance.IocContainer.AddFacility<LoggingFacility>(f => f.UseAbpLog4Net().WithConfig("log4net.config"));        base.Application_Start(sender, e);    }}

唯的差异是大家利用“UseAbpLog四Net()“方法(定义在Abp.Castle.Logging.Log四Net命名空间里)替换”UseLog4Net()“。当大家接纳Abp.Castle.Log4Net包,就不再要求Castle.温莎-log四net和Castle.Core-log四net包。

客户端

ABP为客户端定义了一个简练的Javascript logging
Api,它默许在在浏览器的控制台上写日记,示例代码:

abp.log.warn('a sample log message...');

越多新闻,查看logging API 文书档案。

相关文章