[.Net Core] - 使用 NLog 记录日志到 Sql Server
时间: 2024-02-11 22:04:51 浏览: 145
好的,以下是使用NLog将日志记录到SqlServer的步骤:
1. 首先,需要在项目中安装NLog和NLog.Web.AspNetCore包。可以使用NuGet包管理器或在项目文件中手动添加依赖项。
2. 在项目的appsettings.json文件中添加以下NLog配置:
```
"NLog": {
"targets": {
"database": {
"type": "Database",
"dbProvider": "System.Data.SqlClient",
"connectionString": "Server=[server];Database=[database];User Id=[user];Password=[password];",
"commandText": "INSERT INTO [Logs] ([Date], [Level], [Logger], [Message], [Exception]) VALUES (@Date, @Level, @Logger, @Message, @Exception);",
"parameter": [
{
"name": "@Date",
"layout": "${date}"
},
{
"name": "@Level",
"layout": "${level}"
},
{
"name": "@Logger",
"layout": "${logger}"
},
{
"name": "@Message",
"layout": "${message}"
},
{
"name": "@Exception",
"layout": "${exception}"
}
]
}
},
"rules": [
{
"logger": "*",
"minLevel": "Trace",
"writeTo": "database"
}
]
}
```
3. 在Startup.cs文件中添加以下代码:
```csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
//...
loggerFactory.AddNLog();
//...
app.UseMiddleware<NLogMiddleware>();
//...
}
```
4. 创建一个名为Logs的表,用于存储日志记录。表结构应如下所示:
```sql
CREATE TABLE [dbo].[Logs](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime2](7) NOT NULL,
[Level] [nvarchar](50) NOT NULL,
[Logger] [nvarchar](250) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[Exception] [nvarchar](max) NULL,
CONSTRAINT [PK_Logs] 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]
```
5. 现在,可以在代码中使用NLog记录日志了。例如:
```csharp
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("Hello, world!");
return View();
}
```
这将在Logs表中插入一条日志记录。
希望这可以帮助到你。
阅读全文