一、说明

文书档案目录

  1. NLog介绍和采纳表达官方网址:http://nlog-project.org/
  2. NLog和Log4net对比:https://www.cnblogs.com/qinjin/p/5134982.html

本节内容:

二、NLog集成步骤

  • 服务端
    • 获取Logger
    • Logger的基类
    • 配置
    • Abp.Castle.Log4Net 包
  • 客户端
  1. 下载模板项目,下载地址:https://aspnetboilerplate.com/Templates
    选择.Net Core项目
  2. 新建多少个.NET
    Standard类库项目Abp.Castle.NLog
    必威中文官网 1
  3. 添加NuGet包Castle.Core,
    Castle.LoggingFacility, NLog
    必威中文官网 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项目
    必威中文官网 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,
    将原先的日记组件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)

 

ABP使用Castle
温莎的日记记录工具,它可以和区别的logginh类库协作:Log4Net、NLog、塞里log等。Castle为全数Logger库提供多个公共接口,所以它独自于logging库,也能够在有亟待的时候很轻巧地更迭logging。

Log4Net是最流行的Logging库,ABP模板与对头安排后的Log4Net一同坐班,不过它只是一个单行情势的正视性(查看“配置”核心),所以您能够替换来你心爱的日志库。

获取Logger

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

第一,大家应猎取四个Logger,由于ABP大批量施用重视注入,所以大家得以用属性注入形式来注入三个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接口的命名空间。

其实,大家定义三个当着的ILogger对象,名称为Logger,那一个指标将写日记,重视注入系统将在TaskAppService对象创制之后,设置那几个特性,那正是鼎鼎大名的属性注入情势。

其三,大家把Logger设置为NullLogger.Instance。没那行代码,系统也能职业,但这是性质注入方式的拔尖推行,如若都尚未那个Logger,在动用它时会收到二个“对象引用…“的至极。那个正是保障它为不空,所以若无设置那个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的调整器、应用服务类等提供了基类。它们声明一(Wissu)个Logger属性,所以您能够一直动用那几个Logger写日记,不供给注入,比方:

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

在意:SimpleTaskSystemControllerBase是大家选择特定的三翻五次自AbpController的基类。因而,它能够直接使用Logger。同样,你也得感觉您的另外类写公共基类,然后,你就无须每一回注入Logger了。

配置

从ABP模板创设的利用已经为Log4Net实现了具备的布局。

暗中同意配置日志格式如下所示

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

它们在利用的log4net.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>

Log4net是高度可布署,并强硬的logging库,你能够用不一样的格式写日记并存向不一致的介质(文本文件,数据库…),你能够设置日志的最低等别,你能够写差异的日志到区别的日记文件,当日志文件达到钦命大小时,它会活动备份并创办新的日记文件(那个布局中,回滚文件每文件配置一千0KB)等等,阅读它和谐的安排文书档案获取越来越多音信。

最后,在Global.asax文件中,大家证明要用log4net.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日志记录工具,它不直接注重于log4net,如上边的说教。但有三个Castle的Log4Net集成的难题,它不帮忙新型版的log4new。大家创制二个nuget包,名叫Abp.Castle.Log4Net,来消除那几个标题。把这么些包参预到大家缓和方案后,大家所急需做的只是在使用运行代码里那样修改代码:

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);    }}

唯的不等是我们使用“UseAbpLog4Net()“方法(定义在Abp.Castle.Logging.Log4Net命名空间里)替换”UseLog4Net()“。当我们利用Abp.Castle.Log4Net包,就不再必要Castle.温莎-log4net和Castle.Core-log4net包。

客户端

ABP为客户端定义了三个简约的Javascript logging
Api,它暗中认可在在浏览器的调整台上写日记,示例代码:

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

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

相关文章