日志输出是应用程序必不可少的部分,log4net,nlog这些成熟的组件在之前的项目中被广泛使用,在asp.net core的项目中没有找到与之对应的log4net版本,nlog对core提供了很好的支持,使用上也就简单几步即可完成日志组件的安装。
github上提供了非常明细的操作步骤:
https://github.com/NLog/NLog.Extensions.Logging/blob/master/README.md
1,project.json文件增加引用
"dependencies": {
"NLog.Extensions.Logging": "1.0.0-*"
}
2,项目根目录增加配置文件nlog.config
3,startup.cs增加引用
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddNLog();//添加NLog env.ConfigureNLog("nlog.config");
4,project.json增加日志配置文件
"publishOptions": { "include": [ "wwwroot", "**/*.cshtml", "appsettings.json", "nlog.config",//增加nlog
"web.config" ] },
配置文件范例:
<?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="Warn" internalLogFile="c: empinternal-nlog.txt"> <!-- define various log targets --> <targets> <!-- write logs to file --> <target xsi:type="File" name="allfile" fileName="c: emp log-all-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="ownFile-web" fileName="c: emp log-own-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${message} ${exception}" /> <target xsi:type="Null" name="blackhole" /> </targets> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip Microsoft logs and so log only own logs--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>