-1

I have a net core 3.1 web-API application that integrated with nats and I need to capture all my application's traffic and send them to Prometheus for monitor application's activity in this case, I've used this article but it described a way of capturing Http requests not nats is anyone have any experience in such a problem?

Kasra
  • 119
  • 2
  • 13

1 Answers1

0

I finally figure it out! If anyone has the same question Here is my solution:

    {
        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();
            }
        }
    }```
Kasra
  • 119
  • 2
  • 13