企业库日志记录应用程序块 - System.InvalidOperationException:已设置LogWriter

时间:2015-02-25 15:22:36

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

我正在尝试使用企业库中的Logging Exception Handler,但有一段时间我刷新页面(显然),我收到此错误:

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?

我是企业库日志应用程序块的新手,我不知道如何解决这个问题,有没有人有任何想法?

2 个答案:

答案 0 :(得分:4)

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

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

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

Incidently SetLogWriter接受一个布尔值,指示如果已经设置了LogWriter则是否抛出,这样你就可以覆盖这个抛出行为。

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

来源:entlib forums

答案 1 :(得分:2)

您需要将logwritter设置为false Logger.SetLogWriter(logWriterFactory.Create(),假);

默认情况下,throwIfSet设置为true,如果已设置logwriter,则抛出错误。