1).添加nlog.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="internal-nlog.txt">
<!-- Load the ASP.NET Core plugin -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- define various log targets -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="ownFile-web" fileName="nlog-own-${shortdate}.log"
layout="${longdate}|${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>
2).使用NuGet安装相关日志组件
NLog.Extensions.Logging
NLog.Web.AspNetCore
3).将nlog.config文件配置到环境中并进行日志注册
public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
{
//添加日志配置路径
env.ConfigureNLog("nlog.config");
//注册WEB日志
loggerFactory.AddNLog();
app.AddNLogWeb();
//注册控制台日志
loggerFactory.AddConsole(Configuration.GetSection("Logging")); //控制台日志添加
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
//添加静态文件中间件
app.UseStaticFiles();
//异常中间件
app.UseExceptionHandler();
app.UseMvc(routes =>
{
//默认路由
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Login}");
});
}
4).使用日志记录方法