[LibLog] 使用標準 LogProvider 接口

  • 3390
  • 0
  • Log
  • 2020-10-28

我是在 Hangfire 發現這個套件,說真的有點晚認識這個套件了,它已經停用,作者已經建議改用 Microsoft.Extensions.Logging.Abstractions,不過它對於還停留在 .NET Framework 的專案仍然很有用

簡介

LibLog 現在已經棄用 (see #270). 作者已經建議改用 Microsoft.Extensions.Logging.Abstractions,因為它現在是 .NET 生態系統中的事實上的標準日誌記錄接口...

包含對NLog,Log4Net,Serilog 和 Loupe 的支持

節錄部分自:https://github.com/damianh/LibLog

使用方式

Install-Package LibLog -Version 4.2.6 by .NET Framework

Install-Package LibLog -Version 5.0.8 by .NET Core

Install-Package NLog

Install-Package NLog.Config

Install-Package NLog.Schema

安裝套件後就可以使用 LogProvider,它會自動的掃描你用了哪些 Log Provider

[TestMethod]
public void TestMethod1()
{
    var logger = LogProvider.GetCurrentClassLogger();
    logger.Debug("Debug");
}

 

更多的語法請參考:

https://github.com/damianh/LibLog/wiki/Using

 

設定 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"
      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"/>

  <!--
  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}" />
    -->
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />

  </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" />
    -->
    <logger name="*" minlevel="Debug" writeTo="f" />

  </rules>
</nlog>

 

.NET Framework Project

安裝套件 Install-Package LibLog -Version 4.2.6

安裝套件後會在你的專案產生一個處理 Log 的抽象物件,會以你的專案名稱作為增加一個 Logging 命名空間,檔名為 LibLog.cs

 

.NET Core Project

安裝套件 Install-Package LibLog -Version 5.0.8

LogProvider 的命名空間,會隨著你的 Default Namespace 改變而改變。在專案裡面也看不到 LibLog.cs 檔案了,使用方式仍然不變

 

使用心得

這個套件對程式碼並沒有帶來太大的改變,對於不同的 Log Provider 有一致性的寫法相當的漂亮

 

範例位置

https://github.com/yaochangyu/sample.dotblog/tree/master/LibLog/Lab.LibLogForNLog

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo