首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >事件日志的log4net配置

事件日志的log4net配置
EN

Stack Overflow用户
提问于 2011-04-21 13:34:38
回答 1查看 2.2K关注 0票数 0

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

代码语言:javascript
复制
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如下所示:

代码语言:javascript
复制
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中添加的一行:

代码语言:javascript
复制
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

最后,我的主要应用程序的app.config:

代码语言:javascript
复制
<?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日志记录,而不管它在什么构建配置中运行。

如果有人能在这方面给我指点。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2011-04-21 17:24:01

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

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

只有当配置数据位于应用程序的配置文件中,即名为MyApp.exe.config或Web.config的文件时,System.Configuration API才可用。由于log4net.Config.XmlConfigurator.ConfigureAndWatch API不支持重新加载配置文件,因此无法使用System.Configuration方法监视配置设置。使用System.Configuration API读取配置数据的主要优点是,与直接访问配置文件相比,它所需的权限更少。使用log4net.Config.XmlConfigurator.Configure(ILoggerRepository) API配置应用程序的唯一方法是调用log4net.Config.XmlConfigurator.Configure()方法或System.Configuration方法。

编辑:

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

代码语言:javascript
复制
log4net.Config.XmlConfigurator.Configure();

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5744836

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档