.net6使用Nlog生成日志文件和日志写入sqlserver数据库

我的另一篇使用log4net的
.net6使用 log4net 生成日志文件和日志写入sqlserver数据库

创建sqlserver的日志表

CREATE TABLE [dbo].[NLog](
	[Id] [BIGINT] IDENTITY(1,1) NOT NULL,
	[Application] [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
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

安装的NuGet包

.net6使用Nlog生成日志文件和日志写入sqlserver数据库_第1张图片

Nlog.config的配置


<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>
		
		
			<commandText>
				INSERT INTO dbo.NLog ([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="@exception" layout="${exception:tostring}"/>
		target>
		
		<target xsi:type="File" name="allfile" fileName="NLog\nlog-all-${shortdate}.log"
				layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

		
		<target xsi:type="File" name="ownFile-web" fileName="NLog\nlog-my-${shortdate}.log"
				layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
		<target xsi:type="Null" name="blackhole"/>
	targets>

	
	<rules>
		<logger name="*" minlevel="Trace" writeTo="allDatabase" />
		
		<logger name="*" minlevel="Trace" writeTo="allfile" />
		
		
		
		<logger name="Microsoft.*" maxlevel="Trace" final="true" />
		
		<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
	rules>
nlog>

Program.cs里的配置

.net6使用Nlog生成日志文件和日志写入sqlserver数据库_第2张图片

成功后的效果

.net6使用Nlog生成日志文件和日志写入sqlserver数据库_第3张图片 .net6使用Nlog生成日志文件和日志写入sqlserver数据库_第4张图片

你可能感兴趣的:(.netcore,数据库)