Logging custom errors to elmah.io

This post has been adapted as part of our official documentation. To read the most updated version, please check out Logging errors programmatically.

Some of you may be thinking: “I want to use elmah.io to log some custom errors, but I don’t want to configure ELMAH to log every error on my webserver. Can this be done?” The answer is of course: Yes! The elmah.io NuGet package has some tricks up its sleeve, making it not only an ErrorLog implementation for ELMAH, but also a client you can utilize in your .NET applications. Let me show you how by using a simple example:

Create a new ASP.NET MVC project:

Create new ASP.NET MVC project

Install the elmah.io NuGet package:

Install-Package elmah.io

Add the following code to HomeController.cs:

using System;
using System.Web.Mvc;
using Elmah;
using ErrorLog = Elmah.Io.ErrorLog;
 
namespace WebAppWithCustomLogging.Controllers
{
    public class HomeController : Controller
    {
        private readonly ErrorLog _errorLog;
 
        public HomeController()
        {
            _errorLog = new ErrorLog(
                new Guid("REPLACE WITH YOUR LOG ID"));
        }
 
        public ActionResult Index(int dividend, int divisor)
        {
            var result = 0;
            try
            {
                result = dividend / divisor;
            }
            catch (Exception e)
            {
                _errorLog.Log(new Error(e));
            }
 
            return View(result);
        }
    }
}

In the constructor we create a new instance of the ErrorLog class from the Elmah.Io assembly. The class contain multiple constructors, but if you want to use elmah.io for custom logging, pick the one accepting your Log Id (found at the dashboard on elmah.io). In line 27 we need to log the exception when the division throws an exception. This is done using the Log method of the ErrorLog class.

ErrorLog also provides methods for extracting both single and multiple errors from elmah.io.

elmah.io: Error logging and Uptime Monitoring for your web apps

This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.

See how we can help you monitor your website for crashes Monitor your website