Build status NuGet Samples

Logging to elmah.io from Blazor

Like Blazor itself, Elmah.Io.Blazor is highly experimental and should not be used for production use.

To start logging exceptions from Blazor, install the NuGet package:

Install-Package Elmah.Io.Blazor -IncludePrerelease

In the Startup.cs file, add the elmah.io integration for Blazor:

...
using Elmah.Io.Blazor;

namespace MyBlazorApp
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(l => l
                .AddElmahIo("API_KEY", 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?).

As of writing this article, Blazor doesn't support global error handling. 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