Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sitecore 500 Error Logging / Alerts

Problem

Currently, I'm looking to serve a custom 500 error page as well as log and alert a web master about the condition that was hit (What URL, stack trace, timestamp, etc.).

I tried defined custom http errors under system configuration, but the error pages were not hit. I am able to handle 404s and their related errors (layoutnotfound).

Question

Should I intercept the context in global.asax to handle the 500 errors and return a custom page? Is there another way with Sitecore to achieve what I'm looking for?

Mainly, I'm looking for best practice of logging / alerts for 500 errors with Sitecore

like image 520
al3xnull Avatar asked Mar 03 '26 05:03

al3xnull


2 Answers

Try using ELMAH.

Here is an article on using it with Sitecore.

like image 150
Forgotten Semicolon Avatar answered Mar 04 '26 18:03

Forgotten Semicolon


Elmah is great and does a good job. You can also use log4net to log exceptions. All you do is add an application_error method in global.asax and you can track all the errors that occur. You can also add different appenders and can log messages in a log file, database and email them.

Here is the code that logs the error and includes some additional information like url and Current sitecore item:

        private static readonly ILog log = LogManager.GetLogger(typeof(Global));
        protected void Application_Error(object sender, EventArgs e)
        {
            if (Context != null)
            {
                Exception error = Context.Server.GetLastError().GetBaseException();
                log.Fatal(
                    GetErrorMessage(), error);
            }
        }
        private string GetErrorMessage()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Application_Error: Unhandled exception has been occured.");
            try
            {
                sb.AppendLine("Current Request: " + Context.Request.RawUrl);
                Sitecore.Data.Items.Item currentItem = Sitecore.Context.Item;
                if (currentItem != null)
                    sb.AppendLine(String.Format("Current Item ({0}): {1}", currentItem.ID, currentItem.Paths.FullPath));
                if (Sitecore.Context.Database != null)
                    sb.AppendLine("Current Database: " + Sitecore.Context.Database.Name);
            }
            catch { } // in no way should we prevent the site from logging the error
            return sb.ToString();

        }

If you want an easy solution I would recommend going with Elmah. If you want to have more control and more logging options you should go with a custom log4net solution.

like image 44
marto Avatar answered Mar 04 '26 17:03

marto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!