[C#] 在Project 中整合Log4net

Logging 決定了一個application 質素. 在適當地方加入log, 會令troubleshooting 事半功倍, 並可以確保application 的效能. 在示範中, 會使用Log4net, 一個常用的logging library.

先建立一個config file, 並命名為log4net.config. 內容如下:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="LogFiles/"/> <!-- File Path-->
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <datePattern value="yyyyMMdd.lo\g"/> <!--log file name-->
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5p %date{yyyy/MM/dd HH:mm:ss} %-20c{1} %-20M %m%n" />
    </layout>
  </appender>
  <root>
    <level value="ALL"/>
    <appender-ref ref="RollingFileAppender"/>
  </root>
</log4net>

之後在App.xml.cs 中, override 原有的 OnStartup() 如下.

 public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(System.IO.Path.GetFullPath("./log4net.config")));
            base.OnStartup(e);
        }
    }

在須要落Log 的class 中, 加入以下property, 須留意是若將它設於base class 中, log的 child class method call 會記下base class 名字.

private static ILog _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

 

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.