Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4Net in App object?

Tags:

wpf

log4net

I am getting started with Logging in a WPF desktop app, using Log4Net as the logging component. Here is my question: In a simple desktop app, is there any reason not to instantiate my logger as a property ov the App class (App.xaml.cs), like this?

public partial class App : Application
{
        private static readonly ILog p_Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public ILog Logger
        {
            get { return p_Logger; }
        }

        #endregion
    }
}

That would allow me to invoke the logger

like image 508
David Veeneman Avatar asked Mar 29 '10 17:03

David Veeneman


1 Answers

One reason springs to mind: since the App class's static constructor is the first bit of your code that will run, you will be instantiating the ILog instance before you've configured log4net. Therefore, you ILog instance won't be usable. Generally, you would instead do something like this:

public partial class App : Application
{
    private static ILog log;

    static App()
    {
        XmlConfigurator.Configure();
        log = LogManager.GetLogger(typeof(App));
    }
}

BTW, that MethodBase business really makes me cringe. Why not just use typeof(App)? You shouldn't be copy/pasting code without verifying it, anyway...and typeof(App) will work just fine with refactoring tools...

like image 147
Kent Boogaart Avatar answered Sep 30 '22 14:09

Kent Boogaart