1、前言
前面介绍了NLog
将日志写入文本文件的方法,下面就来介绍一下如何将日志写入SQL Server
数据库。
2、创建数据表
在SQL Server
中新建一个数据库Dao
,然后创建日志表Log
,代码如下:
USE [Dao]
GO
/****** Object: Table [dbo].[Log] Script Date: 2023/2/7 14:39:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Log](
[Id] [int] IDENTITY(1,1) NOT NULL,
[MachineName] [nvarchar](50) NOT NULL,
[Logged] [datetime] NOT NULL,
[Level] [nvarchar](50) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[Logger] [nvarchar](250) NULL,
[Callsite] [nvarchar](max) NULL,
[Exception] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
3、引入NLog
新建一个Web API
工程,使用NuGet
引入如下组件:
NLog
NLog.Database
NLog.Web.AspNetCore
Microsoft.Data.SqlClient
4、配置文件nlog.config
新建一个XML
文件,文件名为nlog.config
,如下图所示:
将nlog.config
文件改为始终复制,如下图所示:
在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="Info"
internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<target name="db" xsi:type="Database">
<!-- 连接字符串 -->
<connectionString>Data Source=rt-dongshenfeng;Initial Catalog=Dao;User ID=sa;Password=123456</connectionString>
<!-- Insert语句 -->
<commandText>
insert into dbo.Log (MachineName,Logged,Level,Message,Logger,Callsite,Exception) values (@MachineName,@Logged,@Level,@Message,@Logger,@Callsite,@Exception);
</commandText>
<!-- 格式化参数 -->
<parameter name="@MachineName" layout="${machinename}" />
<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>
<logger name="Microsoft.*" minlevel="Trace" final="true" />
<logger name="*" minlevel="Info" writeTo="db" />
</rules>
</nlog>
如果要将日志写入数据库,则xsi:type
的值为Database
,connectionString
节点存放数据库连接字符串,commandText
节点存放插入数据的SQL
,parameter
节点定义格式化参数名称和对应的值。
5、设置NLog为日志管理器
修改Program.cs
文件,代码如下:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
namespace App
{
public class Program
{
public static void Main(string[] args)
{
NLogBuilder.ConfigureNLog("nlog.config");
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(logging=>
{
logging.ClearProviders();
})
.UseNLog();
}
}
6、生成日志
添加一个控制器HomeController
,在其构造函数中注入ILogger
接口,代码如下:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
protected readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[HttpGet]
public ActionResult<string> Get()
{
_logger.LogTrace("This is track info");
_logger.LogDebug("This is debug info");
_logger.LogInformation("This is info");
_logger.LogWarning("This is warn info");
_logger.LogError("This is error info");
_logger.LogCritical("This is fatal info");
return "Hello World";
}
}
}
运行程序,可以发现数据库中已经写入了日志,如下图所示:
7、结语
本文主要介绍了NLog
日志写入SQL Server
的操作方法。示例代码中所用的数据驱动为Microsoft.Data.SqlClient
,如果开发者希望使用MySQL
或Oracle
,只需要切换对应的数据驱动即可。