2011-04-21 187 views
0

我試圖通過添加一個包裝log4net的獨立項目來啓用整個解決方案的日誌記錄。我在StackOverflow上找到了一個代碼,但代碼使用了一些配置文件。我不明白這一點。以下是唯一的靜態類:事件日誌記錄的log4net配置

using log4net; 
using log4net.Config; 
using System; 
using System.IO; 

namespace ExciteEngine2.LoggingManager { 

    //// TODO: Implement the additional GetLogger method signatures and log4net.LogManager methods that are not seen below. 
    public static class ExciteLog { 

     private static readonly string LOG_CONFIG_FILE = @"log4net.config"; 

     public static ILog GetLogger(Type type) { 
      // If no loggers have been created, load our own. 
      if (LogManager.GetCurrentLoggers().Length == 0) { 
       LoadConfig(); 
      } 
      return LogManager.GetLogger(type); 
     } 

     private static void LoadConfig() { 
      //// TODO: Do exception handling for File access issues and supply sane defaults if it's unavailable. 
      try { 
       XmlConfigurator.ConfigureAndWatch(new FileInfo(LOG_CONFIG_FILE)); 
      } 
      catch (Exception ex) { 

      }     
     }   

    } 

} 

現在,任何地方都沒有log4net.config。而在我的主要應用程序的項目,我使用的ILog如下:

using log4net; 
using ExciteEngine2.LoggingManager; 

namespace ExciteEngine2.MainApplication { 

    internal static class Program { 

     public static readonly ILog ApplicationLogger = ExciteLog.GetLogger(typeof(Program)); 

     private static void SetupLogging() { 
      log4net.Config.XmlConfigurator.Configure(); 
     } 

     [STAThread] static void Main(string[] args) { 

      //Uninstall 
      foreach (string arg in args) { 
       if (arg.Split('=')[0] == "/u") { 
        Process.Start(new ProcessStartInfo(Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\msiexec.exe", "/x " + arg.Split('=')[1])); 
        return; 
       } 
      } 


       Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); 
       Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB"); 

       Application.EnableVisualStyles(); 
       Application.SetCompatibleTextRenderingDefault(false); 

       Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); 

       try { 
        ThemeResolutionService.ApplicationThemeName = ConfigurationManager.AppSettings["ThemeToUse"]; 
       } 
       catch (Exception ex) { 
        ApplicationLogger.Error("Exception while setting Telerik Theme.", ex); 
        ThemeResolutionService.ApplicationThemeName = "ControlDefault"; 
       } 

       DevExpress.UserSkins.OfficeSkins.Register(); 
       DevExpress.UserSkins.BonusSkins.Register(); 
       DevExpress.Skins.SkinManager.EnableFormSkins(); 
       DevExpress.Skins.SkinManager.EnableMdiFormSkins(); 

       //try { 
       if (args.Contains("/dx")) { 
        Application.Run(new AppMDIRibbonDX()); 
        ApplicationLogger.Info("Application (DX) started."); 

       } 
       else { 
        Application.Run(new AppMDIRibbon()); 
        ApplicationLogger.Info("Application started."); 

       } 
       //} catch (Exception ex) { 
       // ApplicationLogger.Fatal("Exception while initiating. Nothing can be done here.", ex); 
       // XtraMessageBox.Show(String.Format("Exception while initiating. Nothing can be done here.{0}Message: {1}", Environment.NewLine, ex.Message), "Excite Engine 2", MessageBoxButtons.OK, MessageBoxIcon.Error); 

       //} 


     } 

     private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { 
      ApplicationLogger.Fatal("Application Level Exception.", e.Exception); 
      Thread t = (Thread)sender; 
      Exception threadexception = e.Exception; 
      string errormessage = String.Format("Thread ID: {0} [ {1} ]", t.ManagedThreadId, threadexception.Message); 
      XtraMessageBox.Show(String.Format("Application Level Exception!{1}{0}{1}Details:{1}{2}", errormessage, Environment.NewLine, threadexception.StackTrace), "Excite Engine 2", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 

    } 

} 

你可以從我的流程看,我執行這行代碼想log4net的會用我的主要應用項目的app.config :log4net.Config.XmlConfigurator.Configure();

這裏是一個線我在AssemblyInfo.cs中說:

[assembly: log4net.Config.XmlConfigurator(Watch = true)] 

最後,在app.config我的主要應用:

<?xml version="1.0"?> 
<configuration> 

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

    <appSettings> 

    </appSettings> 

    <connectionStrings> 

    </connectionStrings> 

    <startup> 
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" /> 
    </startup> 

    <log4net> 
     <root> 
      <level value="DEBUG" /> 
      <appender-ref ref="LogFileAppender" /> 
     </root> 
     <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" > 
      <param name="File" value="Excite Engine 2 Log.log" /> 
      <param name="AppendToFile" value="true" /> 
      <rollingStyle value="Size" /> 
      <maxSizeRollBackups value="10" /> 
      <maximumFileSize value="10MB" /> 
      <staticLogFileName value="true" /> 
      <layout type="log4net.Layout.PatternLayout"> 
       <param name="ConversionPattern" value="%-5p%d{ddd, dd-MMM-yyyy hh:mm:ss} - %m%n" /> 
      </layout> 
     </appender> 
     <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" > 
      <applicationName value="Excite Engine 2" /> 
      <layout type="log4net.Layout.PatternLayout"> 
       <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> 
      </layout> 
     </appender> 
    </log4net> 

</configuration> 

當我使用<appender-ref ref="LogFileAppender" />運行時,我的主EXE旁邊出現一個名爲Excite Engine 2 Log.log的空文件。當我設置<appender-ref ref="EventLogAppender" />時,事件查看器中沒有任何反應。此外,還有一個屬性:<level value="DEBUG" />這真的困擾着我。我想要的是一個完整的EventViewer記錄我的應用程序,無論其運行的構建配置如何。

欣賞是否有人能指導我這一點。謝謝!

+0

level value =「DEBUG」與您的構建配置無關,這意味着它將在級別DEBUG和更高級別(DEBUG,INFO,WARN,ERROR,FATAL)上記錄。 – 2011-04-21 16:12:26

回答

0

我在StackOverflow上找到了一個代碼,但是 代碼使用了一些配置文件。我 不明白那一點。

他使用一個特定的配置文件,其原因可以從log4net的的網站上看到以下考慮來解釋:

的System.Configuration API僅 可如果配置數據是在應用程序的配置 文件;名爲MyApp.exe.config的 文件或 Web.config。由於 System.Configuration API做配置文件不支持 重裝 配置設置不能 使用 log4net.Config.XmlConfigurator.ConfigureAndWatch 方法觀看。使用 System.Configuration API讀取 配置數據的主要優點在於它的 需要的權限小於 直接訪問配置文件 。配置使用 System.Configuration的API的應用程序 的唯一途徑是調用該 log4net.Config.XmlConfigurator.Configure() 方法或 log4net.Config.XmlConfigurator.Configure(ILoggerRepository) 方法。

編輯:

要登錄到你需要調用你上面的設置→方法您的日誌文件。

log4net.Config.XmlConfigurator.Configure(); 

該聲明永遠不會被調用。它看起來像是在你的ExciteEngine2.LoggingManager中調用LoadConfig(),但是它使用了一個名爲log4net.config的配置文件,你所說的配置文件不存在。如果你把你的配置放在你的app.config文件中,那麼你需要調用你的SetupLogging方法。

+0

好的。說得通。實際上,在我調用'Application.Run()' – DoomerDGR8 2011-04-25 09:32:21

+0

之前,我調用了主應用程序中的'SetupLogging()'方法是的,但是你調用了XmlConfigurator.ConfigureAndWatch(new FileInfo(LOG_CONFIG_FILE));這很可能會覆蓋您的設置。您只需要在應用程序中調用一次配置,並且由於您擁有app.config中的所有設置,您需要像在SetupLogging()中那樣調用它, – 2011-04-25 11:35:10