private async Task SafeLog(DateTime requestTime, long responseMillis, int statusCode, string method, string path, string queryString, string requestBody, string responseBody, string pUser, string pIpAdress) { //var loUser = ""; if (path.ToLower().EndsWith("login") || path.ToLower().EndsWith("token")) { //var loToken = JsonConvert.DeserializeObject<ApiUserService>(requestBody); //loUser = loToken.ApiKey; requestBody = "(Request logging disabled for " + path.ToLower(); responseBody = "(Response logging disabled for " + path.ToLower(); } //if (requestBody.Length > 100) //{ // requestBody = $"(Truncated to 100 chars) {requestBody.Substring(0, 100)}"; //} //if (responseBody.Length > 100) //{ // responseBody = $"(Truncated to 100 chars) {responseBody.Substring(0, 100)}"; //} //if (queryString.Length > 100) //{ // queryString = $"(Truncated to 100 chars) {queryString.Substring(0, 100)}"; //} var loApiLog = new ApiLogService() { RequestTime = requestTime, ResponseMills = responseMillis, StatusCode = statusCode, Method = method, Path = path, QueryString = queryString, RequestBody = requestBody, ResponseBody = responseBody, ApplicationName = "WinvestateTest", ApiCaller = pUser, IpAddress = pIpAdress }; #if PROD loApiLog.ApplicationName = "WinvestateProd"; #endif _ = Task.Run(() => WriteLogs(loApiLog)); }
private static async Task WriteLogs(ApiLogService pApiLog) { var loApiLog = ApiLog.GetModel(pApiLog); await Task.Run(() => Crud <ApiLog> .InsertLog(loApiLog, out _)); //await Task.Run(() => Common.PrepareLogger(JsonConvert.SerializeObject(loApiLog))); //var loRequestResponse = new RequestResponse //{ // Request = pApiLog.RequestBody, // Response = pApiLog.ResponseBody //}; //_ = Task.Run(() => Common.Logger.LogInfo(JsonConvert.SerializeObject(loRequestResponse))); }
public async Task Invoke(HttpContext httpContext, ApiLogService apiLogService) { try { _apiLogService = apiLogService; var request = httpContext.Request; if (request.Path.StartsWithSegments(new PathString("/api"))) { var stopWatch = Stopwatch.StartNew(); var requestTime = DateTime.UtcNow; var requestBodyContent = await ReadRequestBody(request); var originalBodyStream = httpContext.Response.Body; using (var responseBody = new MemoryStream()) { var response = httpContext.Response; response.Body = responseBody; await _next(httpContext); stopWatch.Stop(); string responseBodyContent = null; responseBodyContent = await ReadResponseBody(response); await responseBody.CopyToAsync(originalBodyStream); SafeLog(new SafeLogRQ() { requestTime = requestTime, responseMillis = stopWatch.ElapsedMilliseconds, statusCode = response.StatusCode, method = request.Method, path = request.Path, queryString = request.QueryString.ToString(), requestBody = requestBodyContent, responseBody = responseBodyContent }); } } else { await _next(httpContext); } } catch (Exception) { await _next(httpContext); } }
public async Task Invoke(HttpContext httpContext, ApiLogService 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); await SafeLog(requestTime, stopWatch.ElapsedMilliseconds, response.StatusCode, request.Method, request.Path, request.QueryString.ToString(), requestBodyContent, responseBodyContent, httpContext.Connection.RemoteIpAddress.ToString(), httpContext.User.Identity.IsAuthenticated ?new Guid(httpContext.User.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).First().Value) : Guid.Empty ); } #endregion } catch (System.Exception ex) { _logger.LogWarning("A Inner Middleware exception occurred, but response has already started!"); 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, ApiLogService apiLogService, ILogger <ApiLoggingMiddleware> logger) { _apiLogService = apiLogService; _logger = logger; try { var request = httpContext.Request; if (request.Path.StartsWithSegments(new PathString("/api"))) { 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 rereading httpContext.Request.Body.Position = 0; var originalBodyStream = httpContext.Response.Body; using (var responseBody = new MemoryStream()) { var response = httpContext.Response; response.Body = responseBody; await _next(httpContext); stopWatch.Stop(); string responseBodyContent = null; responseBodyContent = await ReadResponseBody(response); await responseBody.CopyToAsync(originalBodyStream); await SafeLog(requestTime, stopWatch.ElapsedMilliseconds, response.StatusCode, request.Method, request.Path, request.QueryString.ToString(), requestBodyContent, responseBodyContent); } } else { await _next(httpContext); } } catch (Exception ex) { // We can't do anything if the response has already started, just abort. if (httpContext.Response.HasStarted) { _logger.LogWarning("An exception occurred, but response has already started!"); throw; } await HandleExceptionAsync(httpContext, ex); throw; } }
public ApiLogController(ApiLogService apiLogService, ILogger <ApiLogController> logger) { _logger = logger; _apiLogService = apiLogService; }
public LogsController(ApiLogService apiLogService) { _apiLogService = apiLogService; }