Warning: Please consider that this post is over 6 years old and the content may no longer be relevant.
The .Net Framework provides an easy way to log messages using the System.Diagnostics.Trace class. By using Trace the user can configure where and what to log in the config file.
Below are two simple ways to log a message to a text file.
The simplest way if you don’t care about the format of the message is to use a filter on the trace listener in app.config to determine which events to log.
Then you only need to call one of the following methods to log a message with a specific EventType.
If you want more control over the format of the message you can use a TraceSwitch in app.config:
Then retrieve the TraceSwitch in code as follows:
The examples are for a desktop application, but they would work equally well in a web application by configuring web.config. Note that web applications aren’t compiled with Trace enabled, so you need to enable them in web.config by using the following after the <system.diagnostics> node: