简体   繁体   中英

Trace.WriteLine() with TextWriterTraceListener eventually stops working on a published ASP.NET site

I'm adding logging using Trace to a new ASP.NET site. When I run the project locally, the logging works as expected. When I publish the project (via a file system publish through Visual Studio), the site will successfully log for a little while (anywhere from a few seconds to several minutes), but then eventually stop writing to the output file.

Here's how I'm initializing my TraceListener in my Global.asax.cs :

protected void Application_Start() 
{  
    textWriterTL = new TextWriterTraceListener(logFilePath);
    Trace.Listeners.Add(textWriterTL);
    Trace.AutoFlush = true;

    ...
}

Later, in a Web API controller method, I write to Trace like so:

Trace.WriteLine("An error occurred").

I don't feel like I'm doing anything unconventional. Why does my site stop logging after a period of time?

It happens because in the Application_Start method you souldn't instance any class, according to MSDN docs:

You should set only static data during application start. Do not set any instance data because it will be available only to the first instance of the HttpApplication class that is created.

I recommend set the TraceListener in Web.config, just like this sample:

<system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add type="System.Diagnostics.TextWriterTraceListener" name="FileListener" initializeData="MyLog.log" />
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>

Reference: https://msdn.microsoft.com/en-us/library/ms178473.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM