我有一个与 nats 集成的 net core 3.1 web-API 应用程序,在这种情况下,我需要捕获我的所有应用程序的流量并将它们发送到 Prometheus 以监视应用程序的活动,我使用过这篇文章,但它描述了一种捕获 Http 的方法requests not nats 有没有人遇到过这样的问题?
问问题
97 次
1 回答
0
我终于想通了!如果有人有同样的问题这是我的解决方案:
{
private readonly ITracer _tracer;
public TraceMiddleware(ITracer tracer)
{
_tracer = tracer;
}
public async Task ExecuteAsync(NatsContext context, PipelineDelegate next)
{
var operationName = $"{context.Request.Address.Service}:{context.Request.Address.Method}";
var builder = _tracer.BuildSpan(operationName);
#region [Context TraceId]
builder.WithTag("internalRequestId", context["requestId"].ToString());
context.Tracer.AddTracer(context.Request.Address.ToNatsSubject(), context["requestId"].ToString());
builder.WithTag("TraceId", context.Tracer.TraceId);
#endregion
using (var scope = builder.StartActive(false))
{
var span = scope.Span;
span.SetTag("flow", context.Tracer.ToString());
span.SetTag("request-route", context.Request.Address.ToNatsSubject());
span.Log(DateTimeOffset.UtcNow, "request-started");
#region [Prometheus]
var counter = Metrics.CreateCounter("app_request_total", "Nats Requests Total",
new CounterConfiguration
{
LabelNames = new[] {"path", "method", "statusCode"}
});
var path = context.Request.Address.Service;
var method = context.Request.Address.Method;
int statusCode;
try
{
await next();
}
catch (Exception)
{
statusCode = 500;
counter.Labels(path, method, statusCode.ToString()).Inc();
throw;
}
statusCode = (int) context.Response.Status;
counter.Labels(path, method, statusCode.ToString()).Inc();
#endregion
span.Log(DateTimeOffset.UtcNow, "request-finished");
var logData = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("status-code", context.Response.Status),
new KeyValuePair<string, object>("has-exception", context.Response.Error != null)
};
span.Log(logData);
span.Finish();
}
}
}```
于 2020-07-01T07:29:16.550 回答