Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added logging and global exception handling features #14

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Core/Eisk.Core/Eisk.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="log4net" Version="2.0.8" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.3" />
</ItemGroup>
Expand Down
48 changes: 48 additions & 0 deletions Core/Eisk.Core/Exceptions/GlobalExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Eisk.Core.Logger;
using Eisk.Domains.Entities;

namespace Eisk.Core.Exceptions
{
public class GlobalExceptionHandler
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;

public GlobalExceptionHandler(RequestDelegate next, ILogger logger)
{
this._next = next;
this._logger = logger;
}

public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch(Exception exception)
{
_logger.Error($"Error in processing request: {exception}");
await HandleExceptionAsync(httpContext, exception);
}
}

private Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;

return context.Response.WriteAsync(new ErrorDetails()
{
ErrorCode = context.Response.StatusCode,
ErrorMessage = exception.Message
}.ToString());
}


}
}
56 changes: 56 additions & 0 deletions Core/Eisk.Core/Logger/Logger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;

namespace Eisk.Core.Logger
{
//wrapper for logger class
public interface ILogger
{
void Info(string message);
void Warn(string message);
void Debug(string message);
void Error(string message);
}

/// <summary>
/// Responsible for global logging
/// </summary>
public class Logger : ILogger
{
private ILog _logger;

public Logger()
{
this._logger = LogManager.GetLogger(Assembly.GetCallingAssembly(), "logger");
}

public Logger(Type logClass)
{
this._logger = LogManager.GetLogger(logClass);
}

public void Debug(string message)
{
_logger.Debug(message);
}

public void Error(string message)
{
_logger.Error(message);
}

public void Info(string message)
{
_logger.Info(message);
}

public void Warn(string message)
{
_logger.Warn(message);
}
}
}

15 changes: 15 additions & 0 deletions DomainCore/Eisk.Domains/Entities/ErrorDetails.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Newtonsoft.Json;

namespace Eisk.Domains.Entities
{
public class ErrorDetails
{
public int ErrorCode { get; set; }
public string ErrorMessage { get; set; }

public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
2 changes: 1 addition & 1 deletion WebApi/Eisk.WebApi/Controllers/EmployeesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class EmployeesController : WebApiControllerBase<Employee,int>
{
public EmployeesController(EmployeeDomainService employeeDomainService):base(employeeDomainService)
{

throw new System.Exception("test");
}
}
}
1 change: 1 addition & 0 deletions WebApi/Eisk.WebApi/Eisk.WebApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="log4net" Version="2.0.8" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.9" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
</ItemGroup>
Expand Down
9 changes: 8 additions & 1 deletion WebApi/Eisk.WebApi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
using Microsoft.AspNetCore;
using System.Reflection;
using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using log4net;
using log4net.Config;

namespace Eisk.WebApi
{
public class Program
{
public static void Main(string[] args)
{
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

BuildWebHost(args).Run();
}

Expand Down
8 changes: 8 additions & 0 deletions WebApi/Eisk.WebApi/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ namespace Eisk.WebApi
using DataServices.Interfaces;
using DomainServices;
using EFCore.Setup;
using Eisk.Core.Exceptions;
using Eisk.Core.Logger;

public class Startup
{
Expand Down Expand Up @@ -46,6 +48,9 @@ public void ConfigureServices(IServiceCollection services)

services.AddTransient<EmployeeDomainService>();

//Logging service
services.AddSingleton<ILogger, Logger>();

services.AddMvc();

// Register the Swagger generator, defining 1 or more Swagger documents
Expand Down Expand Up @@ -77,6 +82,9 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseDeveloperExceptionPage();
}

//global exception middleware
app.UseMiddleware<GlobalExceptionHandler>();

// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();

Expand Down
19 changes: 19 additions & 0 deletions WebApi/Eisk.WebApi/log4net.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="logfile.log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p - %m%n" />
</layout>
</appender>
<root>
<!--LogLevel: OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
<level value="ALL" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
</configuration>