Log4Net是否在App对象中? [英] Log4Net in App object?

查看:62
本文介绍了Log4Net是否在App对象中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用Log4Net作为日志记录组件在WPF桌面应用程序中进行日志记录.这是我的问题:在一个简单的桌面应用程序中,有没有理由不像这样将应用程序类(App.xaml.cs)的属性实例化为记录器呢?

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

这将允许我调用记录器

推荐答案

一个想到的原因:由于App类的静态构造函数是将要运行的代码的第一位,因此您将实例化ILog配置log4net之前的实例.因此,您的ILog实例将无法使用.通常,您将改为执行以下操作:

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

顺便说一句,MethodBase业务确实让我畏缩.为什么不只使用typeof(App)?无论如何,您不应该在未经验证的情况下复制/粘贴代码... 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...

这篇关于Log4Net是否在App对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆