事件日志记录的log4net配置

问题描述:

我试图通过添加一个包装log4net的独立项目来启用整个解决方案的日志记录。我在*上找到了一个代码,但代码使用了一些配置文件。我不明白这一点。以下是唯一的静态类:事件日志记录的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

我在*上找到了一个代码,但是 代码使用了一些配置文件。我 不明白那一点。

他使用一个特定的配置文件,其原因可以从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