Using Sitecore.Logging to send emails

BACKGROUND
In this post I will show you how to send an email using the Sitecore.Logging namespace.

If you want to get straight to the code here you go!

PROBLEM WE NEED TO SOLVE
Do you need to send emails when something happens in your Sitecore website?  For example, if you get a critical error and want to email this to a distribution list?       Using Sitecore.Diagnostics you can log this error to the Sitecore log, but you still need that email sent to get someone working on the issue asap!

Many solutions exist to fit this need.  You can use System.Net, you can use nLog or a plethora of other logging systems.

But why not use what you already have with Sitecore?    Sitecore went ahead and wrapped up the log4net code inside their own dll,  Sitecore.Logging.dll.    You can use your favorite .NET decompiler to look at the code.    I use Telerik's Just Decompile to look under the hood of the Sitecore.Logging.dll.  

Remember, adding another dll to the application domain takes up memory and is another API that needs to be maintained and learned.  Granted, logging apis are not rocket science but it is one more thing to maintain and configure.

Hand rolling your own email logger is easy to do,  but by leveraging log4net inside of Sitecore.Logging you can get the goodness of log4net w/o having to code it.   Why write your own configuration section to put in the smtp host,   email from, email to parameters or add some type of token system when log4net has these items for you already.   Sure you can use application settings but then again you need to write code to read these items.

OK - SHOW ME HOW TO DO IT ALREADY
I broke it down into three steps,  you can see the code here.

Step one:   Create a new appender class which extends log4net.Appender.SMTPAppender in Sitecore.Logging.

Step two:   Update your web.config file to add a new appender that points to the class you created in step one.

Step three:  Update your web.config file and add a new logger which points to the appender you created in step one.

Step one is actually optional.  I created a new appender class because I saw that the log4net.Appender.SMTPAppender class was using System.Mail to send emails.  That class is obsolete for sending emails and we should be using System.Net namespace to send emails.

I created a Gist which contains all three steps and how to reference and use the logger.

Good luck and have fun!












Comments

Popular posts from this blog

Why I chose Selenium WebDriver instead of Telerik's free testing framework

Displaying shared content across multiple Sites

Handling the situation where scItemPath does not exist in Sitecore MVC