当前位置:网站首页>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 .
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 .
边栏推荐
- Don't know how to interview? Test interview questions summary, teach you to face the interview questions
- Which futures trading platform is more secure. Ask for recommendation.
- MySQL - transaction management
- [deeply understand tcapulusdb technology] tcapulusdb import data
- Lamp Architecture 3 -- compilation and use of PHP source code
- Write efficient defect reports
- Quelle plate - forme à terme est plus sûre. Je vous en prie.
- C language elementary level (10) type rename typedef
- MySQL - adding, deleting, querying and modifying tables
- Is the live interactive function of the applet running in the app?
猜你喜欢

How to read AI summit papers?

Sharing new experiences in home office | community essay solicitation

修修补补一时爽,果断重构有担当——聊聊CRM分布式缓存优化

Automatic operation and maintenance 3 - using playbook in ansible

Navigation bar switching, message board, text box losing focus

Kubernetes快速实战与核心原理剖析

Babbitt yuancosmos daily must read: wechat may ban a official account for the first time on the grounds of "involving secondary transactions in digital collections", and the new regulations of the pla

Lamp architecture 4 -- MySQL source code compilation and use

MySQL - index

Generalized Focal Loss: Learning Qualified and Distributed Bounding Boxes for Dense Object Detection
随机推荐
Application configuration management, basic principle analysis
Azure applicationinsights integrated in blazor
Isn't this another go bug?
Detailed explanation and examples of common parameters of curl
Open source FTP server FileZilla server
Apache shardingsphere 5.1.2 release | new driving API + cloud native deployment to create a high-performance data gateway
Quelle plate - forme à terme est plus sûre. Je vous en prie.
Prepare for the golden three silver four, are you ready? Summary of software test interview questions
JS 中的集合引用类型
【深入理解TcaplusDB技术】TcaplusDB业务数据备份
Kotlin - sequence sequence
MySQL constraints (descriptions of various conditions when creating tables)
[in depth understanding of tcapulusdb technology] tcapulusdb construction data
The new plan for national treasures - the exclusive digital collection of the four museums is coming!
3. function improvement
TOOD: Task-aligned One-stage Object Detection
Lamp Architecture 3 -- compilation and use of PHP source code
Kubernetes快速實戰與核心原理剖析
Automatic operation and maintenance 4 - variables and encryption in ansible
MySQL - data type