Net6+NLog 写入数据库 Sql Server为例

发布时间 2023-04-14 22:58:19作者: 孤海飞雁

这个百度一大片,到处不行,国外网站找也是有问题,官网文档也是有点操蛋。搞到现在ok了 直接上代码。

 //Program.cs 配置
#region 日志 LogManager.LoadConfiguration(ParameterConfig.Nlog).GetCurrentClassLogger(); builder.Logging.AddNLog(ParameterConfig.Nlog);//你nlog文件名称 LogManager.Configuration.Variables["connectionString"] = builder.Services.AddNLogConnection(builder.Configuration);//这里是你要数据库的链接 //.Variables["connectionString"] = services.AddNLogConnection(builder.Configuration); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //避免日志中的中文输出乱码 #endregion

  数据库表

CREATE TABLE [dbo].[AICFlowStatistics_T_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]

 

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">

	<!-- enable asp.net core layout renderers -->
	<extensions>
		<add assembly="NLog.Web.AspNetCore"/>
	</extensions>

	<!-- the targets to write to -->
	<targets>
		<!--database-->
		<target name= "allDatabase" xsi:type="Database"
			dbProvider="System.Data.SqlClient.SqlConnection, System.Data"
			connectionString="${var:connectionString}">
			<commandText>
				INSERT INTO dbo.AICFlowStatistics_T_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= "@callSite" layout="${callsite:filename=true}" />
			<parameter name="@exception" layout="${exception:tostring}"/>
		</target>
		<!-- File Target for all log messages with basic details -->
		<target xsi:type="File" name="allfile" fileName="NLog\nlog-all-${shortdate}.log"
				layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

		<!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
		<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 to map from logger name to target -->
	<rules>
		<logger name="*" minlevel="Warning" writeTo="allDatabase" />
		<!--All logs, including from Microsoft-->
		<logger name="*" minlevel="Trace" writeTo="allfile" />
		<!--Output hosting lifetime messages to console target for faster startup detection -->
		<!--<logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole,ownFile-web" final="true" />-->
		<!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
		<logger name="Microsoft.*" maxlevel="Trace" final="true" />
		<!--<logger name="System.Net.Http.*" maxlevel="Info" final="true" />-->
		<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
	</rules>
</nlog>


 下图为依赖的包

 

 

 最后启动 要利用注入 写入

 

 

 

成功写入

 

 

 

下面控制记录那种级别的日志, Warning 只会记录警告及以上的日志,如果为Trace,就是N多日志,记得改下

<rules> <logger name="*" minlevel="Warning" writeTo="allDatabase" /> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Output hosting lifetime messages to console target for faster startup detection --> <!--<logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole,ownFile-web" final="true" />--> <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) --> <logger name="Microsoft.*" maxlevel="Trace" final="true" /> <!--<logger name="System.Net.Http.*" maxlevel="Info" final="true" />--> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules>