public override void OnException(ExceptionContext context) { //如果该异常已被处理则跳过 if (context.ExceptionHandled) { return; } var action = (ControllerActionDescriptor)context.ActionDescriptor; var reqParam = context.Filters.FirstOrDefault(x => x.GetType() == typeof(ModelValidateFilterAttribute)); var model = new ApiErrorLogModel { HttpMethod = context.HttpContext.Request.Method, ControllerName = action.ControllerName, ActionName = action.ActionName, Path = context.HttpContext.Request.Path, User = context.HttpContext.User.Identity.Name, Msg = context.Exception.Message, RequestJson = reqParam != null?JsonConvert.SerializeObject(((ModelValidateFilterAttribute)reqParam).RequestArguments) : null }; var logger = _loggerfactory.CreateLogger($"{context.Exception.TargetSite.DeclaringType}.{context.Exception.TargetSite.Name}"); logger.LogError(context.Exception, model.ToString()); context.Result = new BadRequestObjectResult(new ErrorResponseModel { code = (int)HttpStatusCode.BadRequest, message = context.Exception.Message, detail = context.Exception }); }
private void WriteLog(AuthorizationFilterContext context) { var action = (ControllerActionDescriptor)context.ActionDescriptor; ApiErrorLogModel msg = new ApiErrorLogModel { HttpMethod = context.HttpContext.Request.Method, ControllerName = action.ControllerName, ActionName = action.ActionName, Path = context.HttpContext.Request.Path, Msg = "authentication failed!" }; var logger = _loggerfactory.CreateLogger(context.HttpContext.Request.Path); logger.LogWarning(msg.ToString()); }
private void WriteErrorToLog(ActionExecutingContext context, string errMsg) { var msg = new ApiErrorLogModel(); var action = (ControllerActionDescriptor)context.ActionDescriptor; msg.ControllerName = action.ControllerName; msg.ActionName = action.ActionName; msg.HttpMethod = context.HttpContext.Request.Method; msg.Path = context.HttpContext.Request.Path; msg.User = context.HttpContext.User.Identity.Name; msg.RequestJson = JsonConvert.SerializeObject(context.ActionArguments); msg.Msg = errMsg; var logger = _loggerfactory.CreateLogger(context.Controller.ToString()); logger.LogError(msg.ToString()); }