当前位置:网站首页>Alibaba cloud link tracking is on the Net project (Jaeger trace)

Alibaba cloud link tracking is on the Net project (Jaeger trace)

2022-06-21 13:42:00 Guo Mahua

        Link tracing is an important part of the microservice architecture , It can help developers find problems quickly , Detect system performance bottlenecks , It can also help us to have a large number of Exception When , Prompt warning, etc .

Alibaba cloud link tracking service

  • Alibaba cloud provides OpenTelemetry Trace Native access to data : adopt OpenTelemetry Access C# Trace
  • It can also be done through SkyWalking、Jaeger、Zipkin Etc
  • Trace Instances can be bound to Alibaba cloud log services ( adopt project,logstore, And index fields ). Access trace after , The log will record uber-trace-id, You need to manually open the field index , To complete the binding .

 

  adopt Jaeger Report .NET Application data ( Click to see the official website example )

Usually our projects are divided into development , test , Online and other multiple environments . therefore , It is recommended that you connect trace when , adopt ServiceName To distinguish between .

modify Span Name generation strategy

Here are .NET 5.0 Version of jaeger trace Access method . Here to AspNetCore Of Span Name generation strategy , as well as Http request Span The name generation strategy has been adjusted . in addition .NET 5.0 Previous versions of Span The filtering method is also different from that described on the official website .

if (!string.IsNullOrWhiteSpace($"{Configuration["JaegerToken"]}"))
            {
                services.AddOpenTracing(builder =>
                    builder.ConfigureAspNetCore(opt =>
                    {
                        opt.Hosting.OperationNameResolver = context => $"{context.Request.Method} {context.Request.Path}";
                        opt.Hosting.IgnorePatterns.Add(ctx => ctx.Request.Path.HasValue && ctx.Request.Path.Value.Contains("health"));
                        opt.Hosting.IgnorePatterns.Add(ctx => ctx.Request.Path.HasValue && ctx.Request.Path.Value.Contains("/api/traces"));
                        opt.Hosting.IgnorePatterns.Add(ctx => ctx.Request.Path.HasValue && ctx.Request.Path.Value.Contains("/swagger"));
                    })
                    .ConfigureHttpHandler(opt=> opt.OperationNameResolver = request => $"{request.Method} {request.RequestUri.Host}{request.RequestUri.AbsolutePath}")
                ); 

                services.AddSingleton<ITracer>(serviceProvider =>
                {
                    string serviceName = serviceProvider.GetRequiredService<IWebHostEnvironment>().ApplicationName;
                 
                    ILoggerFactory loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
                    var resolver = new SenderResolver(loggerFactory).RegisterSenderFactory<ThriftSenderFactory>();
                    Configuration.SenderConfiguration senderConfiguration = new Configuration.SenderConfiguration(loggerFactory)
                        .WithSenderResolver(resolver)
                        .WithEndpoint($"{Configuration["JaegerToken"]}");

                    var tracer = new Tracer.Builder($"{serviceName}{Configuration["environmentName"]}")
                          .WithSampler(new ConstSampler(true))
                          .WithReporter(new RemoteReporter.Builder().WithSender(senderConfiguration.GetSender()).Build())
                          .Build();

                    GlobalTracer.Register(tracer);
                    return tracer;
                });
            }

Added global exception handling , How to mark Span by Exception?

Usually , We will add a global exception handling mechanism to the project , and jaeger trace Will only happen UnhandledException Of Span Mark as exception . therefore , We need to be in the global exception handler , Take the initiative to transfer the current Span Mark as exception , Or generate a child Span And marked as an exception .

Span Can be set by SetTag(Tags.Error, true) The way , Mark as exception . The essence is to add a new name “error” Of tag. such , We can use the Alibaba cloud statistics page , Observed contain exception Span The link to .

public class HttpGlobalExceptionFilter : IExceptionFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {          
            var json = new AjaxResponse(new ErrorInfo(context.Exception.Message));
            context.Result = new InternalServerErrorObjectResult(json);

            if(context.Exception is not DomainException)
            {
                ITracer tracer = GlobalTracer.Instance;
                ISpan parentSpan = tracer.ActiveSpan;
                ISpan childSpan = tracer.BuildSpan($"{context.HttpContext.Request.Method} {context.HttpContext.Request.Path}").AsChildOf(parentSpan).WithTag("error", context.Exception.Message).Start();
                tracer.ScopeManager.Activate(childSpan, false);
                childSpan.Finish();
            }

            context.ExceptionHandled = true;
        }
    }

ILogger 

According to the introduction of the alicloud official website, the trace after ,Nuget package :OpenTracing.Contrib.NetCore It actually creates a ILogger The implementation of the , be known as OpenTracingLogger, And in AddOpenTracing Complete registration when , The only thing is that the access type is internal.

When we use   _logger.LogError($"{ex.Message}"); or _logger.LogInformation($" Status detection completed ");

When printing , The log type and content will be used as Span Of Log Events Stored in link tracking .

OpenTracing.Contrib.NetCore

Our class library can see about AspNetCore, HttpHandler, EFCore, SqlClient And so on Span Generation strategy for .

for example : stay AspNetCore in , Will be in Microsoft.AspNetCore.Hosting.HttpRequestIn.Start,Microsoft.AspNetCore.Mvc.BeforeAction,Microsoft.AspNetCore.Mvc.BeforeActionResult The three phases create three Span, And then the relationship between father and son .

If you think creating a separate ActionResult Span It doesn't work , And will interfere with Trace Presentation of report , Then you can carry out secondary transformation and encapsulation of the project , Design to fit your project Trace The way .

原网站

版权声明
本文为[Guo Mahua]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221433592167.html