事件记录的log4net配置

时间:2011-04-21 13:34:39

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

我正在尝试通过添加包装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>

当我使用<appender-ref ref="LogFileAppender" />运行时,我会在主EXE旁边找到一个名为Excite Engine 2 Log.log的空文件。当我设置<appender-ref ref="EventLogAppender" />时,事件查看器中没有任何反应。此外,还有一个属性:<level value="DEBUG" />这真令我烦恼。我想要的是我的应用程序的完整EventViewer日志记录,无论它运行的构建配置如何。

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

1 个答案:

答案 0 :(得分: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)   方法

修改:

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

log4net.Config.XmlConfigurator.Configure();

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