Net Core平台靈活簡單的日志記錄框架NLog+SqlServer初體驗


Net Core平台靈活簡單的日志記錄框架NLog+SqlServer初體驗

前幾天分享的"[Net Core平台靈活簡單的日志記錄框架NLog+Mysql組合初體驗][http://www.cnblogs.com/yilezhu/p/9416439.html]" 反響還行。有網友就說有了NLog+MySql的組合,那如果我是用SqlServer怎么使用NLog呢?於是乎,這篇“Net Core平台靈活簡單的日志記錄框架NLog+SqlServer初體驗”就誕生了!關於記錄到文本文件里面的方法上篇文章也已經說明了。而且NLog+SqlServer的組合跟NLog+MySql的組合使用方法很類似知識配置不一樣。因此這篇文章會很精簡,直接講使用了!
作者:依樂祝
本文地址:https://www.cnblogs.com/yilezhu/p/9451282.html

NLog+SqlServer的組合在Net Core中怎么用啊?

  1. 關於怎么安裝,使用,請看我的上篇文章“[Net Core平台靈活簡單的日志記錄框架NLog+Mysql組合初體驗][http://www.cnblogs.com/yilezhu/p/9416439.html]”。用法一樣,只是如果你需要把MySql的程序集改成“System.Data.SqlClient”.依賴項截圖如下所示:

    1533814354906

  2. 打開Nlog.config文件,把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"
           autoReload="true"
          throwExceptions="true"
          internalLogLevel="warn"
          internalLogFile="logfiles/internal-nlog.txt">
      <targets>
        <target xsi:type="Null" name="blackhole" />
        <target name="database" xsi:type="Database"
                  dbProvider="System.Data.SqlClient"
                  connectionString="Data Source=127.0.0.1;Initial Catalog=MiddleData;User ID=lzhu;Password=bl123456;"
                 >
          <!--
    create table NLog (
       Id                   int                  identity,
       Application          nvarchar(50)         null,
       Logged               datetime             null,
       Level                nvarchar(50)         null,
       Message              nvarchar(512)        null,
       Logger               nvarchar(250)        null,
       Callsite             nvarchar(512)        null,
       Exception            nvarchar(512)        null,
       constraint PK_NLOG primary key (Id)
    )
    
    -->
          <commandText>
            insert into nlog (
            Application, Logged, Level, Message,
            Logger, CallSite, Exception
            ) values (
            @Application, @Logged, @Level, @Message,
            @Logger, @Callsite, @Exception
            );
          </commandText>
          <parameter name="@application" layout="NLogTestDemo" />
          <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>
    
      </targets>
    
      <rules>
        <!--Skip Microsoft logs and so log only own logs-->
        <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
        <logger name="NLogTestDemo.*" minlevel="Info" writeTo="database" />
      </rules>
    </nlog>
    
  3. 上面的代碼中我是以寫入SqlServer為例進行的NLog配置。下面就可以進行簡單地使用了。首先需要在。首先在Startup中的Configure中來加入中間件:

     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                //使用NLog作為日志記錄工具
                loggerFactory.AddNLog();
                //引入Nlog配置文件
                env.ConfigureNLog("Nlog.config");
                //app.AddNLogWeb();
                app.UseMvc();
            }
    
  4. 在Program中進行如下配置:

    public class Program
        {
            public static void Main(string[] args)
            {
                CreateWebHostBuilder(args).Build().Run();
            }
    
            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                .UseNLog()
                    .UseStartup<Startup>();
        }
    
  5. 下面就可以在代碼中愉快的玩耍了,

      private readonly Logger nlog = LogManager.GetCurrentClassLogger(); //獲得日志實;
    
            // GET api/values
            [HttpGet]
            public ActionResult<string> Get()
            {
                nlog.Log(NLog.LogLevel.Debug, $"yilezhu測試Debug日志");
                nlog.Log(NLog.LogLevel.Info, $"yilezhu測試Info日志");
                try
                {
                    throw new Exception($"yilezhu故意拋出的異常");
                }
                catch (Exception ex)
                {
    
                    nlog.Log(NLog.LogLevel.Error, ex, $"yilezhu異常的額外信息");
                }
                return "yilezhu的返回信息";
            }
    
  6. 下面運行起來項目,然到數據庫里面就可以看到記錄的日志信息如下所示:

    1533814568292

    這里大家可能會問,為什么沒有Debug信息輸出呢,這是因為我們上面NLog配置設置的記錄日志的最低級別為Info.所以比Info級別小的Debug信息不會記錄。如果想記錄的話就把這個級別設置成Debug或者比Debug小的Trace就可以記錄了。如下圖所示:

    1533303848950

源碼下載

https://download.csdn.net/download/qin_yu_2010/10594141

總結

本文開頭講述了上篇關於“[Net Core平台靈活簡單的日志記錄框架NLog+Mysql組合初體驗][http://www.cnblogs.com/yilezhu/p/9416439.html]”說起,然后引出輕量級簡單易用的NLog+SqlServer組合,並通過一個簡單地api項目講述了NLog+SqlServer組合如何在Net Core中使用。以及SqlServer的建表語句。實例代碼都跟上篇文章很相似。希望能對大家有所參考!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM