【问题标题】:log4net configuration for Event Logging事件记录的 log4net 配置
【发布时间】:2011-04-21 13:34:38
【问题描述】:

我正在尝试通过添加一个包装 log4net 的独立项目来启用解决方案范围的日志记录。我在 StackOverflow 上找到了一个代码,但该代码使用了一些配置文件。我不明白那一点。这是唯一的静态类:

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>

当我使用&lt;appender-ref ref="LogFileAppender" /&gt; 运行时,我在主EXE 旁边得到一个名为Excite Engine 2 Log.log 的空文件。当我设置&lt;appender-ref ref="EventLogAppender" /&gt; 时,事件查看器中没有任何反应。此外,还有一个属性:&lt;level value="DEBUG" /&gt; 这真的很困扰我。我想要的是为我的应用程序提供完整的 EventViewer 日志记录,而不管它运行的构建配置如何。

感谢有人可以指导我。谢谢!

【问题讨论】:

  • level value="DEBUG" 与您的构建配置无关,这意味着它将在 DEBUG 及更高级别(DEBUG、INFO、WARN、ERROR、FATAL)进行日志记录。

标签: winforms c#-4.0 log4net event-log


【解决方案1】:

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

他使用特定配置文件的原因可以通过以下从 log4net 的站点中获取的解释:

System.Configuration API 仅 如果配置数据是可用的 在应用程序的配置文件中;这 名为 MyApp.exe.config 的文件或 网络配置。因为 System.Configuration API 没有 支持重新加载配置文件 配置设置不能 观看使用 log4net.Config.XmlConfigurator.ConfigureAndWatch 方法。使用的主要优点 要读取的 System.Configuration API 配置数据是它 需要的权限少于 访问配置文件 直接地。配置的唯一方法 应用程序使用 System.Configuration API 是调用 这 log4net.Config.XmlConfigurator.Configure() 方法或 log4net.Config.XmlConfigurator.Configure(ILoggerRepository) 方法。

编辑:

要登录到您的日志文件,您需要调用上面的 SetupLogging 方法。

log4net.Config.XmlConfigurator.Configure();

永远不会调用此语句。看起来您正在 ExciteEngine2.LoggingManager 中调用 LoadConfig() ,但这使用了一个名为 log4net.config 的配置文件,您说它不存在。如果您将配置放在 app.config 文件中,则需要调用 SetupLogging 方法。

【讨论】:

  • 好的。说得通。在调用Application.Run()之前,我实际上是在我的主应用程序中调用SetupLogging() 方法
  • 是的,但是您正在调用 XmlConfigurator.ConfigureAndWatch(new FileInfo(LOG_CONFIG_FILE));这很可能会覆盖您的设置。您只需要在应用程序中调用一次配置,并且由于您在 app.config 中拥有所有设置,因此您需要像在 SetupLogging() 中一样调用它
猜你喜欢
  • 2010-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
相关资源
最近更新 更多