NLog是一个配置灵活的日志记录类库,拥有输出日志到文件、存储入库、发送到udp地址的高级功能
1 添加 nlog nuget包
Nlog和NLog.Web.AspNetCore
安装完成后
2 在站点根目录下添加配置文件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">
<targets>
<target xsi:type="File" name="file" fileName="nlog-all-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="exception" fileName="nlog-exception-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="trace" fileName="nlog-trace-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="Null" name="blackhole" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file" />
<!--日志级别:Trace -》Debug-》 Information -》Warning-》 Error-》 Critical-->
<!--排除系统日志-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="trace" />
<logger name="*" minlevel="Error" maxlevel="Error" writeTo="exception" />
</rules>
</nlog>
设置配置文件属性:始终复制
3修改Startup.cs文件
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
//添加nlog支持
loggerFactory.AddNLog();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
4在控制器代码中使用 Microsoft.Extensions.Logging;输出日志
public class HomeController : Controller
{
//定义logger接口
private static ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("info test");
_logger.LogTrace("trace test");
_logger.LogError("error test");
return View();
}
}
5 使用nlog自己的logger输出日志, 这样就不用使用依赖注入了,在一些特定的环境下一样可以使用
public class NLogController : Controller
{
//定义logger接口
private static NLog.Logger _logger;
public NLogController()
{
_logger = NLog.LogManager.GetCurrentClassLogger();
}
public IActionResult Index()
{
_logger.Error("nlog test");
return Content("nlog");
}
}
6在站点根目录下查看日志文件
aspnetcore_nlog\aspnetcore_nlog\bin\Debug\netcoreapp2.1