c# - 企业库日志记录应用程序 block - System.InvalidOperationException : The LogWriter is already set

标签 c# asp.net .net enterprise-library error-logging

我正在尝试使用企业库中的日志记录异常处理程序,但偶尔刷新页面时(很明显),我会收到此错误:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.InvalidOperationException: The LogWriter is already set.

代码

protected void Page_Load(object sender, EventArgs e)
        {
            Logger.SetLogWriter(new LogWriterFactory().Create());
            LogEntry entry = new LogEntry();
            entry.Message = "I am logging";
            Logger.Write(entry);

            if (!Page.IsPostBack)
            {
            }
        }           

堆栈跟踪

[InvalidOperationException: The LogWriter is already set.]
Microsoft.Practices.EnterpriseLibrary.Logging.Logger.SetLogWriter(LogWriter logWriter, Boolean throwIfSet) +165
ASPUserManager.Presentation.AspNetUI.GridView.Page_Load(Object sender, EventArgs e) in \AspNetUI\GridView.aspx.cs:20
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

我在想也许我应该检查一下 LogWriter 是否已经设置?

我是 Enterprise Library Logging Application Block 的新手,我不确定如何解决这个问题,有人知道吗?

最佳答案

您只需引导 block 一次——一旦设置了 LogWriter,它就会存储在内部并用于后续的 Write() 调用。通常您会在应用程序启动时执行此操作(例如在 global.asax Application_Start 中)。

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

以上代码加载配置并设置 LogWriter。现在在您的页面中,您可以调用 Logger.Write()。

顺便说一句,SetLogWriter 确实接受一个 bool 值,指示是否在 LogWriter 已设置的情况下抛出,因此您可以覆盖此抛出行为。

但是,在您的情况下,您不想在 Page_Load 中执行此操作。它可能会避免您看到的错误,但在多线程环境(如 Web 应用程序)中,您会(可能)看到其他奇怪的行为,因为 SetLogWriter 会重置内部配置,并且您可能会遇到文件锁定问题或其他问题已处置的 LogWriter。

来源:entlib forums

关于c# - 企业库日志记录应用程序 block - System.InvalidOperationException : The LogWriter is already set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28722771/

相关文章:

c# - Nuget 包 "Not available in this source"... 但 VS 仍然知道它?

c# - 从 .Master Page 中删除 gridview 编辑列

c# - Web API Get 方法参数中的多个 NULL 值

.net - 我可以在 Word 或 Excel 中创建撤消事务吗? (VSTO)

c# - 具有多态数组的 WCF 客户端调用方法失败

c# - DataGridView-如何跳转到搜索中选中的行?

c# - WPF 直接绑定(bind)到 DataContext

c# - 如何使用 C# mongo 驱动程序达到与 python 中的 PyMongo 相同的性能?

c# - 在 Application_End 中处理 Windsor 与在 HttpApplication.Dispose 中处理有何不同?

javascript - 类型错误 : Cannot read property 'get' of undefined (Node. js)