Logging to elmah.io from Blazor

To start logging to elmah.io from Blazor, install the following NuGet packages:

Install-Package Blazor.Extensions.Logging
Install-Package Elmah.Io.Extensions.Logging

In the Startup.cs file, add elmah.io logging configuration:

namespace MyBlazorApp
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(builder => builder
                .AddElmahIo(options =>
                {
                    options.ApiKey = "API_KEY";
                    options.LogId = new Guid("LOG_ID");
                })
            );
        }

        ...
    }
}

Replace API_KEY with your API key (Where is my API key?) and LOG_ID with the ID of the log you want messages sent to (Where is my log ID?).

Exceptions can be logged manually, by injecting an ILogger into your view and adding try/catch:

@using Microsoft.Extensions.Logging
@inject ILogger<FetchData> logger

...

@functions {
    WeatherForecast[] forecasts;

    protected override async Task OnInitAsync()
    {
        try
        {
            forecasts = await Http.GetJsonAsync<WeatherForecast[]>("api/SampleData/WeatherForecasts-nonexisting");
        }
        catch (Exception e)
        {
            logger.LogError(e, e.Message);
        }
    }
}

Information and other severities can be logged as well:

@using Microsoft.Extensions.Logging
@inject ILogger<Counter> logger

...

@functions {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
        logger.LogInformation("Incremented count to {currentCount}", currentCount);
    }
}

This article was brought to you by the elmah.io team. elmah.io 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.

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