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