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();
   }
}
Xaqron
  • 29,931
  • 42
  • 140
  • 205

1 Answers1

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

TarasB
  • 2,407
  • 1
  • 24
  • 32
  • 3
    Logging to windows event-log is not straight forward with asp.net since it requires administrative privileges. – Xaqron Oct 26 '10 at 03:07
  • do you think any changes in the web.config _listiners_ section is required to allow logging into EventLog ? – TarasB Oct 28 '10 at 07:18
  • 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") – Brian McCarthy May 10 '11 at 15:50
  • where will the TextWriterOutput.log file be outputted to? – Brian McCarthy May 10 '11 at 16:01
  • file will be outputted in the place (folder) where process started. You can also specify full path there. – TarasB Oct 12 '11 at 17:12
  • 1
    I still got no log file output until I turned off custom errors. ... – RobRolls Sep 20 '15 at 07:06
  • 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. – MBentley May 02 '16 at 20:27