如何检查是否设置了 LogWriter?

How to check if LogWriter has been set?

我正在尝试处理从 Enterprise Library 4 升级到 6 后最近弹出的 Enterprise Library 6 LogWriter 异常。

我要么得到:

The LogWriter has not been set for the Logger static class. Set it invoking the Logger.SetLogWriter method.

The LogWriter is already set.

...视情况而定。

问题是它抛出一个 InvalidOperationException 似乎太笼统而无法处理,甚至使用

进行检查
if (Logger.Writer == null)

... 也会产生异常,那么如何检查编写器是否已设置?

根据this CodePlex discussion

The boostrapping behavior of Enterprise Library has changed in Version 6. The impact for the static Logger facade is that you need to set the internal LogWriter (for example at application start)

如果您处于 Web 应用程序场景中,Application_Start() 是这样做的好方法:

protected void Application_Start()
{
    Logger.SetLogWriter(new LogWriterFactory().Create());
}

否则,在 Main() 方法中设置(或在它周围的某个地方——比如,在容器初始化期间)。

感谢您的回答和评论。

我查看了该项目的代码,发现其中没有内置支持此功能的内容。

尽管该项目不再处于开发阶段,但我还是抓住机会发布了一个 feature request

实现此要求的最佳方案是分叉下载它并添加执行检查的逻辑并另外定义特定的异常(参见功能请求):

LogWriterNotSetExceptionLogWriterAlreadySetException

编辑

删除分叉,因为这会影响许可。日志记录应用程序块的所有权尚未转移。 Only Unity and Prism have been transferred.

comment on the notice about the future of Unity,来自 P & P 会员的说法:

For the Logging Application Block, we consider it to be superceded by Semantic Logging (formerly Semantic Logging Application Block or SLAB).

https://github.com/mspnp/semantic-logging

In other words, we do not intend to work on the Logging Application Block and we have no plan to transfer it to new owners.

因此,对于从事新事物的任何人来说,最好的选择就是尝试 Semantic Logging