SDK Development

  1. Top open source projects Sentry 20.x JS-SDK Design Art ( Design philosophy and principles )
  2. Top open source projects Sentry 20.x JS-SDK Design Art ( Development Foundation )

series

  1. Snuba:Sentry New search infrastructure ( be based on ClickHouse above )
  2. Sentry 10 K8S Cloud native architecture exploration ,Vue App 1 Minutes fast access
  3. Sentry(v20.x) Before you play / Back end monitoring and event log big data analysis , Use Helm Deploy to K8S colony
  4. Sentry(v20.x) JavaScript SDK Three ways to install and load
  5. Sentry(v20.x) JavaScript SDK Configuration details
  6. Sentry(v20.x) JavaScript SDK Basic usage of manually capturing Events
  7. Sentry(v20.x) JavaScript SDK Source Maps Detailed explanation
  8. Sentry(v20.x) JavaScript SDK Troubleshooting
  9. Sentry(v20.x) JavaScript SDK 1 Minutes to start performance monitoring
  10. Sentry(v20.x) JavaScript SDK Management of performance monitoring Transactions
  11. Sentry(v20.x) JavaScript SDK Sampling for performance monitoring Transactions
  12. Sentry(v20.x) JavaScript SDK Enriching Events( Rich event information )
  13. Sentry(v20.x) JavaScript SDK  Data Management( Group questions )

summary

Here’s an implementation of the new Sentry SDK Guide to . It covers the protocol for event submission , And the typical look and behavior of the client .

Write a SDK

SDK At the heart of this is a set of utilities , Used to capture data about abnormal states in an application . Given this data , It will build and send JSON Payload and send it to Sentry The server .

Expected to be used in the production environment SDK Including the following :

  • DSN To configure
  • Elegant fault ( for example Sentry The server is not reachable )
  • Set properties ( for example tags and extra data
  • Support Linux,Windows and OS X( If applicable )

The following needs to be based on Feature Support for :

  • If there is Cookie Data available , Will not be sent by default
  • If there is POST data , Will not be sent by default

Besides , It is strongly recommended that you use the following features :

  • Automatic error capture ( for example , Uncapped exception handler uncaught exception
  • Log framework Integration
  • Non blocking event commit
  • Context data assistant ( for example , Set the current user , Record the crumbs )
  • Event sampling
  • Honor Sentry Of HTTP 429 Retry-After header
  • Send hooks before and after events
  • Local variable values in the stack trace ( On possible platforms )
  • Send one for each event environment. If the user does not detect or set any value , Should be used production.

see also features page , For information about common Sentry SDK Description of function .

End user usage

Usually , For end users , Use SDK There are three steps , No matter what language you use , These three steps look almost the same :

  1. SDK The initialization ( Sometimes hidden from users ):

JavaScript

Sentry.init({dsn: 'https://[email protected]/0'});

Python

Sentry.init({dsn: 'https://[email protected]/0'});
  1. Capture events :

JavaScript

var resultId = Sentry.captureException(myException);

Python

result_id = sentry_sdk.capture_exception(my_exception);
  1. Use the results of event capture :

JavaScript

alert(`Your exception was recorded as ${resultId}`);

Python

print('Your exception was recorded as %s', result_id);

Ideally ,init Allows multiple configuration methods . The first parameter should always be DSN value ( If possible ):

JavaScript

Sentry.init({
    'dsn': 'https://[email protected]/0',
    'foo': 'bar'
})

Please note that :
SDK We should accept an empty DSN As an effective configuration .
If not initialized SDK, Or use empty DSN Initialize the SDK, be SDK No data should be sent over the network , For example, captured exceptions . Depending on the platform ,SDK This will avoid unnecessary initialization , And minimize its runtime footprint .

Besides , You should provide global functions to catch basic messages or exceptions :

  • Sentry.captureMessage(message)
  • Sentry.captureException(exception)

analysis DSN

encourage SDK Any option is allowed through the constructor , But the first parameter must be allowed as DSN character string . The string contains the following bits :

'{PROTOCOL}://{PUBLIC_KEY}:{SECRET_KEY}@{HOST}{PATH}/{PROJECT_ID}'

The final endpoint to which you will send the request is constructed as follows :

 {BASE_URI} = '{PROTOCOL}://{HOST}{PATH}'
'{BASE_URI}/api/{PROJECT_ID}/{ENDPOINT}/'

Sentry Provide the following endpoints :

  • /envelope/ For the use of Envelopes Any submission of .
  • /store/ For submitting simple JSON event .
  • /minidump/ Used to contain minidump Of multipart request .
  • /unreal/ For the Unreal Engine 4 Crash report .
  • /security/ For browsers CSP The report , Usually in the browser instead of SDK To configure .

Information about how to compose the appropriate request payload , See the corresponding endpoint .

for example , Given the following constructor :

Sentry.init({dsn: 'https://[email protected]/1'})

You should parse the following settings :

  • URI = https://sentry.example.com
  • Public Key = public
  • Project ID = 1

For pure JSON The end of the payload POST The request will then be transmitted to :

'https://sentry.example.com/api/1/store/'

Please note that :
DSN Of secret Part is optional , It has now been abandoned . If provided Sentry Future versions of will completely ignore it ,clients It should still be respected . DSN Parsing code must not require setting secret key.

authentication

Expected to be associated with the message body (message body) Send authentication header together (authentication header), The message header is used as the ownership identifier (ownership identifier):

X-Sentry-Auth: Sentry sentry_version=7,
  sentry_client=<client version, arbitrary>,
  sentry_timestamp=<current timestamp>,
  sentry_key=<public api key>,
  sentry_secret=<secret api key>

Only when the DSN Contained in the secret key In part , It must include sentry_secret. Future versions of the agreement will be completely abandoned secret key.

Please note that :
You should be in the header User-Agent Section contains SDK Version string , If auth Not sent in header sentry_client  , The string will be used .

Unable to send custom X-Sentry-Auth In the case of header , You can send the following values through a query string :

?sentry_version=7&sentry_key=<public api key>&sentry_secret=<secret api key>...

sentry_key

  • Essential .public key As SDK Part of the configuration provides .

sentry_version

  • Essential . Protocol version . The current version of the protocol is 7.

sentry_client

  • identification SDK( Including its version ) Any string of . The typical pattern is client_name/client_version.

for example ,Python SDK It might be used as raven-python/1.0 send out .

sentry_timestamp

  • Unix Time stamp , Indicates when this event was generated .

sentry_secret

  • Should be as SDK The key provided as part of the configuration .

The key Has been effectively discarded , But because of some earlier Sentry Versions need it in most cases , therefore SDK The… Should still be released temporarily key. The secret key Will be in Sentry Completely eliminated in future versions of .

HTTP Headers

We recommend always sending the following header :

  • content-type
  • content-length

according to CORS The strategy of , Allow the following additional headers :

  • x-sentry-auth
  • x-requested-with
  • x-forwarded-for
  • origin
  • referer
  • accept
  • authentication
  • authorization
  • content-encoding
  • transfer-encoding

Request compression

Strongly recommended SDK Compress the request body before sending it to the server , To keep the amount of data small . The preferred method is to send content-encoding header . Relay and Sentry Accept the following encoding :

  • gzip: Use LZ77 Compression algorithm .
  • deflate: Use zlib Structure and deflate Compression algorithm .
  • br: Use Brotli Algorithm .

Transfer encoding

It is recommended to use transport encoding only for very large requests (Transfer Encoding). Set the header to transfer-encoding: chunked, This can be omitted content-length header , And require the request body to be wrapped in chunk In the head .

For more details , Please see the MDN.

Read response

After success , You will receive a HTTP Respond to , It includes JSON Payloads and information about committed payloads :

HTTP/1.1 200 OK
Content-Type: application/json
{
  "id": "fc6d8c0c43fc4630ad850ee518f1b9d0"
}

Please note that Sentry The response code that will be used . Always check 200 Respond to , This will confirm that the message has been delivered . A small level of validation happens immediately , This can lead to different response codes ( And news ).

Handling errors

We strongly recommend that you SDK Deal with it properly Sentry Server failure . say concretely ,SDK Must abide by the 429 The status code , And in Retry-After Don’t try to send before . If Sentry Unavailable , be SDK Events should be discarded , Instead of trying again .

You need to debug errors in the development process , Please check the response header and the response body . for example , You may receive a response similar to the following :

HTTP/1.1 400 Bad Request
Content-Type: application/json
X-Sentry-Error: failed to read request body
{
  "detail":"failed to read request body",
  "causes":[
    "failed to decode zlib payload",
    "corrupt deflate stream"
  ]
}

X-Sentry-Error The header and response body do not always contain a message , But they can still help debug the client . When sent out , They will contain precise error messages , This is useful for identifying root causes .

Please note that :
We do not recommend that even if the error response header States Retry-After,SDK And it doesn’t automatically retry the event submission when an error occurs . If the request fails once , It is likely to fail again at the next attempt . Too many retries may result in further rate limiting or Sentry Blocking of the server .

Concurrent ( Scope Scope And hubs Hub)

SDK It should be through hubs and scopes To provide standardized concurrency . Unified API Document “ concurrency ” This is explained in more detail in the chapter .

Integration layer

SDK Where possible, it should be integrated at a lower level , This captures as many runtimes as possible . It means , If SDK You can hook the runtime or framework directly , This is more than requiring users to subclass specific base classes ( Or mixed use helper) preferable . for example ,Python SDK The core functions will be evaluated in the framework monkey Patch , To automatically pick up errors and integrate scope handling .

 I'm for less
WeChat :uuhells123
official account :*** Afternoon tea
Add me WeChat ( Learn from each other ), Official account ( Get more learning materials ~)