2012-11-19 31 views
3

我在我的解決方案中使用log4net來滿足我的日誌記錄需求(它有各種類型的項目)。是否需要創建log4net實例/對象?

是否真的需要總是像這樣創建一個實例(又名對象):

private static readonly ILog log = LogManager.GetLogger(typeof(MyApp)); 

還是我做的方式:

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); 

要使用log4net的?沒有其他的選擇,這樣我就不必上課,因此需要更少的複製和粘貼:-)?

回答

5

有了一個小幫手的幫助:

public static class LogGateway 
{ 
    static LogGateway() 
    { 
     XmlConfigurator.Configure(); 
    } 

    public static ILog For(object LoggedObject) 
    { 
     if (LoggedObject != null) 
      return For(LoggedObject.GetType()); 
     else 
      return For((string)null); 
    } 

    public static ILog For(Type ObjectType) 
    { 
     if (ObjectType != null) 
      return LogManager.GetLogger(ObjectType); 
     else 
      return LogManager.GetLogger(string.Empty); 
    } 

    public static ILog For(string LoggerName) 
    { 
     return LogManager.GetLogger(LoggerName); 
    } 
} 

你不重複的代碼,你只是指記錄爲:

... 
LogGateway.For(this).Debug("hello!"); // instance method 
LogGateway.For(typeof(Foo)).Debug("hello!"); // static method 
+0

我想通小(助手)類爲需要。我無法弄清楚如何實現它。感謝您提供這些代碼(片段)。由於這些,我現在在文檔中找到了信息:http://logging.apache.org/log4net/release/sdk/log4net.ILog.html。儘管當我現在看看創建實例的原始代碼時,我會看到「Ilog」,並且在一段時間後我可以找到它。所以再次感謝幫助我解決這個看似簡單的問題。 –