ASP.NET Core使用NLog记录日志到Microsoft Sql Server

时间:2023-03-09 18:43:22
ASP.NET Core使用NLog记录日志到Microsoft Sql Server

在之前的文章中介绍了如何在ASP.NET Core使用NLog,本文为您介绍在ASP.NET Core使用NLog记录到Microsoft Sql Server

我们需要添加依赖:

添加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="logfiles/internal-nlog.txt"> <!-- define various log targets -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="${var:configDir}\nlog-all.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="ownFile-web" fileName="${var:configDir}\nlog-own.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${message} ${exception}" /> <target xsi:type="Null" name="blackhole" /> <target name="database" xsi:type="Database"> <connectionString>${var:connectionString}</connectionString> <commandText>
insert into dbo.Log (
Application, Logged, Level, Message,
Logger, Callsite, Exception
) values (
@Application, @Logged, @Level, @Message,
@Logger, @Callsite, @Exception
);
</commandText> <parameter name="@application" layout="AspNetCoreNlog" />
<parameter name="@logged" layout="${date}" />
<parameter name="@level" layout="${level}" />
<parameter name="@message" layout="${message}" /> <parameter name="@logger" layout="${logger}" />
<parameter name="@callSite" layout="${callsite}" />
<parameter name="@exception" layout="${exception:tostring}" />
</target>
</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="database" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>

将nlog.config复制到输出目录

ASP.NET Core使用NLog记录日志到Microsoft Sql Server

设置数据库(我使用的是ef code first方式创建数据表)

 using System;

 namespace Apps.Models
{
public class ApplicationLog
{
public int Id { get; set; }
public string Application { get; set; }
public DateTime Logged { get; set; }
public string Level { get; set; }
public string Message { get; set; }
public string Logger { get; set; }
public string Callsite { get; set; }
public string Exception { get; set; }
}
}
         protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<ApplicationLog>(m =>
{
m.ToTable("Log");
m.HasKey(c => c.Id);
m.Property(c => c.Application).IsRequired().HasMaxLength();
m.Property(c => c.Level).IsRequired().HasMaxLength();
m.Property(c => c.Message).IsRequired();
m.Property(c => c.Logger).HasMaxLength();
});
}

在startup.cs文件中添加:

 using NLog.Extensions.Logging;
using NLog.Web; public Startup(IHostingEnvironment env)
{
env.ConfigureNLog("nlog.config");
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{ loggerFactory.AddNLog(); app.AddNLogWeb();
LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection");
LogManager.Configuration.Variables["configDir"] = Configuration.GetSection("LogFilesDir").Value;
}

appsettings.json

  "ConnectionStrings": {
"DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=logdb;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
},
"LogFilesDir": "c:\\temp\\nlog\\logfiles"

然后就可以记录日志了

     public class HomeController :Controller {
private readonly ILogger _logger; public HomeController(ILoggerFactory loggerFactory) {
_logger = loggerFactory.CreateLogger<HomeController>();
}
public IActionResult Index() {
_logger.LogInformation("你访问了首页");
_logger.LogWarning("警告信息");
_logger.LogError("错误信息");
return View();
}
  }

ASP.NET Core使用NLog记录日志到Microsoft Sql Server