Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf98792f96 | ||
|
|
8c5081d442 |
@@ -56,6 +56,12 @@ public class SimApiOptions
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiResponseFilter { get; set; } = true;
|
public bool EnableSimApiResponseFilter { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 启用请求日志中间件
|
||||||
|
/// default: false
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableRequestLog { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
|
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
|
||||||
/// default: true
|
/// default: true
|
||||||
@@ -104,6 +110,8 @@ public class SimApiOptions
|
|||||||
|
|
||||||
public SimApiRouteOptions SimApiRouteOptions { get; set; } = new();
|
public SimApiRouteOptions SimApiRouteOptions { get; set; } = new();
|
||||||
|
|
||||||
|
public SimApiRequestLogOptions SimApiRequestLogOptions { get; set; } = new();
|
||||||
|
|
||||||
public void ConfigureSimApiRoute(Action<SimApiRouteOptions>? options = null)
|
public void ConfigureSimApiRoute(Action<SimApiRouteOptions>? options = null)
|
||||||
{
|
{
|
||||||
options?.Invoke(SimApiRouteOptions);
|
options?.Invoke(SimApiRouteOptions);
|
||||||
@@ -143,4 +151,9 @@ public class SimApiOptions
|
|||||||
{
|
{
|
||||||
options?.Invoke(SimApiAuthCenterOptions);
|
options?.Invoke(SimApiAuthCenterOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void ConfigureSimApiRequestLog(Action<SimApiRequestLogOptions>? options = null)
|
||||||
|
{
|
||||||
|
options?.Invoke(SimApiRequestLogOptions);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace SimApi.Configurations;
|
||||||
|
|
||||||
|
public class SimApiRequestLogOptions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 是否打印完整的请求Header
|
||||||
|
/// </summary>
|
||||||
|
public bool ShowFullHeader { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否打印完整的响应体
|
||||||
|
/// </summary>
|
||||||
|
public bool ShowFullResponse { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.ExceptionServices;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using SimApi.Configurations;
|
||||||
|
|
||||||
|
namespace SimApi.Middlewares;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 请求日志中间件
|
||||||
|
/// </summary>
|
||||||
|
public class SimApiRequestLogMiddleware(
|
||||||
|
RequestDelegate next,
|
||||||
|
ILogger<SimApiRequestLogMiddleware> log,
|
||||||
|
SimApiRequestLogOptions options)
|
||||||
|
{
|
||||||
|
public async Task InvokeAsync(HttpContext context)
|
||||||
|
{
|
||||||
|
var sw = Stopwatch.StartNew();
|
||||||
|
var fullUrl =
|
||||||
|
$"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
|
||||||
|
|
||||||
|
var logMessage = new StringBuilder();
|
||||||
|
logMessage.AppendLine($"[{context.Request.Method}] {fullUrl}");
|
||||||
|
|
||||||
|
if (options.ShowFullHeader)
|
||||||
|
{
|
||||||
|
logMessage.AppendLine("*( RequestHeaders [Full] ) =>");
|
||||||
|
var headersDict = new Dictionary<string, string>();
|
||||||
|
foreach (var header in context.Request.Headers)
|
||||||
|
{
|
||||||
|
headersDict[header.Key] = header.Value.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
logMessage.AppendLine(JsonSerializer.Serialize(headersDict));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
logMessage.AppendLine("*( RequestHeaders ) =>");
|
||||||
|
var token = context.Request.Headers["Token"].FirstOrDefault() ?? "";
|
||||||
|
var queryId = context.Request.Headers["Query-Id"].FirstOrDefault() ?? "";
|
||||||
|
logMessage.AppendLine($"Token: {token} QueryId: {queryId}");
|
||||||
|
}
|
||||||
|
|
||||||
|
context.Request.EnableBuffering();
|
||||||
|
var requestBodyText = await new StreamReader(context.Request.Body).ReadToEndAsync();
|
||||||
|
context.Request.Body.Seek(0, SeekOrigin.Begin);
|
||||||
|
logMessage.AppendLine("*( RequestBody ) =>");
|
||||||
|
logMessage.AppendLine(requestBodyText);
|
||||||
|
|
||||||
|
var originalBodyStream = context.Response.Body;
|
||||||
|
using var responseBody = new MemoryStream();
|
||||||
|
context.Response.Body = responseBody;
|
||||||
|
|
||||||
|
ExceptionDispatchInfo? edi = null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await next(context);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
edi = ExceptionDispatchInfo.Capture(ex);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
sw.Stop();
|
||||||
|
|
||||||
|
responseBody.Seek(0, SeekOrigin.Begin);
|
||||||
|
var responseText = await new StreamReader(responseBody).ReadToEndAsync();
|
||||||
|
|
||||||
|
logMessage.AppendLine($"*( Response [{context.Response.StatusCode}] ) =>");
|
||||||
|
if (options.ShowFullResponse)
|
||||||
|
{
|
||||||
|
logMessage.Append(responseText);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var truncated = responseText.Length > 200 ? responseText[..200] : responseText;
|
||||||
|
logMessage.Append(truncated);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (edi != null)
|
||||||
|
{
|
||||||
|
logMessage.Append(Environment.NewLine);
|
||||||
|
logMessage.Append($"Exception: {edi.SourceException}");
|
||||||
|
}
|
||||||
|
|
||||||
|
responseBody.Seek(0, SeekOrigin.Begin);
|
||||||
|
await responseBody.CopyToAsync(originalBodyStream);
|
||||||
|
context.Response.Body = originalBodyStream;
|
||||||
|
|
||||||
|
log.LogInformation(logMessage.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
edi?.Throw();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -209,6 +209,7 @@ public static class SimApiExtensions
|
|||||||
x.OperationFilter<SimApiSignOperationFilter>();
|
x.OperationFilter<SimApiSignOperationFilter>();
|
||||||
x.OperationFilter<AesBodyOperationFilter>();
|
x.OperationFilter<AesBodyOperationFilter>();
|
||||||
x.SchemaFilter<GlobalDynamicObjectSchemaFilter>();
|
x.SchemaFilter<GlobalDynamicObjectSchemaFilter>();
|
||||||
|
x.SchemaFilter<DictionarySchemaFilter>();
|
||||||
x.DocumentFilter<RemoveEmptyTagsFilter>();
|
x.DocumentFilter<RemoveEmptyTagsFilter>();
|
||||||
if (simApiOptions.EnableSimApiAuth)
|
if (simApiOptions.EnableSimApiAuth)
|
||||||
{
|
{
|
||||||
@@ -339,6 +340,7 @@ public static class SimApiExtensions
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
builder.AddSingleton(simApiOptions.SimApiRequestLogOptions);
|
||||||
builder.AddSingleton(simApiOptions);
|
builder.AddSingleton(simApiOptions);
|
||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
@@ -497,6 +499,12 @@ public static class SimApiExtensions
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (options.EnableRequestLog)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置SimApiRequestLog...");
|
||||||
|
builder.UseMiddleware<SimApiRequestLogMiddleware>();
|
||||||
|
}
|
||||||
|
|
||||||
if (options.EnableSimApiException)
|
if (options.EnableSimApiException)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置SimApiException...");
|
logger.LogInformation("开始配置SimApiException...");
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using Microsoft.OpenApi;
|
||||||
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
|
|
||||||
|
namespace SimApi.SwaggerFilters;
|
||||||
|
|
||||||
|
public class DictionarySchemaFilter : ISchemaFilter
|
||||||
|
{
|
||||||
|
public void Apply(IOpenApiSchema schema, SchemaFilterContext context)
|
||||||
|
{
|
||||||
|
if (!context.Type.IsGenericType || context.Type.GetGenericTypeDefinition() != typeof(Dictionary<,>))
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (schema is not OpenApiSchema concrete) return;
|
||||||
|
|
||||||
|
var valueType = context.Type.GetGenericArguments()[1];
|
||||||
|
concrete.Type = JsonSchemaType.Object;
|
||||||
|
concrete.AdditionalPropertiesAllowed = true;
|
||||||
|
concrete.AdditionalProperties = context.SchemaGenerator.GenerateSchema(valueType, context.SchemaRepository);
|
||||||
|
concrete.Properties?.Clear();
|
||||||
|
concrete.Example = null;
|
||||||
|
concrete.Examples?.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user