Extensions for various systems in order to demystify exceptions using Ben.Demystify
Current extensions:
- codeessentials.Extensions.Logging.Demystifier
- codeessentials.AspNetCore.Diagnostics.Demystifier
- codeessentials.log4net.Demystifier
Extension to the Microsoft.Extensions.Logging framework to demystify exceptions prior logging.
For ASP.NET Core applications (old style) simply call the AddExceptionDemystifyer()
in ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddExceptionDemystifyer();
...
}
For ASP.NET Core applications using the new style simply call the AddExceptionDemystifyer()
in ConfigureLogging
:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((context, builder) =>
{
builder.AddConfiguration(context.Configuration.GetSection("Logging"))
.AddConsole()
.AddDebug()
.AddExceptionDemystifyer();
})
.UseStartup<Startup>()
.Build();
Or when using the logging framework elsewhere, just extend the LoggerFactory with DemystifyExceptions()
:
var factory = new LoggerFactory().DemystifyExceptions();
factory.AddConsole();
var logger = factory.CreateLogger("Test");
try
{
new SampleExceptionGenerator();
} catch(Exception ex)
{
logger.LogError(ex, "While trying to test");
}
Console.ReadKey();
Middleware for the ASP.NET Core Diagostic system to demystify exceptions
Just add the UseExceptionDemystifier()
call in the Configure
method to demystify exceptions on the middleware stack.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory factory)
{
...
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseExceptionDemystifier();
app.UseBrowserLink();
}
else
{
...
}
...
}
Extension to the log4net library to demystify exceptions. If using log4net as provider within Microsoft.Extensions.Logging library, please use codeessentials.Extensions.Logging.Demystifier
package instead.
Just add the LoggerExtensions.AddExceptionDemystifier()
call after initializing log4net.
static void Main(string[] args)
{
// Set up a simple configuration that logs on the console.
BasicConfigurator.Configure();
// Inject demystifier
LoggerExtensions.AddExceptionDemystifier();
// in order to get this simple test working I've to get the logger after the demystifier was injected
// but this is only for this small sample, your existing code should work as is (e.g. using static ILog members).
var log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
try
{
new SampleExceptionGenerator();
}
catch (Exception ex)
{
log.Error("While trying to test", ex);
}
Console.ReadKey();
}