Skip to content

Commit

Permalink
拦截中间件读取请求和响应体时的异常,埋点动作不应该影响正常业务
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Aug 3, 2024
1 parent 835f859 commit 743821c
Showing 1 changed file with 28 additions and 13 deletions.
41 changes: 28 additions & 13 deletions Stardust.Extensions/TracerMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ public async Task Invoke(HttpContext ctx)
{
//!! 以下代码不能封装为独立方法,因为有异步存在,代码被拆分为状态机,导致这里建立的埋点span无法关联页面接口内的下级埋点
ISpan? span = null;
var action = "";
if (Tracer != null && !ctx.WebSockets.IsWebSocketRequest)
{
var action = GetAction(ctx);
action = GetAction(ctx);
if (!action.IsNullOrEmpty())
{
// 请求主体作为强制采样的数据标签,便于分析链路
Expand All @@ -51,13 +52,20 @@ public async Task Invoke(HttpContext ctx)
req.ContentType != null &&
req.ContentType.StartsWithIgnoreCase(TagTypes))
{
req.EnableBuffering();
try
{
req.EnableBuffering();

var buf = new Byte[1024];
var count = await req.Body.ReadAsync(buf, 0, buf.Length);
span.AppendTag("\r\n<=\r\n" + buf.ToStr(null, 0, count));
req.Body.Position = 0;
flag = true;
var buf = new Byte[1024];
var count = await req.Body.ReadAsync(buf, 0, buf.Length);
span.AppendTag("\r\n<=\r\n" + buf.ToStr(null, 0, count));
req.Body.Position = 0;
flag = true;
}
catch (Exception ex)
{
XTrace.Log.Error("[{0}]读取请求主体失败:{1}", action, ex.Message);
}
}

if (span.Tag.Length < 500)
Expand Down Expand Up @@ -102,12 +110,19 @@ public async Task Invoke(HttpContext ctx)
res.ContentType != null &&
res.ContentType.StartsWithIgnoreCase(TagTypes))
{
var buf = new Byte[1024];
var p = res.Body.Position;
var count = await res.Body.ReadAsync(buf, 0, buf.Length);
span.AppendTag("\r\n=>\r\n" + buf.ToStr(null, 0, count));
res.Body.Position = p;
flag = true;
try
{
var buf = new Byte[1024];
var p = res.Body.Position;
var count = await res.Body.ReadAsync(buf, 0, buf.Length);
span.AppendTag("\r\n=>\r\n" + buf.ToStr(null, 0, count));
res.Body.Position = p;
flag = true;
}
catch (Exception ex)
{
XTrace.Log.Error("[{0}]读取响应主体失败:{1}", action, ex.Message);
}
}

if (span.Tag == null || span.Tag.Length < 500)
Expand Down

0 comments on commit 743821c

Please sign in to comment.