Adding tracelistener to web.config
Asked Answered
L

1

18

I want to use below code with a website. Which config sections I should add to web.config to log the output into a file or windows eventlog ?

using System.Diagnostics;

// Singleton in real code
Class Logger
{
   // In constructor: Trace.AutoFlush = false;

   public void Log(message)
   {
       String formattedLog = formatLog(message);
       Trace.TraceInformation(formattedLog);
       Trace.Flush();
   }
}
Lenient answered 23/10, 2010 at 13:23 Comment(0)
M
26

You should use system.diagnostics section. Here's example from MSDN for text file:

<configuration>
  <system.diagnostics>
    <trace autoflush="false" indentsize="4">
      <listeners>
        <add name="myListener" 
          type="System.Diagnostics.TextWriterTraceListener" 
          initializeData="TextWriterOutput.log" />
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

This is for system events log: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogtracelistener.aspx

Mcfarlane answered 23/10, 2010 at 14:35 Comment(7)
Logging to windows event-log is not straight forward with asp.net since it requires administrative privileges.Lenient
do you think any changes in the web.config listiners section is required to allow logging into EventLog ?Mcfarlane
do you just need this code on the web config or do you also need the following code? ' Create a trace listener for the event log. Dim myTraceListener As New EventLogTraceListener("myEventLogSource") ' Add the event log trace listener to the collection. Trace.Listeners.Add(myTraceListener) ' Write output to the event log. Trace.WriteLine("Test output")Smokechaser
where will the TextWriterOutput.log file be outputted to?Smokechaser
file will be outputted in the place (folder) where process started. You can also specify full path there.Mcfarlane
I still got no log file output until I turned off custom errors. <system.web><customErrors mode="Off"/> ...Foggia
I would suggest using something like Log4Net. It will give you better control over your logging. Also WARNING: note that the TextWriterTraceListener does not have a max file size! Right now I am looking into a customer complaint that someone left this running and they now have a massive log file! It will just keep going until it fills the drive.Taxation

© 2022 - 2024 — McMap. All rights reserved.