Format the email subject in the Elmah Error Logging Module

Elmah error logging modules and handlers for ASP.NET is a great module for logging asp.net errors to many different and configurable repositories.  One of the repositories that Elmah works with is email. You can easily set up Elmah to send emails by changing the elmah configuration section in your web.config.

You can find a sample of all the different elmah web.config settings here.  The email configuration settings are the following:

<errorMail 
  from="elmah@example.com" 
  to="admin@example.com" 
  subject="..."
  async="true|false"
  smtpPort="25"
  smtpServer="smtp.example.com" 
  userName="johndoe"
  password="secret" 
  noYsod="true|false" />

Only the from and to settings are required. If you leave off the subject attribute you will get the default subject line which is something like this:

Error (System.Exception): This is a test exception

Which is made up of the type of exception followed by the exception message:

Error (Exception.Type): Exception.Message

But did you know you can configure the subject line with these pieces of information and also add something more specific for the application you are working on?  For example, I always like the Exception Message in my error email prefixed by the application name and the environment.  For example:

My Web Application (STAGING): This is a test exception

You can do that by specifying the String.Format parameters in the configuration section subject attribute like this:

<errorMail 
  from="elmah@example.com" 
  to="admin@example.com" 
  subject="My Web Application (STAGING): {0}"
  />

Now the Exception Message will replace the {0} in the email subject and you can more easily filter the emails that appear in your inbox (hopefully though there will not be so many).  You can also include the Exception Type by adding {1} to the subject anywhere you want.

Here is the line of code from the Elmah project:

mail.Subject = string.Format(subjectFormat, error.Message, error.Type).Replace('\r', ' ').Replace('\n', ' ');

Technorati Tags:



4 Comments

Comments have been disabled for this content.