本文主要介绍.NET Core中,使用NLog将Log日志记录保存到SQLite数据库的配置方法及示例代码。

1、NLog使用SQLite的配置文件

<?xml version="1.0" encoding="utf-8"?>
http://www.nlog-project.org/schemas/NLog.xsd"
xsi:schemaLocation="NLog NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwExceptions="true"
internalLogIncludeTimestamp="true"
internalLogFile="nlog-internal.log"
internalLogLevel="Error">
<targets>
<target xsi:type="Database"
name="db"
dbProvider="System.Data.SQLite.SQLiteConnection, System.Data.SQLite"
connectionString="Data Source=database.db;">
<commandText>
insert into Logs (TimestampUtc, Application, Level, Message, Exception, Logger)
values (@timestamputc, @application, @level, @message, @exception, @logger);
</commandText>
<parameter name="@timestamputc" layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss.fff}" />
<parameter name="@application" layout="My App" />
<parameter name="@level" layout="${level}" />
<parameter name="@message" layout="${message}" />
<parameter name="@exception" layout="${exception:format=tostring}" />
<parameter name="@logger" layout="${logger}" />
</target>
</targets>
<rules>
<logger name="MyApp.*" minlevel="Info" writeTo="database" />
<logger name="*" minlevel="Warn" writeTo="database" />
</rules>
</nlog>

2、SQLite中建表语句

CREATE TABLE "Logs" ( 
`Id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`TimestampUtc` TEXT NOT NULL,
`Application` TEXT NOT NULL,
`Level` TEXT NOT NULL,
`Message` TEXT NOT NULL,
`Logger` TEXT NOT NULL,
`Exception` TEXT )

3、安装引用System.Data.SQLite Nuget包

Package Manager

PM> Install-Package System.Data.SQLite -Version 1.0.112

.NET CLI

> dotnet add package System.Data.SQLite --version 1.0.112

界面管理器安装方法VS(Visual Studio)中Nuget的使用

相关文档.NET Core和ASP.NET Core 日志框架Nlog安装配置及示例代码

推荐文档

相关文档

大家感兴趣的内容

随机列表