Skip to content

Exception log for non premium users (ElmahCore)

LSNicholls edited this page Mar 21, 2024 · 11 revisions

Elmah Core github page ElmahCore

only two simple steps to add it in your application

install ElmahCore and ElmahCore.Sql into the project from NuGet Package

add the following classes in Helper folder (Change the namespace as per yours)

namespace QmtPlus.Common.Helpers
{
    using ElmahCore;
    using Microsoft.Extensions.Logging;
    using System;

    public class ElmahLogger : ILogger
    {
        private readonly string _name;

        public ElmahLogger(string name)
        {
            _name = name;
        }

        public IDisposable BeginScope<TState>(TState state) => default;

        public bool IsEnabled(LogLevel logLevel) => true;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (exception != null)
            {
                ElmahExtensions.RaiseError(exception);
            }
        }
    }
}
namespace QmtPlus.Common.Helpers
{
    using Microsoft.Extensions.Logging;
    using System.Collections.Concurrent;

    public class ElmahLoggerProvider : ILoggerProvider
    {
        private readonly ConcurrentDictionary<string, ElmahLogger> _loggers = new ConcurrentDictionary<string, ElmahLogger>();

        public ILogger CreateLogger(string categoryName) =>
            _loggers.GetOrAdd(categoryName, name => new ElmahLogger(name));

        public void Dispose() => _loggers.Clear();
    }
}

add the following code in ConfigureServices of Startup.cs

using ElmahCore.Mvc;
using ElmahCore.Sql;

....

services.AddElmah<SqlErrorLog>(options =>
{
    options.OnPermissionCheck = context => context.User.Identity.IsAuthenticated;
    options.ApplicationName = "QmtPlus";
    options.ConnectionString = Configuration.GetValue<string>("Data:Default:ConnectionString");
    options.SqlServerDatabaseTableName = "ErrorsAndExceptions";
    options.Path = "Exceptions";
});

// Update following code
services.AddLogging(loggingBuilder =>
{
    loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
    loggingBuilder.AddConsole();
    loggingBuilder.AddDebug();
    loggingBuilder.AddProvider(new ElmahLoggerProvider());
});

Add the follwoing code in Configure section of Startup.cs

app.UseElmah();

shoud be added after app.UseAuthorization();

Exception Dashboard can be accessed from your_url/Exceptions, and can be exposed on your menu like this:

// for example in in AdministrationNavigation.cs:

[assembly: NavigationLink(9500,"Administration/Exceptions",url:"Exceptions",
    permission:PermissionKeys.Security,icon: "fa-bug",Target ="_blank")]
Clone this wiki locally