using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using System.Web.Http.Filters; using InventoryTraker.Web.Utilities; using NLog; namespace InventoryTraker.Web.Attributes { // http://stackoverflow.com/questions/15167927/how-do-i-log-all-exceptions-globally-for-a-c-sharp-mvc4-webapi-app public class ExceptionHandlingAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext ctx) { if (ctx != null) { var loggerName = ctx.GetLoggerName(); var username = HttpContext.Current.User.Identity.Name; var @params = string.Join(", ", ctx.ActionContext.ActionArguments.Select(i => $"{i.Key}: {{{i.Value}}}")); LogManager.GetLogger(loggerName) .Info("username: {0}, params: {{{1}}}", username, @params); } throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("An error occurred, please try again or contact the administrator."), ReasonPhrase = "Critical Exception" }); } } }