65 lines
2.7 KiB
C#
65 lines
2.7 KiB
C#
using MarcoBMS.Services.Helpers;
|
|
using MarcoBMS.Services.Service;
|
|
using Serilog.Context;
|
|
using System.Diagnostics;
|
|
|
|
namespace MarcoBMS.Services.Middleware
|
|
{
|
|
public class LoggingMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private readonly ILogger<LoggingMiddleware> _logger;
|
|
private readonly ILoggingService _loggingService;
|
|
//private readonly UserHelper _userHelper;
|
|
public LoggingMiddleware(RequestDelegate next, ILogger<LoggingMiddleware> logger, ILoggingService loggingService)
|
|
{
|
|
_next = next;
|
|
_logger = logger;
|
|
//_userHelper = userHelper;
|
|
_loggingService = loggingService;
|
|
}
|
|
|
|
public async Task Invoke(HttpContext context)
|
|
{
|
|
var stopwatch = Stopwatch.StartNew();
|
|
var response = context.Response;
|
|
var request = context.Request;
|
|
var tenant = context.User.FindFirst("TenantId")?.Value;
|
|
int tenantId = (tenant != null ? Convert.ToInt32(tenant) : 1);
|
|
|
|
|
|
using (LogContext.PushProperty("TenantId", tenantId))
|
|
using (LogContext.PushProperty("TraceId", context.TraceIdentifier))
|
|
using (LogContext.PushProperty("UserAgent", request.Headers["User-Agent"].ToString()))
|
|
using (LogContext.PushProperty("HttpMethod", request.Method))
|
|
using (LogContext.PushProperty("Timestamp", DateTime.UtcNow))
|
|
using (LogContext.PushProperty("IpAddress", context.Connection.RemoteIpAddress?.ToString()))
|
|
using (LogContext.PushProperty("RequestPath", request.Path))
|
|
|
|
|
|
try
|
|
{
|
|
await _next(context);
|
|
stopwatch.Stop();
|
|
using (LogContext.PushProperty("StatusCode", response.StatusCode.ToString()))
|
|
using (LogContext.PushProperty("ResponseTimeMs", stopwatch.ElapsedMilliseconds))
|
|
using (LogContext.PushProperty("LogLevel", "Information"))
|
|
_logger.LogInformation("HTTP {method} {path} responded {statusCode} in {timeTaken} ms", request.Method,request.Path, response.StatusCode.ToString(),stopwatch.ElapsedMilliseconds);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
stopwatch.Stop();
|
|
using (LogContext.PushProperty("Error", ex))
|
|
using (LogContext.PushProperty("StatusCode", "500"))
|
|
using (LogContext.PushProperty("ResponseTimeMs", stopwatch.ElapsedMilliseconds))
|
|
using (LogContext.PushProperty("LogLevel", "Error"))
|
|
_logger.LogError("API Error{error}", ex.Message);
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
|