log4net 使用與配置 每天一份log檔案

mybwu_com發表於2014-04-24

1.下載 或 在nuget安裝 log4net



2. web.config (app.config)


<configuration>
 
  <configSections>


 <section name="log4net"
           type="log4net.Config.Log4NetConfigurationSectionHandler,
         log4net" />


 </configSections>




 <log4net>
    


    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="C:\m1\eDASLog\%date{dd.MM.yyyy}.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <datePattern value="yyyyMMdd" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[[%date]] - %message %newline" />
    </layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
  
  </log4net>
</configuration>





為了每天一份log檔案,做這個配置(檔案節點型別為PatternString):


<file type="log4net.Util.PatternString" value="C:\m1\eDASLog\%date{dd.MM.yyyy}.txt" />






3. 應用配置,在Application_Start(對於web 應用)中configure():


log4net.Config.XmlConfigurator.Configure();



4.做一個簡單的wrapper來使用:


 public static class EdasLogger
    {
        private static log4net.ILog Log { get; set; }

        static EdasLogger()
        {
            Log = log4net.LogManager.GetLogger(typeof(Logger));
            
        }

        public static void Error(object msg)
        {
            Log.Error(msg);
        }

        public static void Error(object msg, Exception ex)
        {
            Log.Error(msg, ex);
        }

        public static void Error(Exception ex)
        {
            Log.Error(ex.Message, ex);
        }

        public static void Info(object msg)
        {
            Log.Info(msg);
        }
    }



相關文章