• .NET Core+NLog+存储配置 日志存入到数据库


    nlog-config.xml 配置文件:

    <?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="false"
          internalLogLevel="info"
          internalLogFile="Logs/SysNlog.log">
    
      <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
      </extensions>
    
      <targets>
        <target name="db"
                xsi:type="Database"
                connectionString="${var:NLOG_CONNECTION_STRING}"
                commandType="StoredProcedure"
                commandText="[dbo].[SP_InsertLog]">
          <parameter name="@traceId" layout="${aspnet-TraceIdentifier}" />
          <parameter name="@eventId" layout="${event-properties:EventId}" />
          <parameter name="@user" layout="${aspnet-user-identity}" />
          <parameter name="@application" layout="APP_WEB" />
          <parameter name="@level" layout="${level}" />
          <parameter name="@category" layout="${logger}" />
          <parameter name="@message" layout="${message}" />
          <parameter name="@properties" layout="${all-event-properties:separator=|}" />
          <parameter name="@exception" layout="${exception:tostring}" />
          <parameter name="@clientIP" layout="${aspnet-request-ip}" />
          <parameter name="@addTime" layout="${date:universalTime=True}" />
        </target>
      </targets>
    
      <rules>
        <logger name="*" minlevel="Trace" writeTo="db" />
      </rules>
    </nlog>

     appsettings.json配置

    {
      "ConnectionStrings": {
        "testDatabase": "Data Source=(local); Initial Catalog=TestDB; User Id=sa; Password=Sa; MultipleActiveResultSets=True;",
        "LogDatabase": "Data Source=(local); Initial Catalog=TestDB_Log; User Id=sa; Password=Sa; MultipleActiveResultSets=True;"
      },
     "Encoding": "GBK",
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Microsoft.AspNetCore.Mvc": "Warning",
          "Microsoft.EntityFrameworkCore": "Warning",
          "Default": "Information"
        }
      }
    }

     STARTUP.CS

            //  NLog 数据库配置
                NLog.LogManager.Configuration.FindTargetByName<DatabaseTarget>("db").ConnectionString = Configuration.GetConnectionString("LogDatabase");
    
    

     存储:

    
    
    create procedure [dbo].[SP_InsertLog](
        @traceId nvarchar(32),
        @eventId int,
        @user nvarchar(450),
        @application nvarchar(450),
        @level nvarchar(8),
        @category nvarchar(450),
        @message nvarchar(max),
        @properties nvarchar(max),
        @exception nvarchar(max),
        @clientIP nvarchar(450),
        @addTime datetime
    )
    as
    begin
        insert into dbo.[LogTable]([TraceId],[EventId], [User], [Application], [Level], [Category], [Message], [Properties], [Exception], [ClientIP], [AddTime]) 
            values(@traceId, @eventId, @user, @application, @level, @category, @message, @properties, @exception, @clientIP, @addTime);
    end

     Program.cs

     public class Program
        {
            public static void Main(string[] args)
            {
                var logger = NLogBuilder.ConfigureNLog("Log/nlog-config.xml").GetCurrentClassLogger();
                try
                {
                    CreateWebHostBuilder(args).Build().Run();
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "异常信息");
                    throw;
                }
                finally { NLog.LogManager.Shutdown(); }
            }
    
            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                    .UseStartup<Startup>()
                    .UseNLog();
        }
  • 相关阅读:
    解决ajax 发送post 请求时csrf_token 问题
    pip 常用命令
    mac 查看端口的使用情况
    使用from __future__ import unicode_literals
    git 使用
    django rest_framework
    Apache JMeter 接口压力测试
    HTTP 协议
    自定义异步非阻塞web框架
    WebSocket
  • 原文地址:https://www.cnblogs.com/Warmsunshine/p/9817758.html
Copyright © 2020-2023  润新知