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

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

我们需要添加依赖:

添加nlog.config文件

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4       autoReload="true"
 5       internalLogLevel="Warn"
 6       internalLogFile="logfiles/internal-nlog.txt">
 7 
 8   <!-- define various log targets -->
 9   <targets>
10     <!-- write logs to file -->
11     <target xsi:type="File" name="allfile" fileName="${var:configDir}
log-all.log"
12             layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />
13 
14 
15     <target xsi:type="File" name="ownFile-web" fileName="${var:configDir}
log-own.log"
16             layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}" />
17 
18     <target xsi:type="Null" name="blackhole" />
19 
20     <target name="database" xsi:type="Database">
21 
22       <connectionString>${var:connectionString}</connectionString>
23 
24  
25       <commandText>
26         insert into dbo.Log (
27         Application, Logged, Level, Message,
28         Logger, Callsite, Exception
29         ) values (
30         @Application, @Logged, @Level, @Message,
31         @Logger, @Callsite, @Exception
32         );
33       </commandText>
34 
35       <parameter name="@application" layout="AspNetCoreNlog" />
36       <parameter name="@logged" layout="${date}" />
37       <parameter name="@level" layout="${level}" />
38       <parameter name="@message" layout="${message}" />
39 
40       <parameter name="@logger" layout="${logger}" />
41       <parameter name="@callSite" layout="${callsite}" />
42       <parameter name="@exception" layout="${exception:tostring}" />
43     </target>
44   </targets>
45 
46   <rules>
47     <!--All logs, including from Microsoft-->
48     <logger name="*" minlevel="Trace" writeTo="allfile" />
49     
50     <!--Skip Microsoft logs and so log only own logs-->
51     <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
52     <logger name="*" minlevel="Trace" writeTo="database" />
53     <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
54   </rules>
55 </nlog>

将nlog.config复制到输出目录

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

 1 using System;
 2 
 3 namespace Apps.Models
 4 {
 5     public class ApplicationLog
 6     {
 7         public int Id { get; set; }
 8         public string Application { get; set; }
 9         public DateTime Logged { get; set; }
10         public string Level { get; set; }
11         public string Message { get; set; }
12         public string Logger { get; set; }
13         public string Callsite { get; set; }
14         public string Exception { get; set; }
15     }
16 }
 1         protected override void OnModelCreating(ModelBuilder builder)
 2         {
 3             builder.Entity<ApplicationLog>(m =>
 4             {
 5                 m.ToTable("Log");
 6                 m.HasKey(c => c.Id);
 7                 m.Property(c => c.Application).IsRequired().HasMaxLength(50);
 8                 m.Property(c => c.Level).IsRequired().HasMaxLength(50);
 9                 m.Property(c => c.Message).IsRequired();
10                 m.Property(c => c.Logger).HasMaxLength(250);
11             });
12         }

在startup.cs文件中添加:

 1 using NLog.Extensions.Logging;
 2 using NLog.Web;
 3 
 4 public Startup(IHostingEnvironment env)
 5 {
 6     env.ConfigureNLog("nlog.config");
 7 }
 8 
 9 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
10 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
11 {
12 
13 
14     loggerFactory.AddNLog();
15 
16     app.AddNLogWeb();
17     LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection");
18     LogManager.Configuration.Variables["configDir"] = Configuration.GetSection("LogFilesDir").Value;
19 }

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" 

然后就可以记录日志了

 1     public class HomeController :Controller {
 2         private readonly ILogger _logger;
 3 
 4         public HomeController(ILoggerFactory loggerFactory) {
 5             _logger = loggerFactory.CreateLogger<HomeController>();
 6         }
 7         public IActionResult Index() {
 8             _logger.LogInformation("你访问了首页");
 9             _logger.LogWarning("警告信息");
10             _logger.LogError("错误信息");
11             return View();
12         }
13   }

原文地址:https://www.cnblogs.com/chen8854/p/6800158.html