Serilog Db Logging issue with middleware ASP.NET Core Web API

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>namespace FraudPortalService.Shared.Logging
{
public class FraudPortalLogReqRespTraceMiddleware1
{
private readonly ILogger<FraudPortalLogReqRespTraceMiddleware> _logger;
private readonly Stopwatch _watch = new Stopwatch();
private readonly RequestDelegate _next;
private readonly RecyclableMemoryStreamManager _recyclableMemoryStreamManager;
private static bool _allowReqRespLog;
internal ServiceLogDTO log { get; set; }
public static LoggerConfiguration ConfigLog(ref LoggerConfiguration loggerConfiguration, IConfiguration config)
{
var columnOptions = new ColumnOptions
{
AdditionalColumns = new Collection<SqlColumn>
{
new() { DataType = SqlDbType.Xml, ColumnName = "requestXml" },
new() { DataType = SqlDbType.Xml, ColumnName = "responseXml" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "correlationId" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "messageId" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "methodType" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "url" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "header" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "request" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "response" },
new() { DataType = SqlDbType.SmallInt, ColumnName = "statusCode" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "appCode" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "errMessage" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "stackTrace" },
new() { DataType = SqlDbType.SmallInt, ColumnName = "serverVersion" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "userId" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "clientIp" },
new() { DataType = SqlDbType.DateTime, ColumnName = "timestamp1" },
new() { DataType = SqlDbType.Decimal, ColumnName = "duration" },
new() { DataType = SqlDbType.NVarChar, ColumnName = "applCode" },
}
};
columnOptions.Store.Remove(StandardColumn.Properties);
columnOptions.Store.Remove(StandardColumn.MessageTemplate);
columnOptions.Store.Remove(StandardColumn.Message);
columnOptions.Store.Remove(StandardColumn.Exception);
columnOptions.Store.Remove(StandardColumn.Level);
loggerConfiguration
.AuditTo.Logger(l =>
l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
//Add logging catagory
.Filter.ByIncludingOnly(e =>
Matching.FromSource("FraudPortalService.BusinessLayer.RiskCenterService").Invoke(e) ||
Matching.FromSource("FraudPortalService.Util.FraudPortalServiceReqRespTraceMiddleware").Invoke(e))
.AuditTo.MSSqlServer(connectionString: config.GetConnectionString("Fraudportal"),
sinkOptions: new MSSqlServerSinkOptions { TableName = "LogToDBTest1", AutoCreateSqlTable = true },
columnOptions: columnOptions));
return loggerConfiguration;
}
public FraudPortalLogReqRespTraceMiddleware1(RequestDelegate next, IConfiguration config,ILoggerFactory loggerFactory)
{
this._next = next ?? throw new ArgumentNullException(nameof(next));
_logger = loggerFactory.CreateLogger<FraudPortalLogReqRespTraceMiddleware>();
_recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
_allowReqRespLog = bool.TryParse(config["AppSettings:EnableDBLogSensitiveData"], out var debugenabled) && debugenabled;
}
public async Task InvokeAsync(HttpContext context)
{
_watch.Restart();
string response = "";
var isSwaggerorLogViewer = context.Request.Path.Value.Contains("swagger") || context.Request.Path.Value.Contains("LogViewer")
|| context.Request.Path.Value.Contains("HealthCheck") ||
context.Request.Path.Value.Contains(".ico")
|| context.Request.Path.Value.Contains(".js") ||
var watch = Stopwatch.StartNew();
DateTime reqTs = DateTime.Now;
try
{
if (!isSwaggerorLogViewer)
{
log = new ServiceLogDTO();
await LogRequest(context);
await LogResponse(context);
WriteServiceLogs(log);
}
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
finally
{
watch.Stop();
}
}
private async Task LogRequest(HttpContext context)
{
try
{
context.Request.EnableBuffering();
await using var requestStream = _recyclableMemoryStreamManager.GetStream();
await context.Request.Body.CopyToAsync(requestStream);
log.TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
log.Url = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
log.ClientIP = $"{context.Request.Host.Host}";
log.MethodName = $"{context.Request.Method}";
log.MessageId = Guid.NewGuid().ToString();
if (context.Request.Method == HttpMethod.Get.ToString() || (context.Request.Method == HttpMethod.Post.ToString() && context.Request.Headers.ContentLength == 0))
{
var queryParameters = context.Request.Query.ToDictionary(kv => kv.Key, kv => string.Join(";", kv.Value), StringComparer.OrdinalIgnoreCase); ;
result = FromDictionaryToJson(queryParameters);
log.Request = result;
}
else
{
log.Request = context.Request.QueryString.Value.ToString();
}
// Environment.MachineName;
log.UserId = context.User.Identity.Name;
//httpRequestMessage.GetHeader(Util.Constants.Constant.CustomHeader.UserId);
log.ServiceVersion = ConfigHelper.GetValue(Util.Constants.Constant.ApplicationSettings.ServiceVersion);
log.StatusCode = (int)context.Response.StatusCode;
// log.Request = FormatRequest(context.Request);
log.Header = headers;
}
catch (Exception ex)
{
//_logger.LogError(ex, "request/response logging exception");
throw;
}
context.Request.Body.Position = 0;
}
private async Task LogResponse(HttpContext context)
{
var originalBodyStream = context.Response.Body;
try
{
await using var responseBody = _recyclableMemoryStreamManager.GetStream();
context.Response.Body = responseBody;
await _next(context);
context.Response.Body.Seek(0, SeekOrigin.Begin);
await responseBody.CopyToAsync(originalBodyStream);
log.StatusCode = (int)context.Response.StatusCode;
log.Response = await FormatResponse(context.Response);
_watch.Stop();
// log.ExecutionDuration = Convert.ToDecimal(_watch.Elapsed.TotalSeconds);
// await responseBody.CopyToAsync(originalBodyStream);
}
catch (Exception ex)
{
//_logger.LogError(ex, "request/response logging exception");
throw;
}
finally
{
context.Response.Body = originalBodyStream;
}
//context.Response.Body = responseBody;
//await _next(context);
//log.StatusCode = (int)context.Response.StatusCode;
//log.Response = await FormatResponse(context.Response);
//_watch.Stop();
//log.ExecutionDuration = Convert.ToDecimal(_watch.Elapsed.TotalSeconds);
//await responseBody.CopyToAsync(originalBodyStream);
}
private void WriteServiceLogs(ServiceLogDTO serviceLog)
{
_logger.LogInformation(
// WebUtility.HtmlEncode(TraceLogEntity.LogTemplate),
WebUtility.HtmlEncode(serviceLog.ApplicationCode),
WebUtility.HtmlEncode(serviceLog.ClientIP),
WebUtility.HtmlEncode(serviceLog.StatusCode.ToString()),
WebUtility.HtmlEncode(serviceLog.Header),
WebUtility.HtmlEncode(serviceLog.CorrelationId),
WebUtility.HtmlEncode(serviceLog.ErrorMessage),
WebUtility.HtmlEncode(serviceLog.Url),
//WebUtility.HtmlEncode(log.JsonRequest),
WebUtility.HtmlEncode(serviceLog.Response),
//log.JsonRequest,
//log.JsonResponse,
WebUtility.HtmlEncode(serviceLog.ExecutionDuration.ToString()),
WebUtility.HtmlEncode(serviceLog.Request),
WebUtility.HtmlEncode(serviceLog.Response),
WebUtility.HtmlEncode(serviceLog.ErrorMessage),
WebUtility.HtmlEncode(serviceLog.StatusCode.ToString()),
WebUtility.HtmlEncode(serviceLog.Header),
WebUtility.HtmlEncode(serviceLog.MessageId));
WebUtility.HtmlEncode(serviceLog.MethodName);
WebUtility.HtmlEncode(serviceLog.ServiceVersion);
WebUtility.HtmlEncode(serviceLog.StackTrace);
WebUtility.HtmlEncode(serviceLog.TimeStamp);
WebUtility.HtmlEncode(serviceLog.UserId);
}
private async Task<string> FormatResponse(HttpResponse response)
{
response.Body.Seek(0, SeekOrigin.Begin);
var text = await new StreamReader(response.Body).ReadToEndAsync();
response.Body.Seek(0, SeekOrigin.Begin);
return $"{text}";
}
//private void LogRequest(HttpRequest request)
//{
// request.EnableRewind();
// using (var requestStream = _recyclableMemoryStreamManager.GetStream())
// {
// request.Body.CopyTo(requestStream);
// reques
// _logger.LogInformation($"Http Request Information:{Environment.NewLine}" +
// $"Schema:{request.Scheme} " +
// $"Host: {request.Host} " +
// $"Path: {request.Path} " +
// $"QueryString: {request.QueryString} " +
// $"Request Body: {ReadStreamInChunks(requestStream)}");
// }
//}
//private static ServiceLogDTO CreateRequestLogObject(HttpRequestMessage httpRequest)
//{
// var serviceLog = new ServiceLogDTO
// {
// //ClientIP = Extension.GetClientIp(httpRequest),
// ApplicationCode = httpRequest.GetHeader(Util.Constants.Constant.CustomHeader.ApplicationCode),
// TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture),
// CorrelationId = httpRequest.GetHeader(Util.Constants.Constant.CustomHeader.CorrelationId) ?? Guid.NewGuid().ToString(),
// Header = httpRequest.Headers.ToString(),
// MessageId = Guid.NewGuid().ToString(),
// MethodName = "",//Need to figure this out
// MethodType = httpRequest.Method.Method,
// Request = httpRequest.GetQueryStrings(),
// Url = httpRequest.RequestUri.AbsolutePath,
// UserId = httpRequest.GetHeader(Util.Constants.Constant.CustomHeader.UserId),
// ServiceVersion = ConfigHelper.GetValue(Util.Constants.Constant.ApplicationSettings.ServiceVersion),
// };
// return serviceLog;
//}
//private ServiceLogDTO CreateResponseLogObject(ServiceLogDTO serviceLog, HttpResponseMessage httpResponse)
//{
// if (serviceLog == null)
// {
// return null;
// }
// serviceLog.StatusCode = (int)httpResponse.StatusCode;
// serviceLog.Response = httpResponse.Content?.ReadAsStringAsync().Result;
// _watch.Stop();
// serviceLog.ExecutionDuration = Convert.ToDecimal(_watch.Elapsed.TotalSeconds);
// return serviceLog;
//}
public static string FromDictionaryToJson( Dictionary<string, string> dictionary)
{
var kvs = dictionary.Select(kvp => $""{kvp.Key}":"{kvp.Value}"");
return string.Concat("{", string.Join(",", kvs), "}");
}
public static string FormatHeaders(IHeaderDictionary headers)
{
var stringBuilder = new StringBuilder();
foreach (var (key, value) in headers)
{
stringBuilder.AppendLine($"- {key}: {value}");
}
return stringBuilder.ToString();
}
public static string FormatHeaders(HttpRequestHeaders headers)
{
var stringBuilder = new StringBuilder();
foreach (var item in headers)
{
var val = (item.Value == null) ? "" : (item.Value.GetType() == typeof(string[])) ? item.Value.First() : item.Value.ToString();
stringBuilder.AppendLine($"- {item.Key}: {val}");
}
return stringBuilder.ToString();
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
const HttpStatusCode code = HttpStatusCode.InternalServerError;
var result = JsonSerializer.Serialize(new
{
exceptionMessage = new
{
errorType = "NA",
errorMessage = "Internal Server Error Occurred."
}
});
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
private static string ReadStreamInChunks(Stream stream)
{
const int readChunkBufferLength = 4096;
stream.Seek(0, SeekOrigin.Begin);
using var textWriter = new StringWriter();
using var reader = new StreamReader(stream);
var readChunk = new char[readChunkBufferLength];
int readChunkLength;
do
{
readChunkLength = reader.ReadBlock(readChunk,
0,
readChunkBufferLength);
textWriter.Write(readChunk, 0, readChunkLength);
} while (readChunkLength > 0);
return textWriter.ToString();
}
//public static void ProcessOutboundResponse(ILogger logger, string logcategory, HttpContext? context,
// HttpResponseMessage response, HttpRequestMessage request, Exception? ex = null)
//{
// var reqStr = request.Content?.ReadAsStringAsync()?.GetAwaiter().GetResult();
// TraceLogEntity log = new TraceLogEntity(
// servername: Environment.MachineName,
// reqTimeStamp: request.Properties["BeginInvoke"] != null
// ? ((DateTime)request.Properties["BeginInvoke"]).ToString("yyyy-MM-dd HH:mm:ss.fff")
// : string.Empty,
// logCategory: logcategory,
// inboundTraceId: context?.Request?.Headers["x-client-traceid"],
// header: FormatHeaders(request.Headers),
// httpMethod: request.Method.ToString(),
// url: request.RequestUri.ToString(),
// jsonRequest: _allowReqRespLog ? (reqStr == "null" ? null : reqStr) : string.Empty,
// jsonResponse: _allowReqRespLog ? response?.Content?.ReadAsStringAsync()?.Result : string.Empty,
// executionDuration: $"{DateTime.Now.Subtract((DateTime)request.Properties["BeginInvoke"]).TotalSeconds:F2}",
// isSuccess: ex == null ? true : false,
// inboundTraffic: false,
// errorMessage: null,
// exception: ex?.ToString(),
// traceIdentifier: context?.TraceIdentifier);
// logger.LogDebug(
// WebUtility.HtmlEncode(TraceLogEntity.LogTemplate),
// WebUtility.HtmlEncode(log.ReqTimeStamp),
// WebUtility.HtmlEncode(log.LogCategory),
// WebUtility.HtmlEncode(log.InboundTraceId),
// WebUtility.HtmlEncode(log.Header),
// WebUtility.HtmlEncode(log.HttpMethod),
// WebUtility.HtmlEncode(log.Url),
// //WebUtility.HtmlEncode(log.JsonRequest),
// //WebUtility.HtmlEncode(log.JsonResponse),
// log.JsonRequest,
// log.JsonResponse,
// WebUtility.HtmlEncode(log.ExecutionDuration),
// WebUtility.HtmlEncode(log.IsSuccess ? "true" : "false"),
// WebUtility.HtmlEncode(log.InboundTraffic ? "true" : "false"),
// WebUtility.HtmlEncode(log.ErrorMessage),
// WebUtility.HtmlEncode(log.Exception),
// WebUtility.HtmlEncode(log.TraceIdentifier),
// WebUtility.HtmlEncode(log.ServerName));
//}
//public static void LogInternalMethodAcaps(ILogger logger, string logcategory, HttpContext context,
// DateTime startTm, string url, string reqStr, string respStr, Exception? ex = null)
//{
// TraceLogEntity log = new TraceLogEntity(
// servername: Environment.MachineName,
// reqTimeStamp: startTm.ToString("yyyy-MM-dd HH:mm:ss.fff"),
// logCategory: logcategory,
// inboundTraceId: context?.Request?.Headers["x-client-traceid"],
// header: "",
// httpMethod: "POST",
// url: url,
// jsonRequest: reqStr == "null" ? null : reqStr,
// jsonResponse: respStr,
// executionDuration: $"{DateTime.Now.Subtract(startTm).TotalSeconds:F2}",
// isSuccess: ex == null ? true : false,
// inboundTraffic: false,
// errorMessage: ex?.Message,
// exception: ex?.ToString(),
// traceIdentifier: context?.TraceIdentifier);
// logger.LogDebug(
// WebUtility.HtmlEncode(TraceLogEntity.LogTemplate),
// WebUtility.HtmlEncode(log.ReqTimeStamp),
// WebUtility.HtmlEncode(log.LogCategory),
// WebUtility.HtmlEncode(log.InboundTraceId),
// WebUtility.HtmlEncode(log.Header),
// WebUtility.HtmlEncode(log.HttpMethod),
// WebUtility.HtmlEncode(log.Url),
// //WebUtility.HtmlEncode(log.JsonRequest),
// //WebUtility.HtmlEncode(log.JsonResponse),
// log.JsonRequest,
// log.JsonResponse,
// WebUtility.HtmlEncode(log.ExecutionDuration),
// WebUtility.HtmlEncode(log.IsSuccess ? "true" : "false"),
// WebUtility.HtmlEncode(log.InboundTraffic ? "true" : "false"),
// WebUtility.HtmlEncode(log.ErrorMessage),
// WebUtility.HtmlEncode(log.Exception),
// WebUtility.HtmlEncode(log.TraceIdentifier),
// WebUtility.HtmlEncode(log.ServerName));
//}
private async Task<string> GetRequestBodyAsync(HttpContext context)
{
context.Request.EnableBuffering();
try
{
await using var requestStream = _recyclableMemoryStreamManager.GetStream();
await context.Request.Body.CopyToAsync(requestStream);
return ReadStreamInChunks(requestStream);
}
catch (Exception ex)
{
//_logger.LogError(WebUtility.HtmlEncode(ex.ToString()));
throw;
}
}
//public string GetIP(bool CheckForward,HttpContext httpContext)
//{
// string ip = null;
// if (CheckForward)
// {
// ip = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
// }
// if (string.IsNullOrEmpty(ip))
// {
// ip = httpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
// }
// else
// { // Using X-Forwarded-For last address
// ip = ip.Split(',')
// .Last()
// .Trim();
// }
// return ip;
//}
}
}
</code>
<code>namespace FraudPortalService.Shared.Logging { public class FraudPortalLogReqRespTraceMiddleware1 { private readonly ILogger<FraudPortalLogReqRespTraceMiddleware> _logger; private readonly Stopwatch _watch = new Stopwatch(); private readonly RequestDelegate _next; private readonly RecyclableMemoryStreamManager _recyclableMemoryStreamManager; private static bool _allowReqRespLog; internal ServiceLogDTO log { get; set; } public static LoggerConfiguration ConfigLog(ref LoggerConfiguration loggerConfiguration, IConfiguration config) { var columnOptions = new ColumnOptions { AdditionalColumns = new Collection<SqlColumn> { new() { DataType = SqlDbType.Xml, ColumnName = "requestXml" }, new() { DataType = SqlDbType.Xml, ColumnName = "responseXml" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "correlationId" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "messageId" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "methodType" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "url" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "header" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "request" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "response" }, new() { DataType = SqlDbType.SmallInt, ColumnName = "statusCode" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "appCode" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "errMessage" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "stackTrace" }, new() { DataType = SqlDbType.SmallInt, ColumnName = "serverVersion" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "userId" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "clientIp" }, new() { DataType = SqlDbType.DateTime, ColumnName = "timestamp1" }, new() { DataType = SqlDbType.Decimal, ColumnName = "duration" }, new() { DataType = SqlDbType.NVarChar, ColumnName = "applCode" }, } }; columnOptions.Store.Remove(StandardColumn.Properties); columnOptions.Store.Remove(StandardColumn.MessageTemplate); columnOptions.Store.Remove(StandardColumn.Message); columnOptions.Store.Remove(StandardColumn.Exception); columnOptions.Store.Remove(StandardColumn.Level); loggerConfiguration .AuditTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug) //Add logging catagory .Filter.ByIncludingOnly(e => Matching.FromSource("FraudPortalService.BusinessLayer.RiskCenterService").Invoke(e) || Matching.FromSource("FraudPortalService.Util.FraudPortalServiceReqRespTraceMiddleware").Invoke(e)) .AuditTo.MSSqlServer(connectionString: config.GetConnectionString("Fraudportal"), sinkOptions: new MSSqlServerSinkOptions { TableName = "LogToDBTest1", AutoCreateSqlTable = true }, columnOptions: columnOptions)); return loggerConfiguration; } public FraudPortalLogReqRespTraceMiddleware1(RequestDelegate next, IConfiguration config,ILoggerFactory loggerFactory) { this._next = next ?? throw new ArgumentNullException(nameof(next)); _logger = loggerFactory.CreateLogger<FraudPortalLogReqRespTraceMiddleware>(); _recyclableMemoryStreamManager = new RecyclableMemoryStreamManager(); _allowReqRespLog = bool.TryParse(config["AppSettings:EnableDBLogSensitiveData"], out var debugenabled) && debugenabled; } public async Task InvokeAsync(HttpContext context) { _watch.Restart(); string response = ""; var isSwaggerorLogViewer = context.Request.Path.Value.Contains("swagger") || context.Request.Path.Value.Contains("LogViewer") || context.Request.Path.Value.Contains("HealthCheck") || context.Request.Path.Value.Contains(".ico") || context.Request.Path.Value.Contains(".js") || var watch = Stopwatch.StartNew(); DateTime reqTs = DateTime.Now; try { if (!isSwaggerorLogViewer) { log = new ServiceLogDTO(); await LogRequest(context); await LogResponse(context); WriteServiceLogs(log); } } catch (Exception ex) { await HandleExceptionAsync(context, ex); } finally { watch.Stop(); } } private async Task LogRequest(HttpContext context) { try { context.Request.EnableBuffering(); await using var requestStream = _recyclableMemoryStreamManager.GetStream(); await context.Request.Body.CopyToAsync(requestStream); log.TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture); log.Url = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}"; log.ClientIP = $"{context.Request.Host.Host}"; log.MethodName = $"{context.Request.Method}"; log.MessageId = Guid.NewGuid().ToString(); if (context.Request.Method == HttpMethod.Get.ToString() || (context.Request.Method == HttpMethod.Post.ToString() && context.Request.Headers.ContentLength == 0)) { var queryParameters = context.Request.Query.ToDictionary(kv => kv.Key, kv => string.Join(";", kv.Value), StringComparer.OrdinalIgnoreCase); ; result = FromDictionaryToJson(queryParameters); log.Request = result; } else { log.Request = context.Request.QueryString.Value.ToString(); } // Environment.MachineName; log.UserId = context.User.Identity.Name; //httpRequestMessage.GetHeader(Util.Constants.Constant.CustomHeader.UserId); log.ServiceVersion = ConfigHelper.GetValue(Util.Constants.Constant.ApplicationSettings.ServiceVersion); log.StatusCode = (int)context.Response.StatusCode; // log.Request = FormatRequest(context.Request); log.Header = headers; } catch (Exception ex) { //_logger.LogError(ex, "request/response logging exception"); throw; } context.Request.Body.Position = 0; } private async Task LogResponse(HttpContext context) { var originalBodyStream = context.Response.Body; try { await using var responseBody = _recyclableMemoryStreamManager.GetStream(); context.Response.Body = responseBody; await _next(context); context.Response.Body.Seek(0, SeekOrigin.Begin); await responseBody.CopyToAsync(originalBodyStream); log.StatusCode = (int)context.Response.StatusCode; log.Response = await FormatResponse(context.Response); _watch.Stop(); // log.ExecutionDuration = Convert.ToDecimal(_watch.Elapsed.TotalSeconds); // await responseBody.CopyToAsync(originalBodyStream); } catch (Exception ex) { //_logger.LogError(ex, "request/response logging exception"); throw; } finally { context.Response.Body = originalBodyStream; } //context.Response.Body = responseBody; //await _next(context); //log.StatusCode = (int)context.Response.StatusCode; //log.Response = await FormatResponse(context.Response); //_watch.Stop(); //log.ExecutionDuration = Convert.ToDecimal(_watch.Elapsed.TotalSeconds); //await responseBody.CopyToAsync(originalBodyStream); } private void WriteServiceLogs(ServiceLogDTO serviceLog) { _logger.LogInformation( // WebUtility.HtmlEncode(TraceLogEntity.LogTemplate), WebUtility.HtmlEncode(serviceLog.ApplicationCode), WebUtility.HtmlEncode(serviceLog.ClientIP), WebUtility.HtmlEncode(serviceLog.StatusCode.ToString()), WebUtility.HtmlEncode(serviceLog.Header), WebUtility.HtmlEncode(serviceLog.CorrelationId), WebUtility.HtmlEncode(serviceLog.ErrorMessage), WebUtility.HtmlEncode(serviceLog.Url), //WebUtility.HtmlEncode(log.JsonRequest), WebUtility.HtmlEncode(serviceLog.Response), //log.JsonRequest, //log.JsonResponse, WebUtility.HtmlEncode(serviceLog.ExecutionDuration.ToString()), WebUtility.HtmlEncode(serviceLog.Request), WebUtility.HtmlEncode(serviceLog.Response), WebUtility.HtmlEncode(serviceLog.ErrorMessage), WebUtility.HtmlEncode(serviceLog.StatusCode.ToString()), WebUtility.HtmlEncode(serviceLog.Header), WebUtility.HtmlEncode(serviceLog.MessageId)); WebUtility.HtmlEncode(serviceLog.MethodName); WebUtility.HtmlEncode(serviceLog.ServiceVersion); WebUtility.HtmlEncode(serviceLog.StackTrace); WebUtility.HtmlEncode(serviceLog.TimeStamp); WebUtility.HtmlEncode(serviceLog.UserId); } private async Task<string> FormatResponse(HttpResponse response) { response.Body.Seek(0, SeekOrigin.Begin); var text = await new StreamReader(response.Body).ReadToEndAsync(); response.Body.Seek(0, SeekOrigin.Begin); return $"{text}"; } //private void LogRequest(HttpRequest request) //{ // request.EnableRewind(); // using (var requestStream = _recyclableMemoryStreamManager.GetStream()) // { // request.Body.CopyTo(requestStream); // reques // _logger.LogInformation($"Http Request Information:{Environment.NewLine}" + // $"Schema:{request.Scheme} " + // $"Host: {request.Host} " + // $"Path: {request.Path} " + // $"QueryString: {request.QueryString} " + // $"Request Body: {ReadStreamInChunks(requestStream)}"); // } //} //private static ServiceLogDTO CreateRequestLogObject(HttpRequestMessage httpRequest) //{ // var serviceLog = new ServiceLogDTO // { // //ClientIP = Extension.GetClientIp(httpRequest), // ApplicationCode = httpRequest.GetHeader(Util.Constants.Constant.CustomHeader.ApplicationCode), // TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture), // CorrelationId = httpRequest.GetHeader(Util.Constants.Constant.CustomHeader.CorrelationId) ?? Guid.NewGuid().ToString(), // Header = httpRequest.Headers.ToString(), // MessageId = Guid.NewGuid().ToString(), // MethodName = "",//Need to figure this out // MethodType = httpRequest.Method.Method, // Request = httpRequest.GetQueryStrings(), // Url = httpRequest.RequestUri.AbsolutePath, // UserId = httpRequest.GetHeader(Util.Constants.Constant.CustomHeader.UserId), // ServiceVersion = ConfigHelper.GetValue(Util.Constants.Constant.ApplicationSettings.ServiceVersion), // }; // return serviceLog; //} //private ServiceLogDTO CreateResponseLogObject(ServiceLogDTO serviceLog, HttpResponseMessage httpResponse) //{ // if (serviceLog == null) // { // return null; // } // serviceLog.StatusCode = (int)httpResponse.StatusCode; // serviceLog.Response = httpResponse.Content?.ReadAsStringAsync().Result; // _watch.Stop(); // serviceLog.ExecutionDuration = Convert.ToDecimal(_watch.Elapsed.TotalSeconds); // return serviceLog; //} public static string FromDictionaryToJson( Dictionary<string, string> dictionary) { var kvs = dictionary.Select(kvp => $""{kvp.Key}":"{kvp.Value}""); return string.Concat("{", string.Join(",", kvs), "}"); } public static string FormatHeaders(IHeaderDictionary headers) { var stringBuilder = new StringBuilder(); foreach (var (key, value) in headers) { stringBuilder.AppendLine($"- {key}: {value}"); } return stringBuilder.ToString(); } public static string FormatHeaders(HttpRequestHeaders headers) { var stringBuilder = new StringBuilder(); foreach (var item in headers) { var val = (item.Value == null) ? "" : (item.Value.GetType() == typeof(string[])) ? item.Value.First() : item.Value.ToString(); stringBuilder.AppendLine($"- {item.Key}: {val}"); } return stringBuilder.ToString(); } private static Task HandleExceptionAsync(HttpContext context, Exception ex) { const HttpStatusCode code = HttpStatusCode.InternalServerError; var result = JsonSerializer.Serialize(new { exceptionMessage = new { errorType = "NA", errorMessage = "Internal Server Error Occurred." } }); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)code; return context.Response.WriteAsync(result); } private static string ReadStreamInChunks(Stream stream) { const int readChunkBufferLength = 4096; stream.Seek(0, SeekOrigin.Begin); using var textWriter = new StringWriter(); using var reader = new StreamReader(stream); var readChunk = new char[readChunkBufferLength]; int readChunkLength; do { readChunkLength = reader.ReadBlock(readChunk, 0, readChunkBufferLength); textWriter.Write(readChunk, 0, readChunkLength); } while (readChunkLength > 0); return textWriter.ToString(); } //public static void ProcessOutboundResponse(ILogger logger, string logcategory, HttpContext? context, // HttpResponseMessage response, HttpRequestMessage request, Exception? ex = null) //{ // var reqStr = request.Content?.ReadAsStringAsync()?.GetAwaiter().GetResult(); // TraceLogEntity log = new TraceLogEntity( // servername: Environment.MachineName, // reqTimeStamp: request.Properties["BeginInvoke"] != null // ? ((DateTime)request.Properties["BeginInvoke"]).ToString("yyyy-MM-dd HH:mm:ss.fff") // : string.Empty, // logCategory: logcategory, // inboundTraceId: context?.Request?.Headers["x-client-traceid"], // header: FormatHeaders(request.Headers), // httpMethod: request.Method.ToString(), // url: request.RequestUri.ToString(), // jsonRequest: _allowReqRespLog ? (reqStr == "null" ? null : reqStr) : string.Empty, // jsonResponse: _allowReqRespLog ? response?.Content?.ReadAsStringAsync()?.Result : string.Empty, // executionDuration: $"{DateTime.Now.Subtract((DateTime)request.Properties["BeginInvoke"]).TotalSeconds:F2}", // isSuccess: ex == null ? true : false, // inboundTraffic: false, // errorMessage: null, // exception: ex?.ToString(), // traceIdentifier: context?.TraceIdentifier); // logger.LogDebug( // WebUtility.HtmlEncode(TraceLogEntity.LogTemplate), // WebUtility.HtmlEncode(log.ReqTimeStamp), // WebUtility.HtmlEncode(log.LogCategory), // WebUtility.HtmlEncode(log.InboundTraceId), // WebUtility.HtmlEncode(log.Header), // WebUtility.HtmlEncode(log.HttpMethod), // WebUtility.HtmlEncode(log.Url), // //WebUtility.HtmlEncode(log.JsonRequest), // //WebUtility.HtmlEncode(log.JsonResponse), // log.JsonRequest, // log.JsonResponse, // WebUtility.HtmlEncode(log.ExecutionDuration), // WebUtility.HtmlEncode(log.IsSuccess ? "true" : "false"), // WebUtility.HtmlEncode(log.InboundTraffic ? "true" : "false"), // WebUtility.HtmlEncode(log.ErrorMessage), // WebUtility.HtmlEncode(log.Exception), // WebUtility.HtmlEncode(log.TraceIdentifier), // WebUtility.HtmlEncode(log.ServerName)); //} //public static void LogInternalMethodAcaps(ILogger logger, string logcategory, HttpContext context, // DateTime startTm, string url, string reqStr, string respStr, Exception? ex = null) //{ // TraceLogEntity log = new TraceLogEntity( // servername: Environment.MachineName, // reqTimeStamp: startTm.ToString("yyyy-MM-dd HH:mm:ss.fff"), // logCategory: logcategory, // inboundTraceId: context?.Request?.Headers["x-client-traceid"], // header: "", // httpMethod: "POST", // url: url, // jsonRequest: reqStr == "null" ? null : reqStr, // jsonResponse: respStr, // executionDuration: $"{DateTime.Now.Subtract(startTm).TotalSeconds:F2}", // isSuccess: ex == null ? true : false, // inboundTraffic: false, // errorMessage: ex?.Message, // exception: ex?.ToString(), // traceIdentifier: context?.TraceIdentifier); // logger.LogDebug( // WebUtility.HtmlEncode(TraceLogEntity.LogTemplate), // WebUtility.HtmlEncode(log.ReqTimeStamp), // WebUtility.HtmlEncode(log.LogCategory), // WebUtility.HtmlEncode(log.InboundTraceId), // WebUtility.HtmlEncode(log.Header), // WebUtility.HtmlEncode(log.HttpMethod), // WebUtility.HtmlEncode(log.Url), // //WebUtility.HtmlEncode(log.JsonRequest), // //WebUtility.HtmlEncode(log.JsonResponse), // log.JsonRequest, // log.JsonResponse, // WebUtility.HtmlEncode(log.ExecutionDuration), // WebUtility.HtmlEncode(log.IsSuccess ? "true" : "false"), // WebUtility.HtmlEncode(log.InboundTraffic ? "true" : "false"), // WebUtility.HtmlEncode(log.ErrorMessage), // WebUtility.HtmlEncode(log.Exception), // WebUtility.HtmlEncode(log.TraceIdentifier), // WebUtility.HtmlEncode(log.ServerName)); //} private async Task<string> GetRequestBodyAsync(HttpContext context) { context.Request.EnableBuffering(); try { await using var requestStream = _recyclableMemoryStreamManager.GetStream(); await context.Request.Body.CopyToAsync(requestStream); return ReadStreamInChunks(requestStream); } catch (Exception ex) { //_logger.LogError(WebUtility.HtmlEncode(ex.ToString())); throw; } } //public string GetIP(bool CheckForward,HttpContext httpContext) //{ // string ip = null; // if (CheckForward) // { // ip = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; // } // if (string.IsNullOrEmpty(ip)) // { // ip = httpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; // } // else // { // Using X-Forwarded-For last address // ip = ip.Split(',') // .Last() // .Trim(); // } // return ip; //} } } </code>
namespace FraudPortalService.Shared.Logging
{
    public class FraudPortalLogReqRespTraceMiddleware1
    {
       private readonly ILogger<FraudPortalLogReqRespTraceMiddleware> _logger;
       
        private readonly Stopwatch _watch = new Stopwatch();
        private readonly RequestDelegate _next;
        private readonly RecyclableMemoryStreamManager _recyclableMemoryStreamManager;
        private static bool _allowReqRespLog;
        internal ServiceLogDTO log { get; set; }

        public static LoggerConfiguration ConfigLog(ref LoggerConfiguration loggerConfiguration, IConfiguration config)
        {
            var columnOptions = new ColumnOptions
            {
                AdditionalColumns = new Collection<SqlColumn>
                {
                    new() { DataType = SqlDbType.Xml, ColumnName = "requestXml" },
                    new() { DataType = SqlDbType.Xml, ColumnName = "responseXml" },
                    new() { DataType = SqlDbType.NVarChar, ColumnName = "correlationId" },
                    new() { DataType = SqlDbType.NVarChar, ColumnName = "messageId" },

                        new() { DataType = SqlDbType.NVarChar, ColumnName = "methodType" },
                        new() { DataType = SqlDbType.NVarChar, ColumnName = "url" },
                        new() { DataType = SqlDbType.NVarChar, ColumnName = "header" },
                        new() { DataType = SqlDbType.NVarChar, ColumnName = "request" },

                        new() { DataType = SqlDbType.NVarChar, ColumnName = "response" },

                        new() { DataType = SqlDbType.SmallInt, ColumnName = "statusCode" },
                        new() { DataType = SqlDbType.NVarChar, ColumnName = "appCode" },

                        new() { DataType = SqlDbType.NVarChar, ColumnName = "errMessage" },
                        new() { DataType = SqlDbType.NVarChar, ColumnName = "stackTrace" },
                        new() { DataType = SqlDbType.SmallInt, ColumnName = "serverVersion" },
                        new() { DataType = SqlDbType.NVarChar, ColumnName = "userId" },

                        new() { DataType = SqlDbType.NVarChar, ColumnName = "clientIp" },
                        new() { DataType = SqlDbType.DateTime, ColumnName = "timestamp1" },
                        new() { DataType = SqlDbType.Decimal, ColumnName = "duration" },
                        new() { DataType = SqlDbType.NVarChar, ColumnName = "applCode" },

                    }
            };
            columnOptions.Store.Remove(StandardColumn.Properties);
            columnOptions.Store.Remove(StandardColumn.MessageTemplate);
            columnOptions.Store.Remove(StandardColumn.Message);
            columnOptions.Store.Remove(StandardColumn.Exception);
            columnOptions.Store.Remove(StandardColumn.Level);

            loggerConfiguration
               .AuditTo.Logger(l =>
                    l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
                        //Add logging catagory
                        .Filter.ByIncludingOnly(e =>
                        Matching.FromSource("FraudPortalService.BusinessLayer.RiskCenterService").Invoke(e) ||
                                                     Matching.FromSource("FraudPortalService.Util.FraudPortalServiceReqRespTraceMiddleware").Invoke(e))
                        .AuditTo.MSSqlServer(connectionString: config.GetConnectionString("Fraudportal"),
                            sinkOptions: new MSSqlServerSinkOptions { TableName = "LogToDBTest1", AutoCreateSqlTable = true },
                            columnOptions: columnOptions));
            return loggerConfiguration;
        }

        public FraudPortalLogReqRespTraceMiddleware1(RequestDelegate next, IConfiguration config,ILoggerFactory loggerFactory)
        {
            this._next = next ?? throw new ArgumentNullException(nameof(next));
            _logger = loggerFactory.CreateLogger<FraudPortalLogReqRespTraceMiddleware>();
            _recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
            _allowReqRespLog = bool.TryParse(config["AppSettings:EnableDBLogSensitiveData"], out var debugenabled) && debugenabled;
        }
       
        public async Task InvokeAsync(HttpContext context)
        {
            _watch.Restart();
           
            string response = "";
            var isSwaggerorLogViewer = context.Request.Path.Value.Contains("swagger") || context.Request.Path.Value.Contains("LogViewer")
                                                                                      || context.Request.Path.Value.Contains("HealthCheck") ||
                                                                                      context.Request.Path.Value.Contains(".ico")
                                                                                      || context.Request.Path.Value.Contains(".js") ||
        
            var watch = Stopwatch.StartNew();
            DateTime reqTs = DateTime.Now;

            try
            {
                if (!isSwaggerorLogViewer)
                {
                    log = new ServiceLogDTO();

                    await LogRequest(context);
                    await LogResponse(context);
                    
                    WriteServiceLogs(log);
                }
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
            finally
            {
                watch.Stop();
            }
        }

        private async Task LogRequest(HttpContext context)
        {
            try
            {
                context.Request.EnableBuffering();

                await using var requestStream = _recyclableMemoryStreamManager.GetStream();
                await context.Request.Body.CopyToAsync(requestStream);

                log.TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                log.Url = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
                log.ClientIP = $"{context.Request.Host.Host}";
                log.MethodName = $"{context.Request.Method}";
                log.MessageId = Guid.NewGuid().ToString();

                if (context.Request.Method == HttpMethod.Get.ToString() || (context.Request.Method == HttpMethod.Post.ToString() && context.Request.Headers.ContentLength == 0))
                {
                    var queryParameters = context.Request.Query.ToDictionary(kv => kv.Key, kv => string.Join(";", kv.Value), StringComparer.OrdinalIgnoreCase); ;
                    result = FromDictionaryToJson(queryParameters);
                    log.Request = result;
                }
                else
                {
                    log.Request = context.Request.QueryString.Value.ToString();
                }

                // Environment.MachineName;
                log.UserId = context.User.Identity.Name;
                //httpRequestMessage.GetHeader(Util.Constants.Constant.CustomHeader.UserId);
                log.ServiceVersion = ConfigHelper.GetValue(Util.Constants.Constant.ApplicationSettings.ServiceVersion);
                log.StatusCode = (int)context.Response.StatusCode;
                // log.Request = FormatRequest(context.Request);
                log.Header = headers;
            }
            catch (Exception ex)
            {
                //_logger.LogError(ex, "request/response logging exception");
                throw;
            }

            context.Request.Body.Position = 0;
        }

        private async Task LogResponse(HttpContext context)
        {
            var originalBodyStream = context.Response.Body;

            try
            {
                await using var responseBody = _recyclableMemoryStreamManager.GetStream();
                context.Response.Body = responseBody;
                await _next(context);
                context.Response.Body.Seek(0, SeekOrigin.Begin);
                await responseBody.CopyToAsync(originalBodyStream);

                log.StatusCode = (int)context.Response.StatusCode;
                log.Response = await FormatResponse(context.Response);
                _watch.Stop();

                // log.ExecutionDuration = Convert.ToDecimal(_watch.Elapsed.TotalSeconds);
                // await responseBody.CopyToAsync(originalBodyStream);
            }
            catch (Exception ex)
            {
                //_logger.LogError(ex, "request/response logging exception");
                throw;
            }
            finally
            {
                context.Response.Body = originalBodyStream;
            }

            //context.Response.Body = responseBody;

            //await _next(context);

            //log.StatusCode = (int)context.Response.StatusCode;
            //log.Response = await FormatResponse(context.Response);
            //_watch.Stop();
            //log.ExecutionDuration = Convert.ToDecimal(_watch.Elapsed.TotalSeconds);

            //await responseBody.CopyToAsync(originalBodyStream);
        }

        private void WriteServiceLogs(ServiceLogDTO serviceLog)
        {
            _logger.LogInformation(
                // WebUtility.HtmlEncode(TraceLogEntity.LogTemplate),
                WebUtility.HtmlEncode(serviceLog.ApplicationCode),
                WebUtility.HtmlEncode(serviceLog.ClientIP),
                WebUtility.HtmlEncode(serviceLog.StatusCode.ToString()),
                WebUtility.HtmlEncode(serviceLog.Header),
                WebUtility.HtmlEncode(serviceLog.CorrelationId),
                WebUtility.HtmlEncode(serviceLog.ErrorMessage),
                WebUtility.HtmlEncode(serviceLog.Url),

            //WebUtility.HtmlEncode(log.JsonRequest),                    
            WebUtility.HtmlEncode(serviceLog.Response),
            //log.JsonRequest,
            //log.JsonResponse,
            WebUtility.HtmlEncode(serviceLog.ExecutionDuration.ToString()),
            WebUtility.HtmlEncode(serviceLog.Request),
            WebUtility.HtmlEncode(serviceLog.Response),
            WebUtility.HtmlEncode(serviceLog.ErrorMessage),
            WebUtility.HtmlEncode(serviceLog.StatusCode.ToString()),
            WebUtility.HtmlEncode(serviceLog.Header),
            WebUtility.HtmlEncode(serviceLog.MessageId));
            WebUtility.HtmlEncode(serviceLog.MethodName);
            WebUtility.HtmlEncode(serviceLog.ServiceVersion);
            WebUtility.HtmlEncode(serviceLog.StackTrace);
            WebUtility.HtmlEncode(serviceLog.TimeStamp);
            WebUtility.HtmlEncode(serviceLog.UserId);
        }

        private async Task<string> FormatResponse(HttpResponse response)
        {
            response.Body.Seek(0, SeekOrigin.Begin);
            var text = await new StreamReader(response.Body).ReadToEndAsync();
            response.Body.Seek(0, SeekOrigin.Begin);

            return $"{text}";
        }

        //private void LogRequest(HttpRequest request)
        //{
        //    request.EnableRewind();
        //    using (var requestStream = _recyclableMemoryStreamManager.GetStream())
        //    {
        //        request.Body.CopyTo(requestStream);
        //        reques
        //        _logger.LogInformation($"Http Request Information:{Environment.NewLine}" +
        //                               $"Schema:{request.Scheme} " +
        //                               $"Host: {request.Host} " +
        //                               $"Path: {request.Path} " +
        //                               $"QueryString: {request.QueryString} " +
        //                               $"Request Body: {ReadStreamInChunks(requestStream)}");
        //    }
        //}
        //private static ServiceLogDTO CreateRequestLogObject(HttpRequestMessage httpRequest)
        //{
        //    var serviceLog = new ServiceLogDTO
        //    {
        //        //ClientIP = Extension.GetClientIp(httpRequest),
        //        ApplicationCode = httpRequest.GetHeader(Util.Constants.Constant.CustomHeader.ApplicationCode),
        //        TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture),
        //        CorrelationId = httpRequest.GetHeader(Util.Constants.Constant.CustomHeader.CorrelationId) ?? Guid.NewGuid().ToString(),
        //        Header = httpRequest.Headers.ToString(),
        //        MessageId = Guid.NewGuid().ToString(),
        //        MethodName = "",//Need to figure this out
        //        MethodType = httpRequest.Method.Method,
        //        Request = httpRequest.GetQueryStrings(),
        //        Url = httpRequest.RequestUri.AbsolutePath,
        //        UserId = httpRequest.GetHeader(Util.Constants.Constant.CustomHeader.UserId),
        //        ServiceVersion = ConfigHelper.GetValue(Util.Constants.Constant.ApplicationSettings.ServiceVersion),

        //    };
        //    return serviceLog;
        //}
        //private ServiceLogDTO CreateResponseLogObject(ServiceLogDTO serviceLog, HttpResponseMessage httpResponse)
        //{
        //    if (serviceLog == null)
        //    {
        //        return null;
        //    }

        //    serviceLog.StatusCode = (int)httpResponse.StatusCode;
        //    serviceLog.Response = httpResponse.Content?.ReadAsStringAsync().Result;
        //    _watch.Stop();
        //    serviceLog.ExecutionDuration = Convert.ToDecimal(_watch.Elapsed.TotalSeconds);
        //    return serviceLog;
        //}

        public static string FromDictionaryToJson( Dictionary<string, string> dictionary)
        {
            var kvs = dictionary.Select(kvp => $""{kvp.Key}":"{kvp.Value}"");
            return string.Concat("{", string.Join(",", kvs), "}");
        }

        public static string FormatHeaders(IHeaderDictionary headers)
        {
            var stringBuilder = new StringBuilder();

            foreach (var (key, value) in headers)
            {
                stringBuilder.AppendLine($"- {key}: {value}");
            }

            return stringBuilder.ToString();
        }

        public static string FormatHeaders(HttpRequestHeaders headers)
        {
            var stringBuilder = new StringBuilder();

            foreach (var item in headers)
            {
                var val = (item.Value == null) ? "" : (item.Value.GetType() == typeof(string[])) ? item.Value.First() : item.Value.ToString();
                stringBuilder.AppendLine($"- {item.Key}: {val}");
            }

            return stringBuilder.ToString();
        }

        private static Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            const HttpStatusCode code = HttpStatusCode.InternalServerError;
            var result = JsonSerializer.Serialize(new
            {
                exceptionMessage = new
                {
                    errorType = "NA",
                    errorMessage = "Internal Server Error Occurred."

                }
            });

            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)code;

            return context.Response.WriteAsync(result);
        }

        private static string ReadStreamInChunks(Stream stream)
        {
            const int readChunkBufferLength = 4096;
            stream.Seek(0, SeekOrigin.Begin);
            using var textWriter = new StringWriter();
            using var reader = new StreamReader(stream);
            var readChunk = new char[readChunkBufferLength];
            int readChunkLength;

            do
            {
                readChunkLength = reader.ReadBlock(readChunk,
                    0,
                    readChunkBufferLength);
                textWriter.Write(readChunk, 0, readChunkLength);
            } while (readChunkLength > 0);
            return textWriter.ToString();
        }

        //public static void ProcessOutboundResponse(ILogger logger, string logcategory, HttpContext? context,
        //    HttpResponseMessage response, HttpRequestMessage request, Exception? ex = null)
        //{
        //    var reqStr = request.Content?.ReadAsStringAsync()?.GetAwaiter().GetResult();
        //    TraceLogEntity log = new TraceLogEntity(
        //        servername: Environment.MachineName,
        //        reqTimeStamp: request.Properties["BeginInvoke"] != null
        //            ? ((DateTime)request.Properties["BeginInvoke"]).ToString("yyyy-MM-dd HH:mm:ss.fff")
        //            : string.Empty,
        //        logCategory: logcategory,
        //        inboundTraceId: context?.Request?.Headers["x-client-traceid"],
        //        header: FormatHeaders(request.Headers),
        //        httpMethod: request.Method.ToString(),
        //        url: request.RequestUri.ToString(),
        //        jsonRequest: _allowReqRespLog ? (reqStr == "null" ? null : reqStr) : string.Empty,
        //        jsonResponse: _allowReqRespLog ? response?.Content?.ReadAsStringAsync()?.Result : string.Empty,
        //        executionDuration: $"{DateTime.Now.Subtract((DateTime)request.Properties["BeginInvoke"]).TotalSeconds:F2}",
        //        isSuccess: ex == null ? true : false,
        //        inboundTraffic: false,
        //        errorMessage: null,
        //        exception: ex?.ToString(),
        //        traceIdentifier: context?.TraceIdentifier);
        //    logger.LogDebug(
        //        WebUtility.HtmlEncode(TraceLogEntity.LogTemplate),
        //        WebUtility.HtmlEncode(log.ReqTimeStamp),
        //        WebUtility.HtmlEncode(log.LogCategory),
        //        WebUtility.HtmlEncode(log.InboundTraceId),
        //        WebUtility.HtmlEncode(log.Header),
        //        WebUtility.HtmlEncode(log.HttpMethod),
        //        WebUtility.HtmlEncode(log.Url),
        //        //WebUtility.HtmlEncode(log.JsonRequest),
        //        //WebUtility.HtmlEncode(log.JsonResponse),
        //        log.JsonRequest,
        //        log.JsonResponse,
        //        WebUtility.HtmlEncode(log.ExecutionDuration),
        //        WebUtility.HtmlEncode(log.IsSuccess ? "true" : "false"),
        //        WebUtility.HtmlEncode(log.InboundTraffic ? "true" : "false"),
        //        WebUtility.HtmlEncode(log.ErrorMessage),
        //        WebUtility.HtmlEncode(log.Exception),
        //        WebUtility.HtmlEncode(log.TraceIdentifier),
        //        WebUtility.HtmlEncode(log.ServerName));
        //}

        //public static void LogInternalMethodAcaps(ILogger logger, string logcategory, HttpContext context,
        //    DateTime startTm, string url, string reqStr, string respStr, Exception? ex = null)
        //{
        //    TraceLogEntity log = new TraceLogEntity(
        //        servername: Environment.MachineName,
        //        reqTimeStamp: startTm.ToString("yyyy-MM-dd HH:mm:ss.fff"),
        //        logCategory: logcategory,
        //        inboundTraceId: context?.Request?.Headers["x-client-traceid"],
        //        header: "",
        //        httpMethod: "POST",
        //        url: url,
        //        jsonRequest: reqStr == "null" ? null : reqStr,
        //        jsonResponse: respStr,
        //        executionDuration: $"{DateTime.Now.Subtract(startTm).TotalSeconds:F2}",
        //        isSuccess: ex == null ? true : false,
        //        inboundTraffic: false,
        //        errorMessage: ex?.Message,
        //        exception: ex?.ToString(),
        //        traceIdentifier: context?.TraceIdentifier);
        //    logger.LogDebug(
        //        WebUtility.HtmlEncode(TraceLogEntity.LogTemplate),
        //        WebUtility.HtmlEncode(log.ReqTimeStamp),
        //        WebUtility.HtmlEncode(log.LogCategory),
        //        WebUtility.HtmlEncode(log.InboundTraceId),
        //        WebUtility.HtmlEncode(log.Header),
        //        WebUtility.HtmlEncode(log.HttpMethod),
        //        WebUtility.HtmlEncode(log.Url),
        //        //WebUtility.HtmlEncode(log.JsonRequest),
        //        //WebUtility.HtmlEncode(log.JsonResponse),
        //        log.JsonRequest,
        //        log.JsonResponse,
        //        WebUtility.HtmlEncode(log.ExecutionDuration),
        //        WebUtility.HtmlEncode(log.IsSuccess ? "true" : "false"),
        //        WebUtility.HtmlEncode(log.InboundTraffic ? "true" : "false"),
        //        WebUtility.HtmlEncode(log.ErrorMessage),
        //        WebUtility.HtmlEncode(log.Exception),
        //        WebUtility.HtmlEncode(log.TraceIdentifier),
        //        WebUtility.HtmlEncode(log.ServerName));
        //}

        private async Task<string> GetRequestBodyAsync(HttpContext context)
        {
            context.Request.EnableBuffering();

            try
            {
                await using var requestStream = _recyclableMemoryStreamManager.GetStream();
                await context.Request.Body.CopyToAsync(requestStream);
                return ReadStreamInChunks(requestStream);
            }
            catch (Exception ex)
            {
                //_logger.LogError(WebUtility.HtmlEncode(ex.ToString()));
                throw;
            }
        }

        //public string GetIP(bool CheckForward,HttpContext httpContext)
        //{
        //    string ip = null;
        //    if (CheckForward)
        //    {
        //        ip = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        //    }

        //    if (string.IsNullOrEmpty(ip))
        //    {
        //        ip = httpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        //    }
        //    else
        //    { // Using X-Forwarded-For last address
        //        ip = ip.Split(',')
        //               .Last()
        //               .Trim();
        //    }
        //    return ip;
        //}
    }
}

Program.cs:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var providers = new LoggerProviderCollection();
var logConfig = LoggingConfiguration.GetLoggingConfiguration(builder.Configuration, providers);
FraudPortalLogReqRespTraceMiddleware.ConfigLog(ref logConfig, builder.Configuration);
Log.Logger = logConfig.CreateLogger();
builder.Host.UseSerilog(providers: providers);
app.UseMiddleware<FraudPortalLogReqRespTraceMiddleware>();
</code>
<code>var providers = new LoggerProviderCollection(); var logConfig = LoggingConfiguration.GetLoggingConfiguration(builder.Configuration, providers); FraudPortalLogReqRespTraceMiddleware.ConfigLog(ref logConfig, builder.Configuration); Log.Logger = logConfig.CreateLogger(); builder.Host.UseSerilog(providers: providers); app.UseMiddleware<FraudPortalLogReqRespTraceMiddleware>(); </code>
var providers = new LoggerProviderCollection();
var logConfig = LoggingConfiguration.GetLoggingConfiguration(builder.Configuration, providers);

FraudPortalLogReqRespTraceMiddleware.ConfigLog(ref logConfig, builder.Configuration);

Log.Logger = logConfig.CreateLogger();
builder.Host.UseSerilog(providers: providers);

app.UseMiddleware<FraudPortalLogReqRespTraceMiddleware>();

I tried the above code to log all the requests and response of the API to a database.

I see table is getting created but no records in the table. No errors also

New contributor

user7198357 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật