【问题标题】:WindsorContainer Construction Error and Logging IssueWindsorContainer 构造错误和日志记录问题
【发布时间】:2012-08-07 11:57:14
【问题描述】:

我正在使用 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");
        }
    }

我有什么选择?

谢谢, 尼尔。

【问题讨论】:

  • 您正在运行什么类型的应用程序? ASP.NET?赢得表格?你是如何部署你的应用程序的。在你的服务器上?在客户端机器上?
  • 当你错误配置你的应用程序时,你应该在测试或登台时发现,但是你不需要捕获和记录,因为你的应用程序不会启动,你可以看到堆栈跟踪在本地访问服务。
  • @Steven 不正确。至少在某些情况下,你只是在某个地方得到null

标签: logging castle-windsor construction


【解决方案1】:

您可以写入 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);
}

【讨论】:

  • 我真的很想在日志中有这个,或者至少可以选择通过 log4net Windsor 工具将它写入事件日志。有什么办法吗?
  • 好吧,如果您的记录器配置不正确,就无法使用它。如果配置正确,您可以简单地调用 log4net 日志记录门面。在你的作文根目录中这样做没有问题。
【解决方案2】:

这确实使人们对使用 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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2011-05-19
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多