1什么是Nlog,为什么要使用Nlog作为日志框架

.Net没有内置的文本日志提供者,对于实际需要记录日志到文本文件中的需求不相匹配,常用的第三方日志框架包括Log4Net,Nlog,SeriLog。考虑到系统的兼容性与使用的简易程度,推荐使用NLog框架记录系统运行日志记录。
NLog是一个灵活且免费的日志记录平台,适用于各种.NET平台,包括.NET标准。 NLog 使写入多个目标变得容易。(数据库、文件、控制台,调试输出,电子邮件,时间日志)并动态更改日志记录配置。

  • 易于配置
    NLog 非常容易配置,无论是通过配置文件还是以编程方式。 即使不重新启动应用程序,也可以更改配置。

  • 可模板化
    每个日志消息都可以使用各种布局渲染进行模板化

  • 扩展
    NLog 已经包含多个目标和预定义布局,但您也可以扩展 使用您自己的自定义目标和布局,或包含自己的自定义上下文值

  • 结构化日志记录
    完全支持结构化日志记录和 处理消息模板和自定义日志事件属性。

  • 微软扩展日志记录
    NLog可以与MicrosoftExtensible Logging(和 ASP.NET Core)完全集成,而无需替换标准的Microsoft LoggerFactory。 NLog 自动捕获LogEvent 属性,并可以在结构化日志记录目标输出中使用它们。

  • appsettings.json
    NLog 配置可以从appsettings.json加载,作为NLog.configXML 文件的替代方法。这也是可能的 使用 appsettings.json 中的值配置 NLog 目标,with${configset}

2 Nlog.config配置文件

日志输出的位置,布局及样式设置均是可以自行配置的,通常使用Nlog.config这个xml配置文件。该配置文件可以在多个位置下,以扫描到的第一个Nlog.config的规则为准,若启动项未扫描到Nlog.config,则log规则不生效。

2.1 Nlog.config加载位置

  • 对于独立的 *.exe 应用程序,按如下方式搜索文件:

标准应用程序配置文件 app.config(例如应用程序名称.exe.config)
应用程序目录中的应用程序名称.exe.nlog
应用程序目录中的 NLog.config
NLog.dll.nlog 位于 NLog.dll 所在的目录中(仅当 GAC 中未安装 NLog时)

  • 对于 ASP.NET 应用程序,按如下方式搜索文件:

标准 Web 应用程序配置文件 Web.config
web.nlog 位于与 web.config 相同的目录中
应用程序目录中的NLog.config
NLog.dll.nlog 位于 NLog.dll 所在的目录中(仅当 GAC 中未安装 NLog 时)

2.2 Nlog.config.xml

nlog配置文件官方文档说明

<?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"autoReload="true"internalLogLevel="Info"internalLogFile="./logs/internal-nlog-AspNetCore.txt">  <!-- 日志输出目录 相对路径与绝对路径 --><!-- enable asp.net core layout renderers --><extensions><add assembly="NLog.Web.AspNetCore"/></extensions><!-- targets标签定义日志输出目标,由多个target标签来定义 --><targets><!-- type: type=File输出类型为文件 fileName:fileName日志文件名 layout:记录日志文件的格式信息 layout的具体样式与配置layoutrenders有关,定制化不同的layout可参考官方文档的layoutrenders信息--> <!-- longdate:日期 格式形如`yyyy-MM-dd HH:mm:ss.ffff`--> <!-- target xsi:type="File" 时,其他的标签属性可以看配置文档 https://github.com/NLog/NLog/wiki/File-target--> <target xsi:type="File" name="allfile" fileName="./logs/nlog-AspNetCore-all-${shortdate}.log"layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" /><!-- target记录的最大日志大小,单位为字节  archiveAboveSize:单个日志最大保存的日志大小,单位是字节  maxArchiveFiles :指定日志保存的最大个数--><target xsi:type="File" name="ownFile-web" fileName="./logs/nlog-AspNetCore-own-${shortdate}.log"archiveAboveSize ="10000" maxArchiveFiles="3"layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" /><!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection --><!-- target xsi:type="Console" 时,其他的标签属性可以看配置文档 https://github.com/NLog/NLog/wiki/Console-target--> <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" /></targets><!-- rules标签定义每个target的输出规则 一个target标签可以对应多个输出规则,从上往下进行规则的匹配--><rules><!--name:实际日志的名字,通常是命名空间加ILogger<T>的T信息 minlevel:记录Trace级别以上的日志信息,会根据名叫allfile的target定义的日志输出信息规则进行日志记录--><logger name="*" minlevel="Trace" writeTo="allfile" /><!--final:final=true时,尽管日志往下可能还有多个规则与该日志记录匹配,也不会再往下进行target与rule关系的映射了 --><logger name="Log.Service" minlevel="Info" writeTo="lifetimeConsole" final="true" /><!--maxlevel:日志记录的最大级别,maxlevel=Info 记录Info级别以下的资源--><logger name="Log.*" maxlevel="Info" final="true" /><logger name="Log1.*" minlevel="Trace" writeTo="ownFile-web" /><logger name="System.Net.Http.*" maxlevel="Info" final="true" /></rules>
</nlog>

该配置文件属性:Copy If newer

3 使用步骤【.NetCore项目结构】

  • 安装Nlog的nuge包
    SDK2.1版本时安装 NLog.Extensions.Logging, Version=5.0.0.0

  • 注入Nlog服务

startup类中修改ConfigureServices(IServiceCollection services)方法

public void  ConfigureServices(IServiceCollection services){//添加Nlog服务services.AddLogging(loggingbuilder=> {loggingbuilder.AddNLog();});}
  • 配置Log文件的输出规则

Nlog.config.xml配置文件进行配置,具体xml的内容需要根据实际业务进行编写。nlog配置文件官方文档说明

  • 注入logger,记录日志信息
    利用构造函数注入 private readonly ILogger<泛型> logger;调用扩展方法记录日志
  //// 摘要://     Formats the message and creates a scope.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to create the scope in.////   messageFormat://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.//// 傳回://     A disposable scope object. Can be null.public static IDisposable BeginScope(this ILogger logger, string messageFormat, params object[] args);//// 摘要://     Formats and writes a log message at the specified log level.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   logLevel://     Entry will be written on this level.////   exception://     The exception to log.////   message://     Format string of the log message.////   args://     An object array that contains zero or more objects to format.public static void Log(this ILogger logger, LogLevel logLevel, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes a log message at the specified log level.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   logLevel://     Entry will be written on this level.////   eventId://     The event id associated with the log.////   message://     Format string of the log message.////   args://     An object array that contains zero or more objects to format.public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, string message, params object[] args);//// 摘要://     Formats and writes a log message at the specified log level.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   logLevel://     Entry will be written on this level.////   message://     Format string of the log message.////   args://     An object array that contains zero or more objects to format.public static void Log(this ILogger logger, LogLevel logLevel, string message, params object[] args);//// 摘要://     Formats and writes a log message at the specified log level.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   logLevel://     Entry will be written on this level.////   eventId://     The event id associated with the log.////   exception://     The exception to log.////   message://     Format string of the log message.////   args://     An object array that contains zero or more objects to format.public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes a critical log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogCritical(this ILogger logger, string message, params object[] args);//// 摘要://     Formats and writes a critical log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogCritical(this ILogger logger, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes a critical log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogCritical(this ILogger logger, EventId eventId, string message, params object[] args);//// 摘要://     Formats and writes a critical log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogCritical(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes a debug log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogDebug(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes a debug log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogDebug(this ILogger logger, EventId eventId, string message, params object[] args);//// 摘要://     Formats and writes a debug log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogDebug(this ILogger logger, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes a debug log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogDebug(this ILogger logger, string message, params object[] args);//// 摘要://     Formats and writes an error log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogError(this ILogger logger, string message, params object[] args);//// 摘要://     Formats and writes an error log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogError(this ILogger logger, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes an error log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogError(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes an error log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogError(this ILogger logger, EventId eventId, string message, params object[] args);//// 摘要://     Formats and writes an informational log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogInformation(this ILogger logger, EventId eventId, string message, params object[] args);//// 摘要://     Formats and writes an informational log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogInformation(this ILogger logger, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes an informational log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogInformation(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes an informational log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogInformation(this ILogger logger, string message, params object[] args);//// 摘要://     Formats and writes a trace log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogTrace(this ILogger logger, string message, params object[] args);//// 摘要://     Formats and writes a trace log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogTrace(this ILogger logger, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes a trace log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogTrace(this ILogger logger, EventId eventId, string message, params object[] args);//// 摘要://     Formats and writes a trace log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogTrace(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes a warning log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogWarning(this ILogger logger, EventId eventId, string message, params object[] args);//// 摘要://     Formats and writes a warning log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   eventId://     The event id associated with the log.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogWarning(this ILogger logger, EventId eventId, Exception exception, string message, params object[] args);//// 摘要://     Formats and writes a warning log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogWarning(this ILogger logger, string message, params object[] args);//// 摘要://     Formats and writes a warning log message.//// 參數://   logger://     The Microsoft.Extensions.Logging.ILogger to write to.////   exception://     The exception to log.////   message://     Format string of the log message in message template format. Example: "User {User}//     logged in from {Address}"////   args://     An object array that contains zero or more objects to format.public static void LogWarning(this ILogger logger, Exception exception, string message, params object[] args);

.Net学习——Nlog日志框架的使用相关推荐

  1. 日志管理-NLog日志框架简写用法

    日志管理-NLog日志框架简写用法 本文转载:http://www.blogjava.net/qiyadeng/archive/2013/02/27/395799.html 在.net中也有非常多的日 ...

  2. 学习Java日志框架之——搞懂日志门面(JCL+SLF4J)

    文章目录 系列文章目录 一.什么是日志门面 1.门面模式(外观模式) 2.日志门面 二.了解JCL 1.JCL组件结构 2.JCL案例 (1)JCL默认实现 (2)导入log4j测试原有程序 三.SL ...

  3. 学习Java日志框架之——搞懂JUL(java.util.logging)

    文章目录 系列文章目录 一.JUL简介 二.JUL组件介绍 三.代码实例 1.入门案例 2.日志级别 (1)默认日志级别源码分析 3.自定义日志级别 4.将日志输出到文件中 5.Logger的父子关系 ...

  4. NLog日志框架使用探究

    前言 日志是每个程序的基本模块.本文是为了探究如何通过NLog方便及记录日志并通过Log4View工具收集日志统一查看. 为什么是NLog? 下载量NLog和Log4Net差不多,这两个日志模块是.N ...

  5. NLog日志框架-输出文件数量与大小控制

    目录 概述 一.NLog使用说明 二.文件输出控制配置 1.规则说明 2.演示案例 总结 概述 Nlog是一个免费开源的.NET日志框架,拥有丰富的日志路由(XML配置表)和强大的管理能力.NLog便 ...

  6. Nlog 日志框架使用介绍

    原文地址:https://www.cnblogs.com/zh7791/p/12620439.html NLog是一个基于.NET平台编写的类库,我们可以使用NLog在应用程序中添加极为完善的跟踪调试 ...

  7. 学习日志框架之——搞懂logback

    文章目录 系列文章目录 一.logback概述 1.Logback简介 2.Logback中的组件 3.Logback配置文件 4.日志输出格式 二.使用示例 1.依赖导入 2.入门案例 3.配置文件 ...

  8. 一个简单好用的日志框架NLog

    之前我介绍过如何使用log4net来记录日志,但最近喜欢上了另一个简单好用的日志框架NLog. 关于NLog和log4net的比较这里就不多讨论了,感兴趣的朋友可以参看.NET日志工具介绍和log4n ...

  9. java日志框架(一)JUL 学习 ,这个是什么,他在代码中如何使用,一篇文章讲清楚

    这里写目录标题 JUL 是什么 JUL组件介绍 代码中如何使用(控制台输出) 日志级别 自定义输出级别 输出日志到文件(磁盘文件中) 日志对象父子关系 配置文件 使用方法总结 JUL 是什么 JUL全 ...

最新文章

  1. Oracle——redo+undo总结
  2. Android Studio Emulator 提示 “/dev/kvm is not found” 解决办法
  3. 并不是所有SAP产品的UX,都得遵循Fiori UX风格
  4. cobar mysql cluster_Cobar使用文档(可用作MySQL大型集群解决方案)
  5. 浅谈.Net版(C#)的CMP模式
  6. logstash 吞吐量优化_1002-谈谈ELK日志分析平台的性能优化理念
  7. linux mii,Linux mii-tool 命令用法详解-Linux命令大全(手册)
  8. python简介pdf_Python以及QuTip包简介.PDF
  9. ImageMagick 将PDF转图片命令
  10. 扩大人类对车辆的控制 新种双轨制自驾车出现
  11. Linux性能优化(九)——Kernel Bypass
  12. 第五节 comware概述
  13. mybats-puls---条件构造器Wrapper,插件扩展,SQL注入器,公共字段填充
  14. java变量不声明可以直接使用吗_Java基础_变量的声明与使用
  15. 第三方支付平台:易宝支付
  16. Python实现ACO蚁群优化算法优化支持向量机回归模型(SVR算法)项目实战
  17. Linux 查看内核以及系统版本的3种方法
  18. js中if到底该如何判断变量为空?
  19. 宝塔php防盗链,宝塔面板开启防盗链的方法详细教程
  20. Vuforia的学习(一)---Vuforia的介绍

热门文章

  1. 文献阅读(246)Glow
  2. 工业视觉检测的发展趋势
  3. php获取二维数组前三条,php二维数组排序后获取最大值
  4. 计算机地图制图的优势,计算机地图制图实习报告.doc
  5. 常见空间聚类算法优劣概述
  6. 新版白话空间统计(15)空间关系概念化之距离
  7. RHEL8.x-RedHat-Ansible
  8. 服务器系统我们无法创建新的分区,安装Win10系统提示“无法创建新的分区也找不到现有的分区”如何解决...
  9. 安装win7的时候出现“安装程序无法创建新的系统分区,也无法定位系统分区”
  10. Maxthon阻止了一个错误,...Flash9e.ocx解决办法