2016年11月16日 星期三

[.NET/Tool] Common.Logging與Log4Net的差異與使用

問題:
專案中會看到同時參考Common.Logging與Log4Net,Log4Net就可以輸出Log了,為何還需要Common.Logging?


說明:
專案是可以互相參考的,專案A使用Log4Net輸出log,專案B卻使用NLog,造成管理的不便,
此時使用Common.Logging可提供抽象,由Log4net等dll來實作這些方法,
可以整合Log4net或NLog等.NET常見的Log函式庫,讓專案間可以使用Common.Logging來當Interface。

使用NuGet加入Common.Logging後,using與建立log物件,如下圖:
在app.config加入Logging Configuration後(使用ConsoleOutLoggerFactoryAdapter),
即可輸出Console。



搭配Log4Net,使用NuGet加入Common.Logging.Log4Net1215(目前最新),NuGet就會自動加入對應的Log4Net版本1.2.15(package version為2.0.5),
一樣需設定Logging Configuration,即可輸出Console。




Logging Configuration需注意的是:
● factoryAdapter內的type屬性,最後的Common.Logging.Log4Net1215版本號需正確。
● factoryAdapter下的ConfigType屬性設為INLINE表示讀取專案app.config內設定,若沒設定該屬性,則須有外部設定檔。

輸出外部log,可使用RollingFileAppender

附上Log4Net版本號與NuGet package version對應,如1.2.15對應NuGet 2.0.5。


參考資料:
http://netcommon.sourceforge.net/docs/2.1.0/reference/html/ch01.html
http://logging.apache.org/log4net/release/config-examples.html
https://cmatskas.com/extend-the-common-logging-api-with-log4net/
https://github.com/net-commons/common-logging/wiki/Common.Logging-Packaging-and-Versions
http://stackoverflow.com/questions/37171988/nuget-package-version-not-matching-reference-version