Configuring from code

This post has been adapted as part of our official documentation. To read the most updated version, please check out Configure from code

@saxx wrote an excellent question on Twitter:

@elmah_io Is there a nice way to move the config (LogId) from web.config into the code? I want to push my web.config into public GitHub.
— saxx (@saxx) September 2, 2013

So the question really boils down to this: Can I configure through C# code? Sure! With a little help from ELMAH and some custom code, you will be able to configure any ELMAH error logger through code. Here’s what @saxx ended up implementing:

using Elmah;
using System.Collections.Generic;
using System.ComponentModel.Design;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(EvernoteMvcExample.ElmahConfig), "Start")]
namespace EvernoteMvcExample
    public static class ElmahConfig
        public static void Start()
            ServiceCenter.Current = CreateServiceProviderQueryHandler(ServiceCenter.Current);
        private static ServiceProviderQueryHandler CreateServiceProviderQueryHandler(ServiceProviderQueryHandler sp)
            return context =>
                var container = new ServiceContainer(sp(context));
                var config = new Dictionary<string, string>();
                config["LogId"] = Configuration.ElmahLogId;
                var log = new Elmah.Io.ErrorLog(config);
                container.AddService(typeof(ErrorLog), log);
                return container;

The original can be found in the EverMark project on GitHub.

Let’s look at the code. In line 5, the ElmahConfig class is configured as a PreApplicationStartMethod which means, that ASP.NET (MVC) will execute the Start method when the web application starts up. In line 13 the ServiceCenter.Current property is set to the return type of the CreateServiceProviderQueryHandler-method. This method is where the magic happens. Besides creating the new ServiceContainer, we actually created the Elmah.Io.ErrorLog class normally configured through XML. The Dictionary should contain the LogId found on the dashboard of the website. @saxx doesn’t want to show of the LogId on GitHub (understandable), why this is pulled in through configuration. If your code is private, you can hardcode your LogId instead if you like.

That’s it! You no longer need the <elmah> element in your web.config.

This post was brought to you by the team. is the best error management system for .NET web applications. We monitor your website, alert you when errors start happening and help you fix errors fast.

Monitor your website