Skip to content

Instantly share code, notes, and snippets.

@karkianish
Last active July 31, 2018 19:47
Show Gist options
  • Save karkianish/e265cfd14b0b490e40b25b04b0fdad13 to your computer and use it in GitHub Desktop.
Save karkianish/e265cfd14b0b490e40b25b04b0fdad13 to your computer and use it in GitHub Desktop.
public class ErrorLoggerMiddleware
{
private readonly RequestDelegate m_NextDelegate;
private readonly IEventLogger m_EventLogger;
private readonly IDbLogger m_DbLogger;
public ErrorLoggerMiddleware(RequestDelegate next, IEventLogger eventLogger, IDbLogger dbLogger)
{
m_NextDelegate = next;
m_EventLogger = eventLogger;
m_DbLogger = dbLogger;
}
public async Task Invoke(HttpContext context)
{
bool isApiRequest = context.Request.Path.Value.Contains("/api");
if (isApiRequest)
{
// thanks to the SO post - https://stackoverflow.com/questions/37855384/how-to-log-the-http-response-body-in-asp-net-core-1-0/38275942#38275942
string requestBodyText = string.Empty;
try
{
Stream originalBody = context.Request.Body;
using (StreamReader reader = new StreamReader(context.Request.Body))
{
requestBodyText = await reader.ReadToEndAsync();
context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(requestBodyText));
await m_NextDelegate.Invoke(context);
context.Request.Body = originalBody;
}
}
catch (Exception e)
{
// provide own implementation
m_DbLogger.TryLog(context, e);
m_EventLogger.TryLog(context, e, requestBodyText);
context.Response.ContentType = "application/json";
context.Response.StatusCode = 500;
PostResult response = new PostResult();
response.FatalException = true;
await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
}
}
else
{
await m_NextDelegate.Invoke(context);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment