.Net Core 使用NLog记录日志到文件和数据库的操作方法

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了.Net Core 使用NLog记录日志到文件和数据库的操作方法脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

NLOG 记录日志微软官方推荐使用。

接下来,通过配置日志记录到文件和SQL Server数据库

第一步:首先添加包NLog.config (可通过微软添加包命令Install-Package 包名进行添加,也可以通过管理NuGet程序包进行添加),添加成功后会生成NLog.config配置文件。并对该配置文件进行配置。详细配置可参考GIT上 NLog说明。

一下是我个人配置。

 <&#63;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="Warn"   
        internalLogFile="Logs/nlog-internal.log">
    
   <!--internalLogLevel="Off"-->
   <!-- optional, add some VARiables
   https://github.COM/nlog/NLog/wiki/Configuration-file#variables
   -->
   <variable name="myvar" value="myvalue"/>
 
   <!--
   See https://github.com/nlog/nlog/wiki/Configuration-file
   for information on customizing logging rules and outputs.
    -->
   <targets>
 
     <!--
     add your targets here
     See https://github.com/nlog/NLog/wiki/Targets for possible targets.
     See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
     -->
 
     <!--
     Write events to a file with the date in the filename.
     <target xsi:tyPE="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
             layout="${longdate} ${uppercase:${level}} ${message}" />
     -->
 
     <!-- write logs to file -->
     <target xsi:type="File" name="allfile" fileName="Logs/${date:format=yyyyMM}/nlog-all-${shortdate}.log"
              layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline}" />
 
     <target xsi:type="File" name="ownFile-web" fileName="Logs/${date:format=yyyyMM}/nlog-own-${shortdate}.log"
              layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline} --- |url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
 
     <target xsi:type="Null" name="blackhole" />
 
     <target xsi:type="Database" name="database">
       <connectionString>${var:connectionString}</connectionString>
       <commandText>
         insert into Syslogs (Application,Levels,operatingtime,Operatingaddress,Userid,Logger,Callsite,Requesturl,Referrerurl,Action,Message,Exception)
         values (@application,@levels,@operatingtime,@operatingaddress,@userid,@logger,@callSite,@requesturl,@referrerurl,@action,@message,@exception);
       </commandText>
       <parameter name="@application" layout="WebApi" />
       <parameter name="@levels" layout="${level}" />
       <parameter name="@operatingTime" layout="${date}" />
       <parameter name="@operatingaddress" layout="${aspnet-Request-IP}" />
       <parameter name="@userid" layout="1" />
       <parameter name="@logger" layout="${logger}" />
       <parameter name="@callSite" layout="${callsite}" />
       <parameter name="@requesturl" layout="${aspnet-request-url}" />
       <parameter name="@referrerurl" layout="${aspnet-request}" />
       <parameter name="@action" layout="${aspnet-mvc-action}" />
       <parameter name="@message" layout="${message}" />
       <parameter name="@exception" layout="${exception:tostring}" />
     </target>
     
   </targets>
 
   <rules>
     <!-- add your logging rules here -->
 
     <!--
     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" />
     -->
 
     <!--All logs, including From Microsoft-->
     <!--minlevel 改为Trace 跟踪全部 Error 只捕获异常-->
     <logger name="*" minlevel="Error" writeTo="allfile" />
 
     <!--skip Microsoft logs and so log only own logs-->
     <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
     <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
     <logger name="*" minlevel="Trace" writeTo="database" />    
     
   </rules>
 </nlog>
 
 
 <!--增加引用
 <PackageReference Include="NLog.extensions.Logging" Version="1.2.1" />
 <PackageReference Include="NLog.Web.AspNetCore" Version="4.6.0" />-->

说明:targets 中有一节点为Database,是配置将日志写入数据库中,注意需要在数据库中添加该记录日志表。

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=192.168.30.133;Initial Catalog=test;User ID=sa;Password=123456;Trusted_Connection=True;multipleActiveResultSets=true;Integrated Security=false;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

第二步:添加包NLog.Web.AspNetCore,在Program.cs中的WebHost加入".UseNLog()"(该属于程序集NLog.Web,需要添加引用using NLog.Web;),即为添加nlog.

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using NLog.Web;

namespace WebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseNLog(); //加入nlog日志
    }
}

第三步:在Startup.cs中的Configure方法中添加记日志代码,即需要加载的配置文件和配置日志写入数据库连接字符串代码。注意:为避免中文乱码问题需要添加System.Text.Encoding.CodePages包。

  public void Configure(IApplicationBuilder app, IHostingenvironment env)
          {
  
              #region Nlog记日志
              //将日志记录到数据库                 config/NLog.config
              NLog.LogManager.LoadConfiguration("nlog.config").GetcurrentClassLogger();       NLog.LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection");   Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);  //避免日志中的中文输出乱码
              #endregion
 
             if (env.IsDevelopment())
                 app.UseDeveloperExceptionPage();
             else
                 app.UseHsts();
   app.UseHttpsredirection();
 
             app.USEMvc();
         }

第四步:使用微软推荐的方式在在构造方法中将将日志对象注入

public class UsersController : Controller
    {
        /// <summary>
        /// 日志对象
        /// </summary>
        private readonly ILogger logger;    
         public UsersController(ILoggerFactory loggerFactory)
        {
            this.logger = loggerFactory.CreateLogger<UsersController>();

            #region 测试日志
            logger.LogTrace("开发阶段调试,可能包含敏感程序数据", 1);
            logger.LogDebug("开发阶段短期内比较有用,对调试有益。");
            logger.LogInformation("你访问了首页。跟踪程序的一般流程。");
            logger.LogWarning("警告信息!因程序出现故障或其他不会导致程序停止的流程异常或意外事件。");
            logger.LogError("错误信息。因某些故障停止工作");
            logger.LogCritical("程序或系统崩溃、遇到灾难性故障!!!");
            #endregion
        }

所有工作完成,运行程序。在配置NLog路径下生成日志文件,同时,在数据库中生成日志。

到此这篇关于.Net Core 使用NLog记录日志到文件和数据库的文章就介绍到这了,更多相关.Net Core记录日志到文件和数据库内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的.Net Core 使用NLog记录日志到文件和数据库的操作方法全部内容,希望文章能够帮你解决.Net Core 使用NLog记录日志到文件和数据库的操作方法所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:.Net