2015年2月7日 星期六

Class for Dynamic Logger using C# & log4net.



有時候Asp.net 、web service或寫 C# 會需要紀錄程式的log,

自己寫個文字檔當記錄也是可以,但是如果有現成的就不用自己刻。

這裡整理一下log4net的幾種用法,做為參考


本篇介紹Asp.net WebApplication 有IIS的case

如果你有先玩過log4net再來看這篇!!!





網路上教學很多都是需要在Global.asax 上啟用

這會遇到一個問題,如果IIS(機器)在人家手上,可不能給我上線每次說啟用就啟用

有時候軟重啟(ReStart)IIS 都要求人家幫你開,太痛苦了...

正在run 又要同時上新功能的也不可能讓你把IIS停下來

如果你所有的common log都是寫在同一個log file

你也不太可能在新上版的程式裡隨意的加上Shutdown

log.Logger.Repository.Shutdown();
然後每次呼叫方法時,都開開關關這樣,

這樣搞,共用log有可能被你關掉導致其他程式無法寫入


下面提供一個範例,Dyamic Logger動態的產生一個實體Logger

範例中的寫法不需要吃外部Xml config,

要吃也可以啦,看你要吃什麼設定檔什麼參數,

拉出去吃Web.config或自訂XML都可以。





using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using log4net;
using System.Reflection;
//using log4net.Config;
//using log4net.Repository.Hierarchy;
//using log4net.Appender;
//using log4net.Layout;
//using log4net.Core;

namespace WebApp_log4net
{

    public class HandlerforLog : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            Write("Application is starting");
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }

        public void Write(String message)
        {
            ILog myLog = GetDyamicLogger();
            myLog.Info("[Write]:" + message);
        }

        public static ILog GetDyamicLogger()
        {
            log4net.Repository.Hierarchy.Hierarchy hierarchy = 
            (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();
            log4net.Appender.RollingFileAppender roller = 
              new log4net.Appender.RollingFileAppender();
            roller.LockingModel = new log4net.Appender.FileAppender.MinimalLock();
            roller.AppendToFile = true;
            roller.RollingStyle = 
               log4net.Appender.RollingFileAppender.RollingMode.Composite;
            roller.MaxSizeRollBackups = 29; // 0~29 is 30. 
            roller.MaximumFileSize = "10MB";
            roller.DatePattern = "yyyyMMdd";
            roller.Layout = new log4net.Layout.PatternLayout();
            roller.File = "log\\debug.log";
            roller.StaticLogFileName = true;

            log4net.Layout.PatternLayout patternLayout = 
                  new log4net.Layout.PatternLayout();
            patternLayout.ConversionPattern = 
             @"%date [%thread] %-5level %logger [%property{NDC}] - %message%newline";
            patternLayout.ActivateOptions();

            roller.Layout = patternLayout;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            hierarchy.Root.Level = log4net.Core.Level.All;
            hierarchy.Configured = true;

            DummyLogger dummyILogger = new DummyLogger("LogName");
            dummyILogger.Hierarchy = hierarchy;
            dummyILogger.Level = log4net.Core.Level.All;
            dummyILogger.AddAppender(roller);

            return new log4net.Core.LogImpl(dummyILogger);
        }

        internal sealed class DummyLogger : log4net.Repository.Hierarchy.Logger
        {
            // Methods
            internal DummyLogger(string name)
                : base(name)
            {
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}




參考資料

http://amolgangawane.blogspot.tw/

http://www.howtosolvenow.com/2014/01/log4net-example-in-c-console-application/

http://www.curlette.com/?p=1113

http://interactivelogic.net/wp/2010/02/aspnet-logging-to-output-window-with-log4net/

http://weblogs.asp.net/stevewellens/log4net-log-to-a-javascript-console

http://www.howtosolvenow.com/2014/01/log4net-example-in-c-console-application/


熱門文章