当前位置:网站首页>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 .
边栏推荐
- PostgreSQL query by date range
- Generalized Focal Loss: Learning Qualified and Distributed Bounding Boxes for Dense Object Detection
- Kubernetes快速實戰與核心原理剖析
- MySQL - table operation
- Farewell to the endless summer
- Pingcap was selected as the "voice of customers" of Gartner cloud database in 2022, and won the highest score of "outstanding performer"
- CVPR2022 | 上科大x小红书首次提出动作序列验证任务,可应用于体育赛事打分等多场景
- Use map set or list set to store list set
- [deeply understand tcapulusdb technology] tmonitor system upgrade
- TOOD: Task-aligned One-stage Object Detection
猜你喜欢

Repair for a while, decisively reconstruct and take responsibility -- talk about CRM distributed cache optimization

MySQL - table constraints

CVPR2022 | 上科大x小红书首次提出动作序列验证任务,可应用于体育赛事打分等多场景

5000 word analysis: the way of container security attack and defense in actual combat scenarios

Heat mapping using Seaborn

Automatic operation and maintenance 2 - common modules in ansible

服务治理的工作内容

Annual special analysis of China Mobile Banking in 2022

Cvpr2022 | the action sequence verification task was first proposed by X xiaohongshu of Shanghai University of science and technology, which can be applied to multiple scenarios such as scoring of spo
![[untitled]](/img/3c/c34a8cbbe398cecd54050b30f95b66.png)
[untitled]
随机推荐
5000 word analysis: the way of container security attack and defense in actual combat scenarios
Explanation of vim, makefile and GDB tools
Iterm2 file transfer with remote server
Test the interface between app and wechat applet
Comment utiliser un moteur de recherche?
scrapy_redis分布式爬虫
哪个期货平台 交易更安全放心。求推荐。
应用配置管理,基础原理分析
Kubernetes快速實戰與核心原理剖析
[deeply understand tcapulusdb technology] tcapulusdb import data
[deeply understand tcapulusdb technology] tmonitor system upgrade
What is Devops in an article?
module ‘selenium. webdriver‘ has no attribute ‘PhantomJS‘
seaborn数据总体分布的可视化策略
Azure applicationinsights integrated in blazor
Repair for a while, decisively reconstruct and take responsibility -- talk about CRM distributed cache optimization
Modification method of EKF extended Kalman filter for omnidirectional ground
服务治理的工作内容
Sort query results according to the input order of fuzzy query jancode
6. functions