//<summary>Se ejecuta cuando se produce una excepcion, esta lee los datos de la excepcion y genera un log en la base de datos.</summary> /// <param name="actionExecutedContext">Contexto de ejecucion.</param> public override void OnException(HttpActionExecutedContext actionExecutedContext) { using (IUnitOfWork unitOfWork = new UnitOfWork()) { IRepository <ApiLog> repository = new Repository <ApiLog>(unitOfWork); apiLogService = new ApiLogService(repository); string requestUuid = actionExecutedContext.Request.GetCorrelationId().ToString(); //unitOfWork.BeginTransaction(); try { ApiLog requestLog = apiLogService.FindBy(x => x.Uuid == requestUuid).FirstOrDefault(); if (requestLog != null) { requestLog.Exception = actionExecutedContext.Exception.GetExceptionDetails(); apiLogService.Update(requestLog); } //unitOfWork.Commit(); } catch (Exception e) { //unitOfWork.Rollback(); } base.OnException(actionExecutedContext); } }
public ApiResponseRequestLoggingMiddleware(RequestDelegate next, IApiLogService apiLogService, ILogger <ApiResponseRequestLoggingMiddleware> logger) { _next = next; _apiLogService = apiLogService; _logger = logger; _clearCacheHeadersDelegate = ClearCacheHeaders; }
public AccountBllService(IAccountDalService accountDalService, IApiLogService apiBllService, IMapper mapper, IOptions <AppSettings> appSettings) { _accountDalService = accountDalService; _mapper = mapper; _appSettings = appSettings.Value; _apiBllService = apiBllService; }
public async Task Invoke(HttpContext context, IApiLogService apiLogService) { apiLogService.Log.LogStartTime = DateTime.Now.Millisecond.ToString(); var request = await FormatRequest(context.Request); apiLogService.Log.Request = request; var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream()) { context.Response.Body = responseBody; await _next(context); var response = await FormatResponse(context.Response); apiLogService.Log.Response = response; await responseBody.CopyToAsync(originalBodyStream); } apiLogService.Log.LogEndTime = DateTime.Now.Millisecond.ToString(); apiLogService.Create(apiLogService.Log); }
public ApiLogController(IApiLogService apiLogService) { _apiLogService = apiLogService; }
public async Task Invoke(HttpContext httpContext, IApiLogService apiLogService, ILogger <APIResponseRequestLoggingMiddleware> logger, UserManager <ApplicationUser> userManager) { _logger = logger; _apiLogService = apiLogService; try { var request = httpContext.Request; if (IsSwagger(httpContext) || !request.Path.StartsWithSegments(new PathString("/api"))) { await _next(httpContext); } else { Stopwatch stopWatch = Stopwatch.StartNew(); var requestTime = DateTime.UtcNow; var formattedRequest = await FormatRequest(request); var originalBodyStream = httpContext.Response.Body; using (var responseBody = new MemoryStream()) { httpContext.Response.Body = responseBody; try { var response = httpContext.Response; response.Body = responseBody; await _next.Invoke(httpContext); string responseBodyContent = null; if (httpContext.Response.StatusCode == (int)HttpStatusCode.OK) { responseBodyContent = await FormatResponse(response); await HandleSuccessRequestAsync(httpContext, responseBodyContent, httpContext.Response.StatusCode); } else { await HandleNotSuccessRequestAsync(httpContext, httpContext.Response.StatusCode); } stopWatch.Stop(); #region Log Request / Response //Search the Ignore paths from appsettings to ignore the loggin of certian api paths if (_enableAPILogging && (_ignorePaths.Any(e => !request.Path.StartsWithSegments(new PathString(e.ToLower()))))) { try { await responseBody.CopyToAsync(originalBodyStream); //User id = "sub" y default ApplicationUser user = httpContext.User.Identity.IsAuthenticated ? await userManager.FindByIdAsync(httpContext.User.Claims.Where(c => c.Type == JwtClaimTypes.Subject).First().Value) : null; await SafeLog(requestTime, stopWatch.ElapsedMilliseconds, response.StatusCode, request.Method, request.Path, request.QueryString.ToString(), formattedRequest, responseBodyContent, httpContext.Connection.RemoteIpAddress.ToString(), user ); } catch (Exception ex) { _logger.LogWarning("An Inner Middleware exception occurred on SafeLog: " + ex.Message); } } #endregion } catch (System.Exception ex) { _logger.LogWarning("An Inner Middleware exception occurred: " + ex.Message); await HandleExceptionAsync(httpContext, ex); } finally { responseBody.Seek(0, SeekOrigin.Begin); await responseBody.CopyToAsync(originalBodyStream); } } } } catch (Exception ex) { // We can't do anything if the response has already started, just abort. if (httpContext.Response.HasStarted) { _logger.LogWarning("A Middleware exception occurred, but response has already started!"); throw; } await HandleExceptionAsync(httpContext, ex); throw; } }
public async Task Invoke(HttpContext httpContext, IApiLogService apiLogService, ILogger <APIResponseRequestLogginMiddleware> logger) { _logger = logger; _apiLogService = apiLogService; try { var request = httpContext.Request; if (IsSwagger(httpContext) || !request.Path.StartsWithSegments(new PathString("/api"))) { await _next(httpContext); } else { Stopwatch stopWatch = Stopwatch.StartNew(); var requestTime = DateTime.UtcNow; // Enable seeking httpContext.Request.EnableBuffering(); // Read the stream as text var requestBodyContent = await new StreamReader(httpContext.Request.Body).ReadToEndAsync(); // Set the position of the stream to 0 to enable re-reading httpContext.Request.Body.Position = 0; var originalBodyStream = httpContext.Response.Body; using (var responseBody = new MemoryStream()) { httpContext.Response.Body = responseBody; try { var response = httpContext.Response; response.Body = responseBody; await _next.Invoke(httpContext); string responseBodyContent = null; if (httpContext.Response.StatusCode == (int)HttpStatusCode.OK) { responseBodyContent = await FormatResponse(response); await HandleSuccessRequestAsync(httpContext, responseBodyContent, httpContext.Response.StatusCode); } else { await HandleNotSuccessRequestAsync(httpContext, httpContext.Response.StatusCode); } #region Log Request / Response if (_enableAPILogging) { stopWatch.Stop(); await responseBody.CopyToAsync(originalBodyStream); Guid userId = Guid.Empty; try { userId = httpContext.User.Identity.IsAuthenticated ? new Guid(httpContext.User.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).First().Value) : Guid.Empty; } catch { } //await SafeLog(requestTime, // stopWatch.ElapsedMilliseconds, // response.StatusCode, // request.Method, // request.Path, // request.QueryString.ToString(), // requestBodyContent, // responseBodyContent, // httpContext.Connection.RemoteIpAddress.ToString(), // userId // ); } #endregion } catch (System.Exception ex) { _logger.LogWarning("An Inner Middleware exception occurred: " + ex.Message); await HandleExceptionAsync(httpContext, ex); } finally { responseBody.Seek(0, SeekOrigin.Begin); await responseBody.CopyToAsync(originalBodyStream); } } } } catch (Exception ex) { // We can't do anything if the response has already started, just abort. if (httpContext.Response.HasStarted) { _logger.LogWarning("A Middleware exception occurred, but response has already started!"); throw; } await HandleExceptionAsync(httpContext, ex); throw; } }
//<summary>Recibe la peticion del servidor antes de que llegue al controlador para realzar el log de la peticion.</summary> /// <param name="cancellationToken"></param> /// <param name="request">Objeto que contiene informacion de las peticiones.</param> /// <returns>Respuesta del servidor</returns> protected override async System.Threading.Tasks.Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { using (IUnitOfWork unitOfWork = new UnitOfWork()) { IRepository <ApiLog> repository = new Repository <ApiLog>(unitOfWork); IRepository <User> repositoryUser = new Repository <User>(unitOfWork); apiLogService = new ApiLogService(repository); userService = new UserService(repositoryUser); StringBuilder content = new StringBuilder(); string requestUuid = request.GetCorrelationId().ToString(); HttpConfiguration config = GlobalConfiguration.Configuration; IHttpRouteData routeData = config.Routes.GetRouteData(request); HttpControllerContext controllerContext = new HttpControllerContext(config, routeData, request); DefaultHttpControllerSelector controllerSelector = new DefaultHttpControllerSelector(config); HttpControllerDescriptor controllerDescriptor = controllerSelector.SelectController(request); ApiControllerActionSelector apiControllerSelection = new ApiControllerActionSelector(); controllerContext.ControllerDescriptor = controllerDescriptor; HttpActionDescriptor actionDescriptor = apiControllerSelection.SelectAction(controllerContext); ApiLog requestLog = new ApiLog(); requestLog.Uuid = requestUuid; requestLog.Controller = controllerDescriptor.ControllerName; requestLog.Action = actionDescriptor.ActionName; //Obtiene y decodifica el post para que se muestre la informacion de la manera adecuada string data = HttpUtility.UrlDecode(request.Content.ReadAsStringAsync().Result); requestLog.Data = data; requestLog.CreatedAt = DateTime.Now; requestLog.Url = request.RequestUri.AbsoluteUri;//request.RequestUri.Host + HttpUtility.UrlDecode(request.RequestUri.PathAndQuery); requestLog.Method = request.Method.Method; requestLog.Status = "Started"; object headers = request.Headers.ToDictionary(x => x.Key, y => y.Value); requestLog.Headers = JsonConvert.SerializeObject(headers); //unitOfWork.BeginTransaction(); try { apiLogService.Create(requestLog); //unitOfWork.Commit(); } catch (Exception e) { //unitOfWork.Rollback(); } //Se espera la respuesta del controlador var response = await base.SendAsync(request, cancellationToken); requestUuid = request.GetCorrelationId().ToString(); //unitOfWork.BeginTransaction(); try { requestLog = apiLogService.FindBy(x => x.Uuid == requestUuid).FirstOrDefault(); User user = null; int? userId = UserApiAuthenticated.GetUserAuthenticatedId(request.GetRequestContext()); if (userId.HasValue) { user = userService.GetById(userId.Value); } if (user != null) { requestLog.CreatedBy = user; } if (requestLog != null) { if (response.RequestMessage != null && response.Content != null) { var responseContent = await response.Content.ReadAsStringAsync(); if (requestLog.Exception != null) { requestLog.Status = "HasException"; } else { requestLog.Status = "Completed"; } requestLog.Result = responseContent.ToString(); apiLogService.Update(requestLog); } } //unitOfWork.Commit(); }catch (Exception e) { //unitOfWork.Rollback(); } return(response); } }
public ApiLogDelegatingHandler() { _logService = new ApiLogService(); _keyRepository = new ApiKeyRepository(); }
/// <summary> /// /// </summary> /// <param name="next"></param> public ResponseTimeMiddleware(RequestDelegate next, IConfiguration cfg, IApiLogService apiLogService) { _next = next; _cfg = cfg; _apiLogService = apiLogService; }
public MessageLogging() { ApiLogService = new ApiLogService(); }
public ApiLoggingMiddleware(RequestDelegate next, IApiLogService apiLogService, ILogger <ApiLoggingMiddleware> logger) { _next = next; _apiLogService = apiLogService; _logger = logger; }
public LogMiddleware(RequestDelegate next, IApiLogService apiLogService, IConfiguration configration) { _next = next; _apiLogService = apiLogService; _configration = configration; }