开发者

log4net configuration for Event Logging

开发者 https://www.devze.com 2023-02-28 02:04 出处:网络
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. He

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开发者_如何学C 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消