ASP.NET 8 日志处理之NLog

不推荐使用,输出日志到数据库多次尝试未成功,可参考下面链接研究研究

Database Logging Using NLog in .Net 6 - Sodiq Yekeen

1、安装依赖包

NLog:

NuGet\Install-Package NLog -Version 5.2.8

NLog.Database:

NuGet\Install-Package NLog.Database -Version 5.2.8

NLog.Web.AspNetCore:

NuGet\Install-Package NLog.Web.AspNetCore -Version 5.3.8

Microsoft.Data.SqlClient:

NuGet\Install-Package Microsoft.Data.SqlClient -Version 5.2.0

2、准备配置文件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="Logs\NLog\nlog-internal-AspNetCore.txt">

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

  <!-- the targets to write to -->
  <targets>
     <!--文件中写入,File Target for all log messages with basic details--> 
    <target xsi:type="File" name="allfile" fileName="Logs\NLog\nlog-AspNetCore-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />

     <!--File Target for own log messages with extra web details using some ASP.NET core renderers--> 
    <target xsi:type="File" name="ownFile-web" fileName="Logs\NLog\nlog-AspNetCore-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

    <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection--> 
    <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />


    <!--数据库中写入-->
    <!--新建表:
    CREATE TABLE [dbo].[NLog] (
        [Id] [int] IDENTITY(1,1) NOT NULL,
      [MachineName] [nvarchar](50) NOT NULL,
        [Logged] [datetime] NOT NULL,
        [Level] [nvarchar](50) NOT NULL,
        [Message] [nvarchar](max) NOT NULL,
        [Logger] [nvarchar](250) NULL,
      [CallSite] [nvarchar](50) NOT NULL,
        [Exception] [nvarchar](max) NULL,
      CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([Id] ASC)
        WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    -->
    <!--执行下面命令安装System.Data.SqlClient-->
    <!--NuGet\Install-Package System.Data.SqlClient -Version 4.8.6-->
    <target name="db" xsi:type="Database">
      <!-- 连接字符串 -->
      <connectionString>data source=;initial catalog=demo1;User ID=;Password=</connectionString>
      <!-- Insert语句 -->
      <commandText>
        insert into dbo.NLog (MachineName,Logged,Level,Message,Logger,Callsite,Exception) values (@MachineName,@Logged,@Level,@Message,@Logger,@Callsite,@Exception);
      </commandText>
      <!-- 格式化参数 -->
      <parameter name="@MachineName" layout="${machinename}" />
      <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}" />
      <parameter name="@Exception" layout="${exception:tostring}" />
    </target>
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <logger name="*" minlevel="Trace" writeTo="db" />

    <!--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="Info" final="true" />
    <logger name="System.Net.Http.*" maxlevel="Info" final="true" />

    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

另一种配置文件:

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <variable name="myvar" value="myvalue"/>
  <!--
  CREATE TABLE [dbo].[NLog](
  [Id] [int] 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](50) NULL,
  [Exception] [nvarchar](max) NULL,
  CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED
  (
  [Id] ASC
  )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
  ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  -->
  <targets>
    <target name="AllDatabase" xsi:type="Database"
              dbProvider="System.Data.SqlClient.SqlConnection,System.Data.SqlClient"
              connectionString="Data Source=;Initial Catalog=demo1;User ID=;Password=;"
              commandText="insert into dbo.NLog (Application, Logged, Level, Message,Logger, CallSite, Exception) values (@Application, @Logged, @Level, @Message,@Logger, @Callsite, @Exception);">
      <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>

    <target xsi:type="File" name="allfile" fileName="Logs\NLog\nlog-all-${shortdate}.log"
                layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
    <!--同样是将文件写入日志中,写入的内容有所差别,差别在layout属性中体现。写入日志的数量有差别,差别在路由逻辑中体现-->
    <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>

    <!--路由顺序会对日志打印产生影响。路由匹配逻辑为顺序匹配。-->
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip Microsoft logs and so log only own logs-->
    <!--以Microsoft打头的日志将进入此路由,由于此路由没有writeTo属性,所有会被忽略-->
    <!--且此路由设置了final,所以当此路由被匹配到时。不会再匹配此路由下面的路由。未匹配到此路由时才会继续匹配下一个路由-->

    <logger name="Microsoft.*" minlevel="Trace"  final="true" />
    <!--上方已经过滤了所有Microsoft.*的日志,所以此处的日志只会打印除Microsoft.*外的日志-->
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />

    <!-- add your logging rules here -->
    <logger name="*" minlevel="Trace" writeTo="AllDatabase" />


    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
  </rules>
</nlog>

3、在Program.cs中配置

NLog.LogManager.Setup().LoadConfigurationFromFile("CfgFile/NLog.Config").GetCurrentClassLogger();
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
builder.Host.UseNLog();

4、使用:在需要记录日志的Controller中添加

private readonly ILogger<A01BaseController> _logger;

public A01BaseController(ILogger<A01BaseController> logger)
{
    _logger = logger;

    _logger.LogInformation($"LogInformation: {this.GetType().FullName}被构造...");
    _logger.LogError($"LogError: {this.GetType().FullName}被构造...");
    _logger.LogDebug($"LogDebug: {this.GetType().FullName}被构造...");
    _logger.LogWarning($"LogWarning: {this.GetType().FullName}被构造...");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄健华Yeah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值