public static void LogApiRequestAndResponse(Guid logID, HttpContext context, DateTime requestTime, string requestTenant, string requestUser, string requestBody, Exception ex, DateTime reponseTime, string responseBody) { NLog.Logger requestLogger = NLog.Web.NLogBuilder.ConfigureNLog("Nlog.config").GetLogger("ApiRequestLogger"); NLog.LogEventInfo requestLogEvent = new NLog.LogEventInfo(NLog.LogLevel.Trace, "ApiRequestLogger", "Invoke"); requestLogEvent.Properties["RequestLogID"] = logID; requestLogEvent.Properties["RequestTimestamp"] = requestTime; requestLogEvent.Properties["RequestMethod"] = context.Request.Method; requestLogEvent.Properties["RequestUrl"] = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}?{context.Request.QueryString}";//context.Request.GetDisplayUrl() requestLogEvent.Properties["RequestContentType"] = context.Request.ContentType == null ? "" : context.Request.ContentType; requestLogEvent.Properties["RequestBody"] = requestBody; requestLogEvent.Properties["RequestUser"] = requestUser; requestLogEvent.Properties["RequestTenant"] = requestTenant; requestLogEvent.Properties["HasError"] = false; if (ex != null) { FriendlyException friendlyException = ex as FriendlyException; if (friendlyException != null) { requestLogEvent.Properties["HasError"] = true; requestLogEvent.Properties["ErrorMessage"] = friendlyException.ExceptionMessage; } else { requestLogEvent.Properties["HasError"] = true; requestLogEvent.Properties["ErrorMessage"] = ex.Message; requestLogEvent.Properties["ErrorStackTrace"] = ex.StackTrace; if (ex.InnerException != null) { requestLogEvent.Properties["ErrorMessage"] = requestLogEvent.Properties["ErrorMessage"] + ";\n InnerExceptionMessage: " + ex.InnerException.Message; requestLogEvent.Properties["ErrorStackTrace"] = requestLogEvent.Properties["ErrorMessage"] + ";\n InnerExceptionStackTrace: " + ex.InnerException.StackTrace; } } } requestLogEvent.Properties["ResponseCode"] = context.Response.StatusCode.ToString(); requestLogEvent.Properties["ResponseContentType"] = context.Response.ContentType == null ? "" : context.Response.ContentType;; requestLogEvent.Properties["ResponseBody"] = responseBody; requestLogEvent.Properties["ResponseTimestamp"] = reponseTime; requestLogEvent.Properties["ExecuteDuration"] = (int)(reponseTime - requestTime).TotalMilliseconds; requestLogger.Log(requestLogEvent); }
public async Task Invoke(HttpContext context) { Guid logID = Guid.NewGuid(); DateTime requestTime = DateTime.UtcNow; string requestTenant = "", requestUser = "", requestBody = ""; Exception invokeException = null; DateTime reponseTime = requestTime; string responseBody = ""; try { if (context.Request.ContentType != null && !context.Request.ContentType.Contains("multipart/form-data")) { requestBody = await GetRequestBody(context.Request); } if (context.Request.Path.HasValue && !context.Request.Path.Value.StartsWith("/swagger") && !context.Request.Path.Value.StartsWith("/api/heathcheck")) { Claim userInfoClaim = context.User.FindFirst("current_user_info"); UserInfo currentUserInfo = JsonConvert.DeserializeObject <UserInfo>(userInfoClaim.Value); requestTenant = currentUserInfo.TenantCode; requestUser = currentUserInfo.UserName; context.Items.Add("CurrentUserInfo", currentUserInfo); UserPermission userPermission = await _userPermissionCache.GetCurrentUserPermission(); context.Items.Add("CurrentUserPermission", userPermission); var originalBodyStream = context.Response.Body; using (var memoryResponseBody = new MemoryStream()) { context.Response.Body = memoryResponseBody; await _next(context); responseBody = await GetResponseBody(context.Response); await memoryResponseBody.CopyToAsync(originalBodyStream); } } else { await _next(context); } } catch (Exception ex) { invokeException = ex; context.Response.ContentType = "application/json"; FriendlyException friendlyException = invokeException as FriendlyException; if (friendlyException != null) { switch (friendlyException.ExceptionCode) { case 401: friendlyException.ExceptionMessage = "Unauthorized user."; break; case 403: friendlyException.ExceptionMessage = "Current user have no permission for this."; break; case 404: friendlyException.ExceptionMessage = "This item does not exists."; break; case 409: friendlyException.ExceptionMessage = "This item already exists."; break; } context.Response.StatusCode = friendlyException.ExceptionCode; await context.Response.WriteAsync(JsonConvert.SerializeObject(new { FriendlyExceptionMessage = friendlyException.ExceptionMessage })); } else { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; await context.Response.WriteAsync(JsonConvert.SerializeObject(new { FriendlyExceptionMessage = $"Internal Server Error, Error ID is {logID}, Please contact the administrator to handle." })); } } finally { reponseTime = DateTime.UtcNow; if (context.Request.Path.HasValue && !context.Request.Path.Value.StartsWith("/swagger") && !context.Request.Path.Value.StartsWith("/api/heathcheck")) { NlogHelper.LogApiRequestAndResponse(logID, context, requestTime, requestTenant, requestUser, requestBody, invokeException, reponseTime, responseBody); } } }