WindsorContainer构造错误和记录问题

时间:2012-08-07 11:57:14

标签: logging castle-windsor construction

我正在使用Castle windsor,并使用配置文件启动它(并且确实希望保留所有内容),这也包含一个日志工具。

当我在初始化时从windsor收到错误(由于配置错误,缺少依赖等),我没有启动记录器,因此 - 无法在任何地方写错误...这是我的代码:

    private static ILogger m_Logger { get; set; } 

    static void Main(string[] args)
    {
        try
        {
            // Windsor has missing dependencies
            var container = new WindsorContainer("windsor.xml");
            // Did not make it here...
            var logger = container.Resolve<ILogger>();
            m_Logger.Debug("Testing 123");
        }
        catch (Exception)
        {
            // Logger was not initialized, null reference exception!
            m_Logger.Debug("Testing 123");
        }
    }

我有什么选择?

谢谢, 尼尔。

2 个答案:

答案 0 :(得分:0)

您可以写入Windows事件日志:

catch (Exception ex)
{
    const string Source = "MySource";
    const string Log = "MyNewLog";

    // Create the source, if it does not already exist.
    if(!EventLog.SourceExists(Source))
    {
        EventLog.CreateEventSource(Source , Log);
    }

    // Create an EventLog instance and assign its source.
    EventLog myLog = new EventLog();
    myLog.Source = Source;

    string eventMessage = string.Empty;

    while (ex != null)
    {
        eventMessage += string.Format("{0}\n{1}\n{2}\n\n",
            ex.GetType().FullName,
            ex.Message,
            ex.SackTrace);
    }

    myLog.WriteEntry(eventMessage);
}

答案 1 :(得分:0)

这真的很好地满足了首先使用IOC容器的所有期望。 无论如何,您可以在catch块中手动创建记录器(例如:log4net)并记录它。

...
catch (Exception)
{
    // Create logger here
    m_Logger = new Log4NetLogger(); // Assuming 'windsor.xml' configured to inject a Log4NetLogger
    m_Logger.Debug("Testing 123");
}