即兴添加一下

.NET 6 使用Nlog 记录日志到本地并写入SQLserver数据库

1. 安装Nlog

img
对应Nuget包版本
NLog:5.0.4
NLog.Database:5.0.4
NLog.Web.AspNetCore:5.1.4
Microsoft.Data.SqlClient: 5.0.0 (写入SQLServer数据库用的)

2. 建表SQL

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]
GO

3. 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>
  <targets>
    <target name="database" xsi:type="Database">
      <connectionString>Server=localhost;Database=Travel;User=sa;Password=123456;Encrypt=True;TrustServerCertificate=True; </connectionString>
      <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}" />
    <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="Microsoft.*" finalMinLevel="Warn" writeTo="database" />
    <logger name="Microsoft.AspNetCore.Hosting.*" finalMinLevel="Error" writeTo="database" />
    <logger name="*" minlevel="Info" writeTo="database" />
    <logger name="*" minlevel="Trace" writeTo="allfile" />
    <!--<logger name="*" minlevel="Trace" writeTo="ownFile-web" />-->
  </rules>
</nlog>

4. Nlog日志级别

名称 解释 使用范围
Trace very detailed logs,包含大量的信息 该级别一般仅在开发环境中启用。
Debug debugging information, 比 Trance 级别稍微粗略高 一般在生产环境中不启用
Info information messages,普通消息 一般在生产环境中启用
Warn warning messages,警告信息 一般用于可恢复或临时性错误的非关键问题
Error Error messages,错误信息 一般错误信息
Fatal warning messages,严重错误信息 非常严重的错误

5. Program.cs写法

 //添加到builder.Build()之前即可
 builder.Logging.ClearProviders();
 builder.Host.UseNLog();

6. 代码写法

img
img

7. 呈现效果

数据库效果

img

本地文件效果

img

8. 参考

Nlog官网.Net6 示例:https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-6
写入SQLServer数据库:https://sodiqyekeen.com/database-logging-using-nlog-in-net-6/

Tips: 在参考写入数据库这篇文章之前用搜索到的其他的配置文件老是保存不了到数据库,最后通过复制文章中的配置文件进行修改才成功写入了数据库。

posted @ 2023-12-06 14:07  我本梁人  阅读(452)  评论(0编辑  收藏  举报