Dealing with Errors During Development
December 18, 2008 Leave a comment
Of course good .NET programming practices have you nest your code within try/catch blocks, so you can still render pages even if there is some bad code within one of the web parts on the page, however, most articles I have seen reference pushing all errors to the Trace log.
This is all well and good in a production environment, but, in a development environment, I find it useful rather than to write errors to the Trace log, and having to dig through thousands of lines of messages (if you are not throttling events that is) in a text file (or using a third party tool – I’ve seen some on CodePlex), write event log entries to the system event log, and keep that open.
Writing events to the system event log is easy – just do the following in your code.
// we need to include the System.Diagnostics namespace using System.Diagnostics; // example try/catch block try { // code here } catch (Exception ex) { Trace.Write(ex); Trace.WriteLine(HttpContext.Current.Request.Url.ToString()); EventLog.WriteEntry("Project List", ex.ToString(), EventLogEntryType.Warning, 2); }
The 4 parameters passed above are
- Source
- String value containing the name of the source application
- Message
- String value containing the error message
- Type (Error, FailureAudit, Information, SuccessAudit, Warning)
- Must be specified by using EventLogEntryType
- Event ID
- Byte value representing an error code
Which will write an event, such as the example shown above to the Application event log.
More on the EventLog class can be found here: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog(VS.80).aspx