Sentry (v20.12.1) k8s cloud native architecture exploration, JavaScript performance monitoring management transactions

For less 2021-01-21 20:37:43
sentry v20.12.1 20.12.1 k8s cloud


series

  1. Sentry-Go SDK Chinese Practice Guide
  2. Let's brush together Sentry For Go Official document Enriching Events
  3. Snuba:Sentry New search infrastructure ( be based on ClickHouse above )
  4. Sentry 10 K8S Cloud native architecture exploration ,Vue App 1 Minutes fast access
  5. Sentry(v20.12.1) K8S Cloud native architecture exploration , Before you play / Back end monitoring and event log big data analysis , High performance and high availability + Scalable cluster deployment
  6. Sentry(v20.12.1) K8S Cloud native architecture exploration ,Sentry JavaScript SDK Three ways to install and load
  7. Sentry(v20.12.1) K8S Cloud native architecture exploration ,SENTRY FOR JAVASCRIPT SDK Configuration details
  8. Sentry(v20.12.1) K8S Cloud native architecture exploration , SENTRY FOR JAVASCRIPT Basic usage of manually capturing Events
  9. Sentry(v20.12.1) K8S Cloud native architecture exploration ,SENTRY FOR JAVASCRIPT Source Maps Detailed explanation
  10. Sentry(v20.12.1) K8S Cloud native architecture exploration ,SENTRY FOR JAVASCRIPT Troubleshooting
  11. Sentry(v20.12.1) K8S Cloud native architecture exploration ,1 Minutes to go JavaScript Performance monitoring

Automatic Instrumentation

To automatically capture transactions, You must first enable tracing in your application .

@sentry/tracing The package provides a BrowserTracing Integrate , To add automatic instrumentation To monitor the performance of browser applications .

What Automatic Instrumentation Provides

BrowserTracing Integrated for each page load and navigation Event creates a new transaction, And for opening these transactions Every time that happens XMLHttpRequest or fetch Request to create a child span. Learn more traces, transactions, and spans.

Enable Automatic Instrumentation

To enable this autotracking , Please be there. SDK Configuration options include BrowserTracing Integrate .( Please note that , Use ESM When the module , The main @sentry/* import Must precede @sentry/tracing import.)

When the configuration is complete , stay sentry.io View in transactions when , You will see at the same time pageload and navigation.

ESM

// If you're using one of our integration packages, like `@sentry/react` or `@sentry/angular`,
// substitute its name for `@sentry/browser` here
import * as Sentry from "@sentry/browser";
import { Integrations as TracingIntegrations } from "@sentry/tracing"; // Must import second
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [
new Integrations.BrowserTracing({
tracingOrigins: ["localhost", "my-site-url.com", /^\//],
// ... other options
}),
],
// We recommend adjusting this value in production, or using tracesSampler
// for finer control
tracesSampleRate: 1.0,
});

CDN

Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [
new Sentry.Integrations.BrowserTracing({
tracingOrigins: ["localhost", "my-site-url.com", /^\//],
// ... other options
}),
],
// We recommend adjusting this value in production, or using tracesSampler
// for finer control
tracesSampleRate: 1.0,
});

Configuration Options

You can pass many different options to BrowserTracing Integrate ( As {optionName: value} The object of form ), But it has a reasonable default value . For all the possible options , Please see the TypeDocs.

tracingOrigins

tracingOrigins The default value of is ['localhost', /^\//]. JavaScript SDK take sentry-trace header All outgoing... Attached to a string in its target containing list or to a regular expression matching the list XHR/fetch request . If your front end makes a request to another domain , You need to add it , In order to sentry-trace header Spread to back end services , This is going to be transactions Linking together as part of a single trace is required .tracingOrigins Options and the entire request URL matching , Not just domains . Use more rigorous regular expressions to match URL Some parts of , You can ensure that the request is not attached unnecessarily sentry-trace header.

for example :

  • The front end application is from example.com Provided
  • Back end services are provided by api.example.com Provide
  • The front-end application performs API call
  • therefore , This option needs to be configured like this :new Integrations.BrowserTracing({tracingOrigins: ['api.example.com']})
  • Now? , towards api.example.com Emitted XHR/fetch The request will get additional sentry-trace header
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [
new Integrations.BrowserTracing({
tracingOrigins: ["localhost", "my-site-url.com"],
}),
],
// We recommend adjusting this value in production, or using tracesSampler
// for finer control
tracesSampleRate: 1.0,
});

You will need to configure your Web The server CORS With permission sentry-trace header. This configuration may be similar to "Access-Control-Allow-Headers: sentry-trace", But the configuration depends on your settings . If you are not allowed to use sentry-trace header, The request may be blocked .

beforeNavigate

about pageload and navigation transactions,BrowserTracing Integrated use of browser window.location API Generate transaction name . To customize pageload and navigation transactions The name of , You can go to BrowserTracing Integration provides beforeNavigate Options . This option allows you to modify transaction Name to make it more generic , for example , be known as GET /users/12312012 and GET /users/11212012 Of transactions Can be renamed to GET /users/:userid, So that they can be together .

import * as Sentry from "@sentry/browser";
import { Integrations } from "@sentry/tracing";
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [
new Integrations.BrowserTracing({
beforeNavigate: context => {
return {
...context,
// You could use your UI's routing library to find the matching
// route template here. We don't have one right now, so do some basic
// parameter replacements.
name: location.pathname
.replace(/\d+/g, "<digits>")
.replace(/[a-f0-9]{32}/g, "<hash>"),
};
},
}),
],
// We recommend adjusting this value in production, or using tracesSampler
// for finer control
tracesSampleRate: 1.0,
});

shouldCreateSpanForRequest

This function can be used to filter out unwanted spans, for example XHR Health check or similar check . By default ,shouldCreateSpanForRequest It's filtered out except tracingOrigins All content other than that defined in .

import * as Sentry from "@sentry/browser";
import { Integrations } from "@sentry/tracing";
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [
new Integrations.BrowserTracing({
shouldCreateSpanForRequest: url => {
// Do not create spans for outgoing requests to a `/health/` endpoint
return !url.match(/\/health\/?$/);
},
}),
],
// We recommend adjusting this value in production, or using tracesSampler
// for finer control
tracesSampleRate: 1.0,
});

Manual Instrumentation

To capture manually transactions, You must first enable tracing in your application .

To manually instrument Some areas of the code , You can create transactions To capture them .

This is for all JavaScript SDK( Back end and front end ) All effective , And independent of Express,Http and BrowserTracing Integrated and working .

const transaction = Sentry.startTransaction({ name: "test-transaction" });
const span = transaction.startChild({ op: "functionX" }); // This function returns a Span
// functionCallX
span.finish(); // Remember that only finished spans will be sent with the transaction
transaction.finish(); // Finishing the transaction will send it to Sentry

for example , If you want to create for user interaction on the page transaction, Do the following :

// Let's say this function is invoked when a user clicks on the checkout button of your shop
shopCheckout() {
// This will create a new Transaction for you
const transaction = Sentry.startTransaction('shopCheckout');
// set the transaction on the scope so it picks up any errors
hub.configureScope(scope => scope.setSpan(transaction));
// Assume this function makes an xhr/fetch call
const result = validateShoppingCartOnServer();
const span = transaction.startChild({
data: {
result
},
op: 'task',
description: `processing shopping cart result`,
});
processAndValidateShoppingCart(result);
span.finish();
transaction.finish();
}

This example will send a transaction shopCheckout To Sentry. The deal will contain a task span, The span To measure processAndValidateShoppingCart How long did it take . Last , Yes transaction.finish() Will complete transaction And send it to Sentry.

Creating... For asynchronous operations spans when , You can also use Promises. But remember , Must be called on transaction.finish() Before it was span Included in transaction .

for example :

function processItem(item, transaction) {
const span = transaction.startChild({
op: "http",
description: `GET /items/:item-id`,
});
return new Promise((resolve, reject) => {
http.get(`/items/${item.id}`, response => {
response.on("data", () => {});
response.on("end", () => {
span.setTag("http.status_code", response.statusCode);
span.setData("http.foobarsessionid", getFoobarSessionid(response));
span.finish();
resolve(response);
});
});
});
}

Connect Backend and Frontend Transactions

To combine the back end with the front end transactions Connect to a single consistent trace ,Sentry Use trace_id value , The value propagates between the front end and the back end . According to the circumstances , this ID You can ask for header or HTML <meta> Mark the transmission of . Link in this way transactions So that you can go to Sentry UI Navigate between them in the , So you can better understand how different parts of the system interact with each other . You can learn more about this model in our distributed tracking document .

Pageload

Enable tracing on both the front end and the back end and take advantage of the automatic front end instrumentation When the function , Can be automatically generated on the front-end pageload transaction It's the same as the one on the back end that provides the request for the page service transaction Connect . Because it runs in the browser JavaScript The code cannot read the response of the current page headers, therefore trace_id Must be transmitted in the response itself , Especially when it's sent from the back end HTML <head> Medium <meta> In the label .

<html>
<head>
<meta name="sentry-trace" content="{{ span.toTraceparent() }}" />
<!-- ... -->
</head>
</html>

name Property must be a string "sentry-trace",content Property must be created by the back end of Sentry SDK Use span.toTraceparent()( Or equivalent , It depends on the back end platform ) Generate . This guarantees that a new unique value will be generated for each request .

span Reference is for HTML serviceable transaction, Or any of them child spans. It defines the pageload transaction The father of .

Once the data is contained in <meta> In the label , our BrowserTracing The integration will automatically capture the data and link it to pageload Generated on transaction.( Please note that , It doesn't link to automatically generated navigation transactions, That is, there is no need to reload the entire page transaction. Every transaction It's all back-end requests transaction Result , So there should be a unique trace_id.)

After loading the page , Any request it makes ( And any requests from the back end ) All by request header link .

As discussed above <meta> The label is the same , The title is sentry-trace, Its value is determined by calling span.toTraceparent()( Or equivalent ) To get , among span It's related transaction Or any of its children .

Sentry All the tracking related integration of (BrowserTracing,Http and Express) Will be generated for all of them transactions and spans Automatically generate or pick up and propagate this header. Create... Manually transaction or span In any case , You can attach and read it yourself header, It makes sense .

Control Data Truncation

At present , The maximum number of characters per label is limited to 200 Characters . exceed 200 Tags with a character limit will be truncated , Missing potentially important information . To keep this data , You can split data into multiple tags .

for example , One 200 Multiple character mark request :

https://empowerplant.io/api/0/projects/ep/setup_form/?user_id=314159265358979323846264338327&tracking_id=EasyAsABC123OrSimpleAsDoReMi&product_name=PlantToHumanTranslator&product_id=161803398874989484820458683436563811772030917980576

above 200 Requests with more than characters will be truncated to :

https://empowerplant.io/api/0/projects/ep/setup_form/?user_id=314159265358979323846264338327&tracking_id=EasyAsABC123OrSimpleAsDoReMi&product_name=PlantToHumanTranslator&product_id=1618033988749894848

contrary , Use span.set_tag and span.set_data Structured metadata is used to keep the details of this query . This can be done by baseUrl,endpoint and parameters complete :

const baseUrl = "https://empowerplant.io";
const endpoint = "/api/0/projects/ep/setup_form";
const parameters = {
user_id: 314159265358979323846264338327,
tracking_id: "EasyAsABC123OrSimpleAsDoReMi",
product_name: PlantToHumanTranslator,
product_id: 161803398874989484820458683436563811772030917980576,
};
const span = transaction.startChild({
op: "request",
description: "setup form",
});
span.setTag("baseUrl", baseUrl);
span.setTag("endpoint", endpoint);
span.setData("parameters", parameters);
// you may also find some parameters to be valuable as tags
span.setData("user_id", parameters.user_id);
http.get(`${base_url}/${endpoint}/`, (data = parameters));

Group Transactions

Sentry Capture transactions when , They will be assigned a transaction name . The name is usually given by Sentry SDK Automatically generated based on the framework integration you use . If you can't take advantage of automatic transaction Generate ( Or want to customize transaction How names are generated ), You can use , Using configuration initialization SDK The global event handler registered when .

stay node.js An example of doing this in an application :

import { addGlobalEventProcessor } from "@sentry/node";
addGlobalEventProcessor(event => {
// if event is a transaction event
if (event.type === "transaction") {
event.transaction = sanitizeTransactionName(event.transaction);
}
return event;
});

For the use of BrowserTracing Integrated browser JavaScript Applications ,beforeNavigate The option can be used according to URL Better put navigation/pageload transactions Group together .

import * as Sentry from "@sentry/browser";
import { Integrations } from "@sentry/tracing";
Sentry.init({
// ...
integrations: [
new Integrations.BrowserTracing({
beforeNavigate: context => {
return {
...context,
// You could use your UI's routing library to find the matching
// route template here. We don't have one right now, so do some basic
// parameter replacements.
name: location.pathname
.replace(/\d+/g, "<digits>")
.replace(/[a-f0-9]{32}/g, "<hash>"),
};
},
}),
],
});

Retrieve an Active Transaction

If you want to Spans Attach to... Already in progress transaction in , For example, in the right transaction When grouping , have access to Sentry.getCurrentHub().getScope().getTransaction(). When scope There are running transaction when , This function will return a Transaction object , Otherwise it will return undefined. If you are using BrowserTracing Integrate , By default , We will transaction Attach to Scope, So you can do the following :

function myJsFunction() {
const transaction = Sentry.getCurrentHub()
.getScope()
.getTransaction();
if (transaction) {
let span = transaction.startChild({
op: "encode",
description: "parseAvatarImages",
});
// Do something
span.finish();
}
}

Chinese documents are synchronized to :

 I'm for less .
WeChat :uuhells123.
official account : Hacker afternoon tea .
Thank you for your support !
版权声明
本文为[For less]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121203724736p.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云