事件记录的 log4net 配置

发布于 2024-11-03 03:39:50 字数 6836 浏览 3 评论 0原文

我试图通过添加一个包装 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>

当我使用 ,我在主 EXE 旁边得到一个名为 Excite Engine 2 Log.log 的空文件。当我设置 时,事件查看器中没有任何反应。另外,还有一个属性: 这真的很困扰我。我想要的是我的应用程序的完整 EventViewer 日志记录,无论其运行的构建配置如何。

如果有人可以在这方面指导我,我将不胜感激。谢谢!

I'm trying to enable solution-wide logging by adding a stand-alone project that wraps log4net. I found a code on StackOverflow but the code is using some config file. I do not understand that bit. Here is the only static class:

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) {

            }                   
        }         

    }

}

Now, there is no log4net.config anywhere. And in my main application project, I'm using the ILog as follows:

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);
        }

    }

}

As you can see from my flow, I'm executing this line of code thinking log4net will use my main application project's app.config: log4net.Config.XmlConfigurator.Configure();

And here is a line I added in AssemblyInfo.cs:

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

Finally, the app.config for my Main application:

<?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>

When I run with <appender-ref ref="LogFileAppender" />, I get an empty file named Excite Engine 2 Log.log right next to my main EXE. And when I set <appender-ref ref="EventLogAppender" />, nothing happens in Event Viewer. Also, there is an attribute: <level value="DEBUG" /> thats really bothering me. What I want is a full EventViewer logging for my application regardless of the build configuration it is running in.

Appreciate if someone could guide me on this. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清浅ˋ旧时光 2024-11-10 03:39:50

我在 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 方法。

I found a code on StackOverflow but
the code is using some config file. I
do not understand that bit.

The reason he's using a specific config file can be explained by the following taken from log4net's site:

The System.Configuration API is only
available if the configuration data is
in the application's config file; the
file named MyApp.exe.config or
Web.config. Because the
System.Configuration API does not
support reloading of the config file
the configuration settings cannot be
watched using the
log4net.Config.XmlConfigurator.ConfigureAndWatch
methods. The main advantage of using
the System.Configuration APIs to read
the configuration data is that it
requires less permissions than
accessing the configuration file
directly. The only way to configure an
application using the
System.Configuration APIs is to call
the
log4net.Config.XmlConfigurator.Configure()
method or the
log4net.Config.XmlConfigurator.Configure(ILoggerRepository)
method.

Edit:

To log to your log file you need to call your SetupLogging method above.

log4net.Config.XmlConfigurator.Configure();

This statement is never being called. It looks like you are calling LoadConfig() in your ExciteEngine2.LoggingManager but this uses a config file called log4net.config which you said doesn't exist. If you are putting your configuration in your app.config file then you need to call your SetupLogging method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文