创建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包
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">
<!-- 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="server=.;database=Net6Learning;user id=sa;password=123456">
<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= "@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="Trace" 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>
Program.cs里的配置
成功后的效果