log4net Configuration for console app

荒凉一梦 提交于 2019-12-21 04:02:12

问题


can anyone suggest how to configure the log4net for an console app?

Or at least how/where to catch the Application_Start event? (It seams that some calls are required at this moment)

Thanks in advance!


回答1:


You need to configure it before the first logger is instantiated.

To do so:

  • Your main class (Program.cs) should not have a logger

  • The main method should not reference any classes that have a logger.

  • You can then configure log4net in the main method.

Alternatively you can use a wrapper class to instantiate loggers, that ensures log4net is configured before creating a logger, e.g.:

static class Log4NetHelper
{
    private static bool _isConfigured;

    static void EnsureConfigured()
    {
        if (!_isConfigured)
        {
            ... configure log4net here ...
            _isConfigured = true;
        }
    }

    public static ILog GetLogger(string name)
    {
        EnsureConfigured();
        log4net.ILog logger = log4net.LogManager.GetLogger(name);
        return logger;
    }
}



回答2:


Try writing

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

in AssemblyInfo.cs

That's it!



来源:https://stackoverflow.com/questions/1742078/log4net-configuration-for-console-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!