diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 1e0e19c4bf064..c0a458e9c1fac 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -2,8 +2,10 @@ # See https://github.com/getsentry/sentry-docs/pull/13662 on how commented codeowners are tagged -# Requiring review from security team for Content-Security-Policy changes +# Requiring review from security team for CSP, Security/Legal Pages, but not IP Ranges **/vercel.json @getsentry/security +/docs/security-legal-pii/security/ @getsentry/security +/docs/security-legal-pii/security/ip-ranges.mdx # Codeowners listed below are used as a reference for the Sentry team to know who to contact for a given area of the codebase. diff --git a/.github/workflows/bump-api-schema-sha.yml b/.github/workflows/bump-api-schema-sha.yml index 14b4190e8b8ae..cbd319f4f4bfc 100644 --- a/.github/workflows/bump-api-schema-sha.yml +++ b/.github/workflows/bump-api-schema-sha.yml @@ -1,15 +1,22 @@ -name: Bump API Schema SHA +name: Bump @sentry/api on: - # This could be run manually, but the general expectation is that this fires - # from GHA in getsentry/sentry-api-schema on changes there. See: + # The API reference is built from the pinned @sentry/api version. getsentry/sentry + # releases it whenever the API spec changes; this picks up the new version. See: # # https://develop.sentry.dev/api/public/#build-process - + # + # The file keeps its old name so existing dispatches still reach it. + schedule: + - cron: '17 * * * *' workflow_dispatch: +# A dispatch and the hourly run must not both push the same bump branch. +concurrency: + group: bump-sentry-api + cancel-in-progress: false jobs: release: runs-on: ubuntu-latest - name: 'Bump API Schema SHA' + name: 'Bump @sentry/api' steps: - name: Get auth token id: token @@ -18,53 +25,18 @@ jobs: app-id: ${{ vars.SENTRY_API_SCHEMA_UPDATER_APP_CLIENT_ID }} private-key: ${{ secrets.SENTRY_API_SCHEMA_UPDATER_PRIVATE_KEY }} owner: getsentry - repositories: | - sentry-docs - sentry-api-schema + repositories: sentry-docs - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: token: ${{ steps.token.outputs.token }} - - name: 'Bump API Schema SHA' - shell: bash + - uses: pnpm/action-setup@02f6c237bd2518259fed6c71566509edfb3f2b74 # v4 + - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v4 + with: + node-version-file: 'package.json' + - name: 'Bump @sentry/api' env: # An elevated token is necessary because with plain github.token # GitHub does not recursively call workflows, which means CI does not # kick off for the PR we're about to create. GITHUB_TOKEN: ${{ steps.token.outputs.token }} - run: | - set -euo pipefail - - git config user.email "271575301+sentry-api-schema-updater[bot]@users.noreply.github.com" - git config user.name "sentry-api-schema-updater[bot]" - - filepath="src/build/resolveOpenAPI.ts" - - # Authenticate to avoid the low unauthenticated rate limit, and fail on - # HTTP errors so an error body never gets written in as the SHA. - sha="$(curl -sSL --fail \ - -H "Authorization: Bearer $GITHUB_TOKEN" \ - -H 'Accept: application/vnd.github.VERSION.sha' \ - 'https://api.github.com/repos/getsentry/sentry-api-schema/commits/main')" - - if [[ ! "$sha" =~ ^[0-9a-f]{40}$ ]]; then - echo "::error::Expected a 40-character commit SHA from the GitHub API, got: $sha" - exit 1 - fi - echo "Latest commit to 'getsentry/sentry-api-schema' is $sha" - - sed -i -e "s|^const SENTRY_API_SCHEMA_SHA =.*$|const SENTRY_API_SCHEMA_SHA = '$sha';|g" "$filepath" - echo "Updated $filepath" - - if git diff --quiet "$filepath"; then - echo "No changes to $filepath, skipping." - exit 0 - fi - - branch="bot/bump-api-schema-to-${sha:0:8}" - git checkout -b "$branch" - git add "$filepath" - git commit -m "Bump API schema to ${sha:0:8}" - git push --set-upstream origin "$branch" - - gh pr create --fill - gh pr merge --squash --admin -d + run: sh scripts/bump-sentry-api.sh diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 92ffeabdffd99..9238ddc5a98fc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,5 +1,3 @@ -default_language_version: - node: "22" exclude: '\.snap|node_modules$' repos: - repo: https://github.com/pre-commit/pre-commit-hooks @@ -23,13 +21,20 @@ repos: - id: flake8 - id: fix-encoding-pragma args: ['--remove'] + - repo: https://github.com/shellcheck-py/shellcheck-py + rev: v0.10.0.1 + hooks: + - id: shellcheck + args: ['--shell=sh', '--enable=check-extra-masked-returns'] + # Older scripts are bash and predate this hook. + files: '^scripts/bump-sentry-api\.sh$' - repo: local hooks: - id: prettier name: Prettier description: This hook runs Prettier on JavaScript and TypeScript files - entry: prettier - language: node + entry: pnpm exec prettier + language: system files: '\.[cm]?[jt]sx?$' exclude: 'node_modules' types: [text] @@ -37,8 +42,8 @@ repos: - id: eslint name: eslint description: This hook runs eslint on JavaScript and TypeScript files - entry: eslint - language: node + entry: pnpm exec eslint + language: system files: '\.[cm]?[jt]sx?$' exclude: 'node_modules' types: [text] diff --git a/AGENTS.md b/AGENTS.md index 0c692c1be4f92..90f746d72ed98 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -98,6 +98,7 @@ When writing requirements in `develop-docs/`: - **ALWAYS** run `/brand-guidelines` to audit any user-facing content before committing. See `.agents/skills/brand-guidelines/SKILL.md` - Use `docs-review` skill for Sentry style and voice review. See `.claude/skills/docs-review/SKILL.md` - Use `technical-docs` skill when writing or reviewing SDK documentation. See `.claude/skills/technical-docs/SKILL.md` +- Quick starts set `runtime` (for example `node` or `cloudflare`) in their frontmatter. The page then shows a runtime selector at the top that links the quick starts of the same guide for the other runtimes ## LLM-Friendly MD Exports diff --git a/app/api/platform-content/[platform]/[runtime]/[framework]/[...includePath]/route.ts b/app/api/platform-content/[platform]/[runtime]/[framework]/[...includePath]/route.ts new file mode 100644 index 0000000000000..acfaca67ac4f3 --- /dev/null +++ b/app/api/platform-content/[platform]/[runtime]/[framework]/[...includePath]/route.ts @@ -0,0 +1,161 @@ +import { + PlatformContentPayload, + RUNTIMES, +} from 'sentry-docs/components/frameworkSelector/frameworks'; +import {resolvePlatformContent} from 'sentry-docs/components/platformContent'; +import {getFileBySlugWithCache} from 'sentry-docs/mdx'; + +/** + * Serves the compiled MDX of a `` include as it applies to a framework running + * on a runtime, so a runtime's page can swap in framework snippets client-side + * (see ``). + * + * Only the combinations from `generateStaticParams` are built; there is no runtime rendering. + */ + +export const dynamic = 'force-static'; +export const dynamicParams = false; + +export function generateStaticParams() { + return Object.entries(RUNTIMES).flatMap(([runtime, {frameworks, includePaths}]) => + frameworks.flatMap(({key: framework}) => + includePaths.map(includePath => ({ + platform: 'javascript', + runtime, + framework, + includePath: includePath.split('/'), + })) + ) + ); +} + +type SlugFile = Awaited>; + +async function tryGetFile(slug: string): Promise { + try { + return await getFileBySlugWithCache(slug); + } catch { + return undefined; + } +} + +/** + * Resolves an include for a framework on a runtime: + * 1. `..`, for snippets specific to both + * 2. On Node.js, the framework guide's content, which falls back to Node.js + * Elsewhere, only a `.` snippet, to not pull in Node.js content + * 3. The runtime guide's own content + */ +async function resolveForFramework( + includePath: string, + platform: string, + runtime: string, + framework: string +): Promise { + const base = `platform-includes/${includePath}/${platform}`; + + const doc = await tryGetFile(`${base}.${runtime}.${framework}`); + if (doc) { + return doc; + } + + if (runtime === 'node') { + return resolvePlatformContent({ + includePath, + path: ['platforms', platform, 'guides', framework], + }); + } + + return ( + (await tryGetFile(`${base}.${framework}`)) ?? + resolvePlatformContent({ + includePath, + path: ['platforms', platform, 'guides', runtime], + }) + ); +} + +const INCLUDE_RE = / Promise, + payload: PlatformContentPayload +) { + for (const [, rawName] of source.matchAll(INCLUDE_RE)) { + const name = rawName.replace(/\.mdx$/, ''); + if (name in payload.includes) { + continue; + } + // Missing includes render nothing, same as . + const doc = await tryGetFile(`includes/${name}`); + if (doc) { + payload.includes[name] = doc.mdxSource; + await collectNested(doc.matter.content, resolve, payload); + } + } + + for (const [, includePath] of source.matchAll(PLATFORM_CONTENT_RE)) { + if (includePath in payload.platformContents) { + continue; + } + const doc = await resolve(includePath); + payload.platformContents[includePath] = doc?.mdxSource ?? null; + if (doc) { + await collectNested(doc.matter.content, resolve, payload); + } + } +} + +async function buildPayload( + includePath: string, + resolve: (includePath: string) => Promise +): Promise { + const doc = await resolve(includePath); + const payload: PlatformContentPayload = { + changed: false, + code: doc?.mdxSource ?? null, + includes: {}, + platformContents: {}, + }; + if (doc) { + await collectNested(doc.matter.content, resolve, payload); + } + return payload; +} + +export async function GET( + _request: Request, + { + params, + }: { + params: Promise<{ + framework: string; + includePath: string[]; + platform: string; + runtime: string; + }>; + } +) { + const {platform, runtime, framework, includePath} = await params; + const resolve = (path: string) => + resolveForFramework(path, platform, runtime, framework); + + const resolveForRuntime = (path: string) => + resolvePlatformContent({ + includePath: path, + path: ['platforms', platform, 'guides', runtime], + }); + + const [payload, runtimePayload] = await Promise.all([ + buildPayload(includePath.join('/'), resolve), + buildPayload(includePath.join('/'), resolveForRuntime), + ]); + payload.changed = + payload.code !== runtimePayload.code || + JSON.stringify(payload.platformContents) !== + JSON.stringify(runtimePayload.platformContents); + + return Response.json(payload); +} diff --git a/app/globals.css b/app/globals.css index 0bf7f57a9d819..18c1e69c0a170 100644 --- a/app/globals.css +++ b/app/globals.css @@ -1,4 +1,19 @@ -@import '@radix-ui/themes/styles.css'; +/* + * Radix Themes, split up so we only ship the color scales we use. The all-in-one + * styles.css carries all 30 scales and was the bulk of our render-blocking CSS. + * Using a new Radix color (accentColor, color="..." or var(---N))? Add + * its scale here, or it renders unstyled. Order mirrors styles.css. + */ +@import '@radix-ui/themes/tokens/colors/gray.css'; +@import '@radix-ui/themes/tokens/colors/sand.css'; +@import '@radix-ui/themes/tokens/colors/amber.css'; +@import '@radix-ui/themes/tokens/colors/green.css'; +@import '@radix-ui/themes/tokens/colors/iris.css'; +@import '@radix-ui/themes/tokens/colors/red.css'; +@import '@radix-ui/themes/tokens/colors/yellow.css'; +@import '@radix-ui/themes/tokens/base.css'; +@import '@radix-ui/themes/components.css'; +@import '@radix-ui/themes/utilities.css'; @tailwind base; @tailwind components; diff --git a/app/layout.tsx b/app/layout.tsx index 1bab67dbe638b..0f63de21c0b57 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -9,7 +9,7 @@ import {SkipToContent} from 'sentry-docs/components/skipToContent'; import {ThemeProvider} from 'sentry-docs/components/theme-provider'; const rubik = Rubik({ - weight: ['400', '500', '700'], + weight: ['400', '500', '600', '700'], style: ['normal', 'italic'], subsets: ['latin'], variable: '--font-rubik', diff --git a/app/platform-redirect/page.tsx b/app/platform-redirect/page.tsx index 8ae7d7f0d7a64..858edc12f0828 100644 --- a/app/platform-redirect/page.tsx +++ b/app/platform-redirect/page.tsx @@ -7,7 +7,7 @@ import {SmartLink} from 'sentry-docs/components/smartLink'; import {extractPlatforms, getDocsRootNode, nodeForPath} from 'sentry-docs/docTree'; import {setServerContext} from 'sentry-docs/serverContext'; -import {platformUrlFor, sanitizeNext} from './utils'; +import {landingPageFallbackGuide, platformUrlFor, sanitizeNext} from './utils'; export const metadata: Metadata = { robots: 'noindex', @@ -142,9 +142,11 @@ export default async function Page(props: { const requestedPlatform = Array.isArray(platform) ? platform[0] : platform; if (requestedPlatform) { - const validPlatform = platformOrGuideList.find( - p => p.key === requestedPlatform?.toLowerCase() - ); + const requestedKey = requestedPlatform.toLowerCase(); + const fallbackKey = landingPageFallbackGuide(rootNode, requestedKey); + const validPlatform = + platformOrGuideList.find(p => p.key === requestedKey) ?? + platformOrGuideList.find(p => p.key === fallbackKey); if (validPlatform) { return redirect(platformUrlFor(validPlatform.url, sanitized)); } diff --git a/app/platform-redirect/utils.spec.ts b/app/platform-redirect/utils.spec.ts index 3b14c5b7f79df..a55e6f20f5e43 100644 --- a/app/platform-redirect/utils.spec.ts +++ b/app/platform-redirect/utils.spec.ts @@ -1,11 +1,54 @@ +import type {DocNode} from 'sentry-docs/docTree'; import {describe, expect, it} from 'vitest'; -import {platformUrlFor, sanitizeNext} from './utils'; +import {landingPageFallbackGuide, platformUrlFor, sanitizeNext} from './utils'; const path = (next: string) => sanitizeNext(next).pathname; const hash = (next: string) => sanitizeNext(next).hash; const REJECTED = {pathname: '', hash: ''}; +describe('landingPageFallbackGuide', () => { + const node = ( + slug: string, + frontmatter: Record = {}, + children: DocNode[] = [] + ) => ({slug, frontmatter, children, missing: false, path: slug}) as unknown as DocNode; + + const rootNode = node('', {}, [ + node('platforms', {}, [ + node('javascript', {}, [ + node('guides', {}, [ + node('express', { + inheritCommonContent: false, + fallbackGuide: 'javascript.node', + }), + node('nestjs', {fallbackGuide: 'javascript.node'}), + node('cordova', {inheritCommonContent: false}), + ]), + ]), + ]), + ]); + + it('returns the fallback guide of a landing page guide', () => { + expect(landingPageFallbackGuide(rootNode, 'javascript.express')).toBe( + 'javascript.node' + ); + }); + + it('returns nothing for a guide that inherits the common content', () => { + expect(landingPageFallbackGuide(rootNode, 'javascript.nestjs')).toBeUndefined(); + }); + + it('returns nothing for a landing page guide without a fallback guide', () => { + expect(landingPageFallbackGuide(rootNode, 'javascript.cordova')).toBeUndefined(); + }); + + it('returns nothing for a platform or an unknown guide', () => { + expect(landingPageFallbackGuide(rootNode, 'javascript')).toBeUndefined(); + expect(landingPageFallbackGuide(rootNode, 'javascript.unknown')).toBeUndefined(); + }); +}); + describe('sanitizeNext', () => { it('should return an empty string for external URLs', () => { expect(sanitizeNext('http://example.com')).toEqual(REJECTED); diff --git a/app/platform-redirect/utils.ts b/app/platform-redirect/utils.ts index e646c519afcab..816318c19a356 100644 --- a/app/platform-redirect/utils.ts +++ b/app/platform-redirect/utils.ts @@ -1,3 +1,25 @@ +import {DocNode, nodeForPath} from 'sentry-docs/docTree'; + +/** + * Returns the `fallbackGuide` key (e.g. `javascript.node`) of a guide that is a single + * landing page (`inheritCommonContent: false`), such as `javascript.express`. The pages + * that such a guide does not have are in its fallback guide. + */ +export function landingPageFallbackGuide( + rootNode: DocNode, + key: string +): string | undefined { + const [platform, guide] = key.split('.'); + if (!guide) { + return undefined; + } + const guideNode = nodeForPath(rootNode, ['platforms', platform, 'guides', guide]); + if (guideNode?.frontmatter.inheritCommonContent !== false) { + return undefined; + } + return guideNode.frontmatter.fallbackGuide; +} + // Parse base only — never part of the return value, and only compared against itself const PARSE_BASE = 'https://sanitize.invalid'; diff --git a/develop-docs/backend/api/public.mdx b/develop-docs/backend/api/public.mdx index a64e88bd63f4e..bbcbca4a5378a 100644 --- a/develop-docs/backend/api/public.mdx +++ b/develop-docs/backend/api/public.mdx @@ -390,29 +390,27 @@ When you open the pull request, please add a screenshot of the page or pages you ### Build Process -The openapi-diff test will fail when CI runs on your pull request, this is expected and meant to -highlight the diff. It is not required to merge. +The `openapi-diff` workflow compares your pull request's schemas with master where your branch +started. Its **Public API changelog** job lists your public API changes in the job summary and +never fails. Its **RPC schema breaking changes** job fails when an RPC method changes in a way that +breaks existing callers. To see the changelog locally, run `make build-api-docs`, then +`make diff-api-docs`. -Once you make changes to an endpoint and merge the change into Sentry, a series of GitHub Actions -will be triggered to make your changes automatically go live: +Once you make changes to an endpoint and merge the change into Sentry, these steps make your changes go live: 1. The [openapi workflow in - sentry](https://github.com/getsentry/sentry/blob/master/.github/workflows/openapi.yml) updates - the schema in [sentry-api-schema](https://github.com/getsentry/sentry-api-schema) with the - OpenAPI build artifact. -2. The [cascade-to-sentry-docs workflow in - sentry-api-schema](https://github.com/getsentry/sentry-api-schema/blob/main/.github/workflows/cascade-to-sentry-docs.yml) - reacts to the push to `main` in (1) by triggering the [bump-api-schema-sha workflow in - sentry-docs](https://github.com/getsentry/sentry-docs/blob/master/.github/workflows/bump-api-schema-sha.yml). -3. The [bump-api-schema-sha workflow in + sentry](https://github.com/getsentry/sentry/blob/master/.github/workflows/openapi.yml) builds + the schema. When the schema changed since the last release, sentry releases a new version of + the [`@sentry/api`](https://www.npmjs.com/package/@sentry/api) package from + `static/packages/api`. The package's `@sentry/api/docs` export holds the API reference data. +2. The [bump workflow in sentry-docs](https://github.com/getsentry/sentry-docs/blob/master/.github/workflows/bump-api-schema-sha.yml) - fetches the latest commit SHA from `sentry-api-schema` and writes it into the correct file, then - makes and merges a PR in `sentry-docs`, which kicks off a deploy via Vercel to - https://docs.sentry.io/api/. + runs hourly. When npm has a newer `@sentry/api`, it pins that version, then makes and merges + a PR in `sentry-docs`, which kicks off a deploy via Vercel to https://docs.sentry.io/api/. ## Troubleshooting API Docs Tests -NOTE: The `openapi-diff` test is supposed to fail when CI runs on your pull request as it is meant to highlight the schema changes. It is not required to merge. +NOTE: The **Public API changelog** job of `openapi-diff` never fails. Read its job summary to check your public API changes. **Problem**: `TypeError: Cannot read properties of null (reading 'type')` diff --git a/develop-docs/backend/issue-platform/issue-types/index.mdx b/develop-docs/backend/issue-platform/issue-types/index.mdx index 316bd2e4cb50d..901f8dfbb39ba 100644 --- a/develop-docs/backend/issue-platform/issue-types/index.mdx +++ b/develop-docs/backend/issue-platform/issue-types/index.mdx @@ -7,7 +7,7 @@ An issue type is a way to group related issues together. Examples include `metri ## Register an Issue Type -To register a new issue type you need to subclass `GroupType` +To register a new issue type you need to subclass `GroupType` When registering the class, set the following required attributes on the class: @@ -18,13 +18,13 @@ When registering the class, set the following required attributes on the class: - `description`: str - A human-readable description of your issue type. - `category`: int - - Categories are used to group related issue types together. Use one of the existing categories defined in this enum or add a new one. + - Categories are used to group related issue types together. Use one of the existing categories defined in this enum or add a new one. Don't use the categories marked as deprecated (`PERFORMANCE`, `PROFILE`, `CRON`, `REPLAY`, `UPTIME`, `METRIC_ALERT`). You may also set these optional attributes: - `released`: bool - Whether this issue type has been released to all customers. See Releasing your issue type. -- `noise_config`: NoiseConfig | None +- `noise_config`: NoiseConfig | None - A `NoiseConfig` that allows you to set policy on how many times a fingerprint must occur in a period of time before an issue is created. NoiseConfig has two attributes: - `ignore_limit`: int - How many occurrences need to occur before we create a new issue. @@ -43,7 +43,7 @@ class ProfileFileIOGroupType(GroupType): type_id = 2001 slug = "profile_file_io_main_thread" description = "File I/O on Main Thread" - category = GroupCategory.PROFILE.value + category = GroupCategory.MOBILE.value ``` and here's one with `noise_config` configured @@ -54,7 +54,7 @@ class ProfileFileIOGroupType(GroupType): type_id = 2001 slug = "profile_file_io_main_thread" description = "File I/O on Main Thread" - category = GroupCategory.PROFILE.value + category = GroupCategory.MOBILE.value noise_config = NoiseConfig(5, timedelta(days=2)) ``` diff --git a/develop-docs/development-infrastructure/python-dependencies.mdx b/develop-docs/development-infrastructure/python-dependencies.mdx index b3bb69875ae4c..36f3cbeacc241 100644 --- a/develop-docs/development-infrastructure/python-dependencies.mdx +++ b/develop-docs/development-infrastructure/python-dependencies.mdx @@ -45,7 +45,7 @@ If you need to make modifications to a dependency and need to deploy the result before it is accepted upstream, you must fork the dependency and publish it to pypi and internal pypi. 1. Fork into the `getsentry` organization and make your changes. -2. Add craft configuration to publish to pypi+internal pypi ([example](https://github.com/getsentry/sentry-forked-djangorestframework-stubs/pull/1)). +2. Add craft configuration to publish to pypi+internal pypi ([example](https://github.com/getsentry/sentry-forked-email-reply-parser/pull/1)). 3. Add the dependency to your repository. diff --git a/develop-docs/integrations/slack/index.mdx b/develop-docs/integrations/slack/index.mdx index 6cf9addb47cc3..af0cd177ed9f2 100644 --- a/develop-docs/integrations/slack/index.mdx +++ b/develop-docs/integrations/slack/index.mdx @@ -70,13 +70,12 @@ On the same page under **Scopes** you'll need to add **Bot Scopes** and **User S Add the following scopes to **Bot Scopes**: - `app_mentions:read`, `assistant:write`, `channels:history` and `groups:history` are used for Seer + `app_mentions:read`, `channels:history`, and `groups:history` are used for Seer Features which are not currently available for self-hosted. You can freely omit them. | Scope | Reason | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `assistant:write` | Enables accessing the app as a personal Slack Agent. | | `app_mentions:read` | Receive `app_mention` events when the bot is mentioned (e.g. @Sentry) in a message. | | `channels:read` | List and validate public channels when configuring alert destinations, and resolve channel names to IDs. | | `channels:history` | (Optional) Allows Sentry to read messages from public channels. Sentry uses this to gather thread context for conversations with Seer Agent. | diff --git a/develop-docs/sdk/foundations/client/data-collection/index.mdx b/develop-docs/sdk/foundations/client/data-collection/index.mdx index 4c16fa0c5e696..64b771931d822 100644 --- a/develop-docs/sdk/foundations/client/data-collection/index.mdx +++ b/develop-docs/sdk/foundations/client/data-collection/index.mdx @@ -2,12 +2,15 @@ title: Data Collection description: Configuration for what data SDKs collect by default, including technical context, PII, and sensitive data. spec_id: sdk/foundations/client/data-collection -spec_version: 0.15.0 +spec_version: 0.16.0 spec_status: candidate spec_depends_on: - id: sdk/foundations/client version: ">=1.0.0" spec_changelog: + - version: 0.16.0 + date: 2026-09-10 + summary: Explain migration from `sendDefaultPii` for SDKs that can't cleanly map previous behavior to data collection. - version: 0.15.0 date: 2026-09-29 summary: "Attach cookie headers as one string-array span attribute (`name=value` elements) instead of one attribute per cookie name. Filter nameless cookie segments and unparseable cookie strings." @@ -745,8 +748,9 @@ init({ ### Migration from `sendDefaultPii` -- **`sendDefaultPii: true`** (legacy) → omit `dataCollection` entirely; the new defaults already populate `user.*` and collect HTTP bodies. Add overrides only to restrict collection. -- **`sendDefaultPii: false`** (legacy) → opt out of the categories the new defaults collect. +#### Migration guidance for users +- Previous **`sendDefaultPii: true`** → users can omit `dataCollection` entirely; the new defaults already populate `user.*` and collect HTTP bodies. Add overrides only to restrict collection. +- Previous **`sendDefaultPii: false`** → users should opt out of the categories the new defaults collect. The new defaults collect **more data** than either legacy setting did. User identity, generative AI content, HTTP request/response bodies, and file paths are now on by default, and more HTTP headers and cookies are collected. This config restricts collection to roughly match the previous behavior of `sendDefaultPii: false`: @@ -778,6 +782,21 @@ init({ }); ``` +#### Migration in SDKs + +If the SDK can cleanly map what `sendDefaultPii` did to data collection options, it **MAY** backfill data collection options from the configured `sendDefaultPii` value. + +If the SDK cannot cleanly map the `sendDefaultPii` behavior to data collection options, it **MUST NOT** derive data collection options from the configured `sendDefaultPii` value. Instead, the following rules apply: +- If the user sets at least one data collection option, the SDK **MUST** ignore `sendDefaultPii`. The SDK **MUST** apply the options the user set, and the spec defaults for all `dataCollection` options. This also means that the SDK might send more data when `sendDefaultPii` was set to `false` before, so users should be made aware of that. + +- If the user sets no data collection options, the SDK **MUST** keep the legacy `sendDefaultPii` behavior unchanged. +This prevents breaking changes in PII filtering and allows customers to migrate to data collection at their own pace. Customers may keep using `sendDefaultPii` without changes to SDK behavior as long as they don't opt into data collection. + +Examples of the SDK not cleanly mapping: +- mixed behavior between integrations (e.g. one integration sent cookies even with `sendDefaultPii` = `false` while another did not) +- hard coded filter terms that don't match the ones defined in data collection spec (e.g. sensitive http header names) +- sensitive values were omitted and are now attached as `[Filtered]` + --- ## Changelog diff --git a/develop-docs/sdk/foundations/envelopes/index.mdx b/develop-docs/sdk/foundations/envelopes/index.mdx index 4dfbbb16d251e..8c7cdd507d7bb 100644 --- a/develop-docs/sdk/foundations/envelopes/index.mdx +++ b/develop-docs/sdk/foundations/envelopes/index.mdx @@ -343,7 +343,7 @@ These limits are subject to future change and defined currently as (see [Relay c - *200 MiB* for an envelope after decompression including all envelope items. - *1 MiB* for event (errors and transactions), span, log, and metric (statsd, buckets, meta) envelope items. -- *2 KiB* for each metric within an envelope. Relay discards the entire envelope if the one of the metrics exceeds 2 KiB. +- *1 MiB* for each trace metric within a `trace_metric` item. Relay discards only the metrics that exceed the limit. - *100 KiB* for monitor check-in items - *4 KiB* for client report items - *50 MiB* for profile items diff --git a/develop-docs/sdk/telemetry/client-reports.mdx b/develop-docs/sdk/telemetry/client-reports.mdx index b824451590bf9..698521ec97b1e 100644 --- a/develop-docs/sdk/telemetry/client-reports.mdx +++ b/develop-docs/sdk/telemetry/client-reports.mdx @@ -2,12 +2,15 @@ title: Client Reports description: SDK self-reporting protocol for tracking discarded events and their discard reasons. spec_id: sdk/telemetry/client-reports -spec_version: 1.25.0 +spec_version: 1.26.0 spec_status: stable spec_depends_on: - id: sdk/foundations/transport/envelopes version: ">=1.0.0" spec_changelog: + - version: 1.26.0 + date: 2026-11-06 + summary: Broadened `invalid` discard reason to cover any data dropped because it is invalid - version: 1.25.0 date: 2026-10-08 summary: Clarified that discarded envelopes are counted per contained item, not as a quantity of 1 @@ -366,7 +369,7 @@ Each outcome object in `discarded_events` has: - + ### Discard Reasons @@ -387,7 +390,7 @@ The following discard reasons are defined for `discarded_events`: | `backpressure` | 1.13.0 | Downsampling due to system load. | | `buffer_overflow` | 1.15.0 | SDK internal buffer (e.g., breadcrumbs buffer) overflowed. | | `ignored` | 1.16.0 | Telemetry item was ignored by the SDK (e.g., a span was ignored by `ignore_spans`; can also be used by other deny-list mechanisms). | -| `invalid` | 1.17.0 | Failed validation (e.g., replay session exceeded maximum allowed length). | +| `invalid` | 1.17.0 | Telemetry item failed validation or (since 1.26.0) was otherwise invalid, and no more specific reason applies. | | `no_parent_span` | 1.22.0 | Span was not started or dropped because no parent span was present at span start (for example, auto-instrumented spans suppressed when the request happens outside an active span). | | `callback_error` | 1.24.0 | A user-provided callback (e.g., `before_send`, `traces_sampler`) threw an error. | diff --git a/develop-docs/sdk/telemetry/traces/modules/ai-agents.mdx b/develop-docs/sdk/telemetry/traces/modules/ai-agents.mdx index ae60466096767..4b200f07353b2 100644 --- a/develop-docs/sdk/telemetry/traces/modules/ai-agents.mdx +++ b/develop-docs/sdk/telemetry/traces/modules/ai-agents.mdx @@ -38,7 +38,7 @@ Valid examples: gen_ai.invoke_agent ├── gen_ai.chat ├── gen_ai.memory -├── gen_ai.extraction +├── gen_ai.extract ├── gen_ai.chat ├── gen_ai.execute_tool ├── gen_ai.chat @@ -49,7 +49,7 @@ gen_ai.invoke_agent ``` gen_ai.chat -gen_ai.extraction +gen_ai.extract gen_ai.invoke_agent ├── gen_ai.chat ├── gen_ai.execute_tool @@ -77,7 +77,7 @@ Describes AI agent invocation. Agent invocations represent operations that can include multiple model calls, or some auxiliary work that goes beyond transforming the model input and output. - Span `op` is `"gen_ai.invoke_agent"`. -- Span `name` is `"invoke_agent {gen_ai.agent.name}"`. (e.g. `"invoke_agent Weather Agent"`) **[2]** +- Span `name` is `"invoke_agent {gen_ai.agent.name}"`. (e.g. `"invoke_agent Weather Agent"`) In some agent libraries, the agent name is optional, and some do not provide the user an option to name their agents. In these cases, the span name is `"invoke_agent {call_id}"`, where `call_id` is some user-provided identifier for the agent invocation. For example, `functionId` in Vercel AI. - Attribute `gen_ai.operation.name` is `"invoke_agent"`. - Attribute `gen_ai.agent.name` is the agent's name. (e.g. `"Weather Agent"`). As a fallback to `gen_ai.agent.name`, the product also interprets `gen_ai.function_id` as an agent name for libraries that let users set a tracing identifier on a per-invocation basis. - If relevant, the `gen_ai.pipeline.name` attribute is the name of the AI workflow, pipeline or chain within which the agent operates. (e.g. `"weather-pipeline"`) @@ -100,40 +100,46 @@ Additional attributes on the span: ### Request Data -| Attribute | Type | Description | Example | -| :--------------------------------- | :----- | :----------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------- | -| `gen_ai.input.messages` | string | List of dictionaries describing the messages (prompts) sent to the LLM. **[0]**, **[1]** | `'[{"role": "user", "parts": [{"type": "text", "content": "..."}]}]'` | -| `gen_ai.tool.definitions` | string | List of dictionaries describing the available tools. **[0]** | `'[{"name": "random_number", "description": "..."}, ...]'` | -| `gen_ai.system_instructions` | string | The system instructions passed to the model. | `"You are a helpful assistant."` | -| `gen_ai.request.max_tokens` | int | Model configuration parameter. | `500` | -| `gen_ai.request.seed` | string | Seed for reproducible outputs. | `"12345"` | -| `gen_ai.request.frequency_penalty` | float | Model configuration parameter. | `0.5` | -| `gen_ai.request.presence_penalty` | float | Model configuration parameter. | `0.5` | -| `gen_ai.request.temperature` | float | Model configuration parameter. | `0.1` | -| `gen_ai.request.top_p` | float | Model configuration parameter. | `0.7` | -| `gen_ai.request.top_k` | int | Limits model to K most likely next tokens. | `40` | -| `gen_ai.request.reasoning.level` | string | The reasoning or thinking effort level requested for a GenAI model. Supported values vary by provider. | `"medium"` | + ### Response Data -| Attribute | Type | Description | Example | -| :------------------------------------ | :------ | :------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------- | -| `gen_ai.output.messages` | string | Stringified array of message objects representing the model's output. **[0]**, **[1]** | `'[{"role": "assistant", "parts": [{"type": "text", "content": "..."}]}]'` | -| `gen_ai.response.finish_reasons` | string | The reason why the model stopped generating. | `"stop"` | -| `gen_ai.response.id` | string | Unique identifier for the completion. | `"chatcmpl-abc123"` | -| `gen_ai.response.streaming` | boolean | Whether response was streamed asynchronously. | `true` | -| `gen_ai.response.time_to_first_chunk` | double | Seconds until first response chunk in streaming. | `0.5` | + ### Token Usage Data -| Attribute | Type | Description | Example | -| :----------------------------------------- | :--- | :----------------------------------------------------------------------------------------------------------------------------- | :------ | -| `gen_ai.usage.input_tokens` | int | The number of tokens used in the AI input (prompt), including cached tokens. | `60` | -| `gen_ai.usage.cache_read.input_tokens` | int | The number of cached tokens used in the AI input (prompt). | `50` | -| `gen_ai.usage.cache_creation.input_tokens` | int | Tokens written to cache when processing input. | `20` | -| `gen_ai.usage.output_tokens` | int | The number of tokens used in the AI output, including reasoning tokens. | `130` | -| `gen_ai.usage.reasoning.output_tokens` | int | The number of tokens used for reasoning. | `30` | -| `gen_ai.usage.total_tokens` | int | The sum of `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. | `190` | + ## Embedding Span @@ -148,10 +154,9 @@ This span represents a request to encode input into numeric vector embeddings. Additional attributes on the span: -| Attribute | Type | Description | Example | -| :-------------------------- | :----- | :-------------------------------------- | :-------------- | -| `gen_ai.embeddings.input` | string | Input to embed. | "Hello, world!" | -| `gen_ai.usage.input_tokens` | int | The number of tokens used in the input. | `60` | + ## Execute Tool Span @@ -165,12 +170,62 @@ Describes a tool execution. Additional attributes on the span: -| Attribute | Type | Description | Example | -| :--------------------------- | :----- | :------------------------------------------------------------------------------------------------------------- | :----------------------------------------- | -| `gen_ai.tool.name` | string | Name of the tool executed. | `"random_number"` | -| `gen_ai.tool.description` | string | Description of the tool executed. | `"Tool returning a random number"` | -| `gen_ai.tool.call.arguments` | string | Arguments of the tool call (stringified). | `'{"max":10}'` | -| `gen_ai.tool.call.result` | string | Result of the tool call (stringified). | `"7"` | + + +## Decision Span + +Describes a decision on generated content against a set of questions, such as grading a model's reply for accuracy or classifying a support message, for example from TypeSafe Jev. Sentry shows decisions as their own rows in the conversation transcript and timeline, with dedicated **Input** and **Output** views. + +- Span `op` is `"gen_ai.decide"`. +- Span `name` is `"decide {gen_ai.request.model}"`. (e.g. `"decide typesafe/jev-1.13"`) +- Attribute `gen_ai.operation.name` is `"decide"`. Decisions share the `ai_client` operation type with model calls, so this attribute is what tells them apart. +- Attribute `gen_ai.request.model` is the requested model. (e.g. `"typesafe/jev-1.13"`) Without a model, Relay doesn't classify the span as `ai_client`. +- Attribute `gen_ai.response.model` is the concrete response model, if the provider reports one. (e.g. `"typesafe/jev-1.13-20260917"`) +- If the decision runs under an agent, the `gen_ai.agent.name` attribute is the name of the agent. (e.g. `"Support Agent"`) + +Additional attributes on the span: + + + +`gen_ai.input.messages` holds a one-element array with the content being evaluated (`state`) and the questions asked about it (`questions`). `gen_ai.output.messages` holds a one-element array with the answers (`answers`), keyed by the same question names. + +## Extraction Span + +Describes an extraction of typed fields from an input, such as the total and due date of an invoice, for example from Cloudflare Clairic. The model can extract values that are in the input, compute values from them, and estimate or forecast values that the input doesn't determine. + +- Span `op` is `"gen_ai.extract"`. +- Span `name` is `"extract {gen_ai.request.model}"`. (e.g. `"extract @cf/cloudflare/clairic"`) +- Attribute `gen_ai.operation.name` is `"extract"`. +- Attribute `gen_ai.request.model` is the requested model. (e.g. `"@cf/cloudflare/clairic"`) +- Attribute `gen_ai.response.model` is the concrete response model, if the provider reports one. (e.g. `"clairic"`) +- If the extraction runs under an agent, the `gen_ai.agent.name` attribute is the name of the agent. (e.g. `"Billing Agent"`) + +Additional attributes on the span: + + + +`gen_ai.input.messages` holds a one-element array with the request body as the caller passed it, without `model`. `gen_ai.output.messages` holds a one-element array with the response body as the provider returned it, without `model` and `usage`. Don't send the other usage counts that the provider reports (such as Clairic's `state_tokens`, `image_tokens`, `schema_tokens`, and `passes`). `gen_ai.usage.input_tokens` already includes them. ## Derived by Relay @@ -183,17 +238,3 @@ Relay sets these attributes during ingestion: - `gen_ai.context.window_size` is looked up from the model metadata registry by `gen_ai.response.model`. - `gen_ai.context.utilization` is computed as `gen_ai.usage.total_tokens / gen_ai.context.window_size`. - `gen_ai.cost.input_tokens`, `gen_ai.cost.output_tokens`, and `gen_ai.cost.total_tokens` are calculated from token counts and per-token pricing in the model registry. - - -**[0]:** - -Span attributes only allow primitive data types (like `int`, `float`, `boolean`, `string`). This means you need to use a stringified version of a list of dictionaries. Do NOT set the object/array `[{"foo": "bar"}]` but rather the string `'[{"foo": "bar"}]'` (must be parsable JSON). - -**[1]:** - -Messages use the format `{role, parts}` where `parts` is an array of typed objects: `[{"role": "user", "parts": [{"type": "text", "content": "..."}]}]`. The `role` must be `"user"`, `"assistant"`, `"tool"`, or `"system"`. Each part has a `type`; common types include `"text"` (user-visible content), `"reasoning"` (internal thinking/chain-of-thought), `"tool_call"`, and `"tool_call_response"`. Use `{"type": "reasoning", "content": "..."}` for the model's thinking output — Sentry surfaces it separately and does not render it as a user-visible message in Conversations, so do not represent thinking content as a `"text"` part. For backwards compatibility, the legacy format `{role, content}` is also accepted. - -**[2]** - -In some agent libraries, the agent name is optional, and some do not provide the user an option to name their agents. -In these cases, the span name is `"invoke_agent {call_id}"`, where `call_id` is some user-provided identifier for the agent invocation. For example, `functionId` in Vercel AI. diff --git a/develop-docs/services/objectstore.mdx b/develop-docs/services/objectstore.mdx index 385009640fe89..692761bf93234 100644 --- a/develop-docs/services/objectstore.mdx +++ b/develop-docs/services/objectstore.mdx @@ -199,8 +199,22 @@ this configuration automatically. The central Objectstore route already exists. Don't create another route for a new calling service. Instead, configure the client endpoint as `http://objectstore` and route the `objectstore` hostname through the service's -Envoy sidecar. You can find a complete example in -`k8s/services/launchpad/_values.yaml`. +Envoy sidecar. + +For the sidecar to intercept these requests, map `objectstore` to its intercept +IP in every deployment that calls Objectstore: + +```yaml {filename:k8s/services//deployment.yaml} +spec: + template: + spec: + hostAliases: + - ip: "{{ intercept_ip }}" + hostnames: + - objectstore +``` + +You can find a complete example in `k8s/services/launchpad/_values.yaml`. If your service uses direct authentication, additionally provision credentials: diff --git a/docs/ai/agent-setup/get-started.mdx b/docs/ai/agent-setup/get-started.mdx index 81d27efe979be..03019fc48208a 100644 --- a/docs/ai/agent-setup/get-started.mdx +++ b/docs/ai/agent-setup/get-started.mdx @@ -44,7 +44,7 @@ Each step that touches Sentry, by route: | Get the DSN | `sentry dsn list` | `find_dsns` | The user pastes it | | Install the SDK | The platform's docs page | The platform's docs page | The platform's docs page | | Confirm the error arrived | `sentry issue list`, `sentry issue view` | `search_issues`, `search_events`, `get_sentry_resource` | Ask the user to check | -| Onboarding progress | Through the MCP server, if it's connected | `onboarding_status_update` | None | +| Onboarding progress | `sentry api` | `onboarding_status_update` | None | ## Step 3: Identify the Platform @@ -136,26 +136,38 @@ Offer follow-ups and let the user pick. Don't start them on your own. - Production was raised with the user: the DSN, sample rate, `release`, and `environment` are set for it, or there's an agreed next step. - Readable production stack traces were addressed: source maps or debug symbols are wired in, or the user knows what they need. -## Onboarding Progress (Through the Sentry MCP Server) +## Onboarding Progress -Sentry's onboarding page can show the progress of a setup like this one. The updates go through the Sentry MCP server, so send them when it's connected, even if the CLI does the rest of the setup. They only apply when the user's first message contains an onboarding code: a random-looking 10-character ASCII alphanumeric token set apart from the prose, such as `[abcd12efg0]` or `Onboarding: abcd12efg0`. Without one, make no progress calls, and never ask for or guess a code later. +Sentry's onboarding page can show the progress of a setup like this one. Send the updates through the route you picked in Step 2: `sentry api` on the CLI route, or the `onboarding_status_update` tool on the MCP route. The no-tools route sends none. They only apply when the user's first message, or the Sentry handoff guide that sent you here, contains an onboarding code: a random-looking 10-character ASCII alphanumeric token set apart from the prose, such as `[abcd12efg0]`, `Onboarding: abcd12efg0`, or `run code: abcd12efg0`. Without one, make no progress calls, and never ask for or guess a code later. Use the organization slug that came with the code. - **Keep the code to yourself.** Never mention, quote, or explain it unless the user asks about it, and don't let it change anything you say. -- **Find the tool.** Call `search_sentry_tools` with the exact query `onboarding_status_update`. If it returns that tool, its input schema is the contract for every call and wins over anything on this page. Call it through `execute_sentry_tool(name='onboarding_status_update', arguments=...)` with the code as `runToken`, and `stage`, `status`, `runStatus`, and `eventNote` inside the required `update` object. Stage metadata goes in `update.extra`. +- **Sentry CLI.** At each stage boundary, run: + + ```sh + sentry api organizations//onboarding/agent/status/ -X POST -F schemaVersion=1 \ + -f 'runToken=' \ + -f stage= \ + -f status= \ + -f 'eventNote=' + ``` + + Add each other field as its own `-f`: `-f runStatus=completed`, `-f 'extra[method]=cli'`, and one `-f 'extra[projectSlugs][]='` or `-f 'extra[issueIds][]='` for each slug or ID. Only `connect_agent`, `create_project`, and `receive_verification_error` take `extra`. + +- **Sentry MCP.** Call `search_sentry_tools` with the exact query `onboarding_status_update`. If it returns that tool, its input schema is the contract for every call and wins over anything on this page. Call it through `execute_sentry_tool(name='onboarding_status_update', arguments=...)` with the code as `runToken`, and `stage`, `status`, `runStatus`, and `eventNote` inside the required `update` object. Stage metadata goes in `update.extra` (MCP only). - **Call it silently.** Make the call at the right point with no narration of the call or its reply. If the user asks what it does, say it updates the onboarding page in Sentry for this setup. -- **Keep notes minimal.** Every call needs an `update.eventNote` saying what the stage is doing or did, within the schema's limit. Never include file contents, repository paths, terminal output, event payloads, MCP results, secrets, or personal or customer information. +- **Keep notes minimal.** Every call needs an `eventNote` saying what the stage is doing or did, within the schema's limit. Never include file contents, repository paths, terminal output, event payloads, MCP results, secrets, or personal or customer information. - **Statuses:** `active` (started or resumed), `waiting` (blocked on the user or permission), `completed`, `skipped` (only where a stage below allows it), and `failed`. After a `failed` stage, send `active` again when you retry. Never send `bypassed`; a later stage marks skipped earlier ones itself, so a missed call never needs replaying. -- **Run status:** send `update.runStatus: completed` only when `check_stack_trace_quality` finishes, and `update.runStatus: failed` only when the whole setup can't continue. -- **Never let it block setup.** If a call fails on invalid parameters and the error names the mistake, fix it and retry once. If the tool is missing or keeps failing, or a reply says `continueUpdates: false` or `Continue updates: no`, stop sending updates for the rest of the session and carry on. A failed progress call is never a setup failure. +- **Run status:** send `runStatus: completed` only when `check_stack_trace_quality` finishes, and `runStatus: failed` only when the whole setup can't continue. +- **Never let it block setup.** If a call fails on invalid parameters and the error names the mistake, fix it and retry once. If the tool is missing or keeps failing, a reply says `continueUpdates: false` or `Continue updates: no`, or a `sentry api` call fails with 404, 409, or 410, stop sending updates for the rest of the session and carry on. A failed progress call is never a setup failure. | Stage | When | | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `connect_mcp` | `completed` as soon as an MCP call such as `find_organizations` succeeds. | +| `connect_agent` | `completed` as soon as Step 2 confirms your route: `sentry auth status` shows you're logged in (CLI route, with `-f 'extra[method]=cli'`), or an MCP call such as `find_organizations` succeeds (the tool records the method itself). | | `analyze_project` | `active` before you inspect the repository (Step 2), `waiting` while you ask the user to confirm the platform, `completed` once the platform and current setup are clear (Step 3). If the project already uses Sentry, `completed` before you hand off. | -| `create_project` | `waiting` before you ask to create a project, `active` while you pick or create it, each usable project slug in `update.extra.projectSlugs`, `completed` once every planned project has a DSN. For one existing project, `completed` with its slug and `update.eventNote: Project already existed.` | +| `create_project` | `waiting` before you ask to create a project, `active` while you pick or create it, each usable project slug in `extra.projectSlugs`, `completed` once every planned project has a DSN. For one existing project, `completed` with its slug and `eventNote: Project already existed.` | | `instrument_app` | `active` just before you change SDK files, `completed` once the SDK is installed and initialized (Step 5). | | `plan_test_error` | `active` while you plan the test error, `waiting` for input or permission, `completed` when the trigger is ready. | | `send_verification_error` | `active` before you trigger it, `waiting` if it can't run yet, `completed` once it's triggered. | -| `receive_verification_error` | `active` or `waiting` while you check, each confirmed issue ID (never event IDs) in `update.extra.issueIds`, `completed` once every project has a confirmed result. | +| `receive_verification_error` | `active` or `waiting` while you check, each confirmed issue ID (never event IDs) in `extra.issueIds`, `completed` once every project has a confirmed result. | | `prepare_production` | `active` when production work starts (Step 7), `waiting` before you ask to deploy, `completed` once the configuration is ready or the user picks a next step. If deployment waits, say the agreed next step in the note. | -| `check_stack_trace_quality` | `active` before you check (Step 8), `completed` with `update.runStatus: completed` once the checks and accepted work are done or the user declines. `skipped` with `update.runStatus: completed` only when the platform needs no source maps or debug files. If the project already used Sentry, `skipped` with `update.runStatus: completed` and `update.eventNote: Sentry is already configured for this project.` | +| `check_stack_trace_quality` | `active` before you check (Step 8), `completed` with `runStatus: completed` once the checks and accepted work are done or the user declines. `skipped` with `runStatus: completed` only when the platform needs no source maps or debug files. If the project already used Sentry, `skipped` with `runStatus: completed` and `eventNote: Sentry is already configured for this project.` | diff --git a/docs/concepts/otlp/direct/logs.mdx b/docs/concepts/otlp/direct/logs.mdx index 19a40c40164f4..5020f113996f5 100644 --- a/docs/concepts/otlp/direct/logs.mdx +++ b/docs/concepts/otlp/direct/logs.mdx @@ -6,8 +6,6 @@ description: "Send OpenTelemetry logs directly to Sentry without a Sentry SDK." keywords: ["otlp", "otel", "opentelemetry", "logs", "logging"] --- - - Send logs directly from your OpenTelemetry SDK to Sentry's OTLP endpoint. You can find your endpoint URL and auth key in [Project settings > Client Keys (DSN)](https://sentry.io/orgredirect/organizations/:orgslug/settings/projects/:projectId/keys/). ## Environment Variables diff --git a/docs/concepts/otlp/direct/traces.mdx b/docs/concepts/otlp/direct/traces.mdx index 4a55b3a2c7f83..30ac98f648ff7 100644 --- a/docs/concepts/otlp/direct/traces.mdx +++ b/docs/concepts/otlp/direct/traces.mdx @@ -6,8 +6,6 @@ description: "Send OpenTelemetry traces directly to Sentry without a Sentry SDK. keywords: ["otlp", "otel", "opentelemetry", "traces", "tracing"] --- - - Send traces directly from your OpenTelemetry SDK to Sentry's OTLP endpoint. You can find your endpoint URL and auth key in [Project settings > Client Keys (DSN)](https://sentry.io/orgredirect/organizations/:orgslug/settings/projects/:projectId/keys/). ## Environment Variables diff --git a/docs/concepts/otlp/forwarding/pipelines/sentry-exporter.mdx b/docs/concepts/otlp/forwarding/pipelines/sentry-exporter.mdx index 1f2cef1258f70..66a1b2f0023ab 100644 --- a/docs/concepts/otlp/forwarding/pipelines/sentry-exporter.mdx +++ b/docs/concepts/otlp/forwarding/pipelines/sentry-exporter.mdx @@ -5,10 +5,6 @@ sidebar_order: 15 description: "Route OpenTelemetry traces and logs from multiple services to different Sentry projects through a single collector instance." keywords: ["otlp", "otel", "opentelemetry", "collector", "exporter", "routing"] --- - - The Sentry Exporter has **alpha** stability for traces and logs. Configuration options and behavior may change. - - The Sentry Exporter routes telemetry from multiple services to different Sentry projects through a single collector instance. Without it, you'd need to configure separate DSNs for each project or set up additional routing connectors. diff --git a/docs/concepts/otlp/index.mdx b/docs/concepts/otlp/index.mdx index c74e2f1862d9e..c728b56a28e22 100644 --- a/docs/concepts/otlp/index.mdx +++ b/docs/concepts/otlp/index.mdx @@ -5,8 +5,6 @@ description: "Learn how to send OpenTelemetry traces and logs to Sentry." keywords: ["otlp", "otel", "opentelemetry"] --- - - Sentry can ingest OpenTelemetry traces and logs via OTLP endpoints, either directly from an [OTel SDK](https://opentelemetry.io/docs/languages/) or through a pipeline tool like the [OpenTelemetry Collector](/concepts/otlp/forwarding/pipelines/collector/). Sentry does not support OTLP metrics at this time. ## Linking Traces with a Sentry SDK diff --git a/docs/contributing/pages/components.mdx b/docs/contributing/pages/components.mdx index 130549944885f..06fe0522ac58f 100644 --- a/docs/contributing/pages/components.mdx +++ b/docs/contributing/pages/components.mdx @@ -360,6 +360,7 @@ Attributes: - `includePath` (string) - the subfolder within `/includes` to map to - `platform` (string) - defaults to the `platform` value from the page context +- `switchable` (boolean) - lets a surrounding [`FrameworkSelector`](#frameworkselector) swap the include for the selected framework's version Some notes: @@ -371,6 +372,28 @@ Some notes: Note: This currently causes issues with tableOfContents generation, so its recommended to disable the TOC when using it. +## FrameworkSelector + +Adds a framework dropdown to a runtime's quick start, such as the Node.js, Bun, and Deno guides. Selecting a framework that doesn't have its own SDK (Express, Fastify, Koa, Hapi) swaps every `` inside the selector for that framework's version. Selecting a framework that has its own guide (Next.js, Nuxt, and others) opens that guide. The selection is kept in the `?framework=` query parameter. + +```markdown {tabTitle:Example} + + + + + +``` + +The runtimes, their frameworks, and their switchable include paths are configured in `src/components/frameworkSelector/frameworks.ts`. + +The framework snippets are only shown after a reader selects the framework, so they're easy to miss when you change content: + +- `platform-includes//javascript..mdx` (for example, `javascript.express.mdx`) shows up on the Node.js, Bun, **and** Deno quick starts. Put snippets that only apply to one runtime in `javascript...mdx`, for example `javascript.node.express.mdx`. +- On Node.js, a framework without its own file uses the Node.js content. On Bun and Deno, it uses the runtime's own content. +- Every `switchable` include path has to be listed in the runtime's `includePaths` in `frameworks.ts`. If it isn't, the framework version isn't built and the page quietly keeps showing the runtime's content. `frameworks.spec.ts` fails when the two get out of sync. +- The framework snippets aren't part of the runtime page's [Markdown export](/contributing/pages/llm-support/). Keep framework-specific guidance that agents need, such as error handling options, on the framework's own guide page too, for example `docs/platforms/javascript/guides/express/index.mdx`. +- To review a change, open the quick start with the framework selected, for example `/platforms/javascript/guides/node/?framework=express`, for each runtime the file applies to. + ## PlatformIdentifier Render terms in the correct case within the body text of a page (not in code samples) based on the platform case_style setting: diff --git a/docs/get-started/guides/logs.mdx b/docs/get-started/guides/logs.mdx index 4040c6ee31049..bd0d8b3934674 100644 --- a/docs/get-started/guides/logs.mdx +++ b/docs/get-started/guides/logs.mdx @@ -26,7 +26,7 @@ sentry_sdk.logger.(message, attribute=value) ```csharp {tabTitle: .NET} using Sentry; -SentrySdk.Logger.(message); +SentrySdk.Logger.Log(message); ``` ```ruby {tabTitle: Ruby} @@ -48,7 +48,7 @@ import io.sentry.Sentry Sentry.logger().(message) ``` -**Levels:** `trace`, `debug`, `info`, `warn` (or `warning` in Python), `error`, `fatal` +**Levels:** `trace`, `debug`, `info`, `warn` (or `warning` in Python and .NET), `error`, `fatal` **Attributes:** Key-value pairs you can search and filter on. Consistency matters, so use whatever naming convention fits your codebase. @@ -82,11 +82,13 @@ sentry_sdk.logger.info("Order completed", ```csharp {tabTitle: .NET} using Sentry; -SentrySdk.Logger.Info("Order completed", logger => logger - .SetAttribute("orderId", "order_123") - .SetAttribute("userId", user.Id) - .SetAttribute("amount", 149.99) - .SetAttribute("paymentMethod", "stripe")); +SentrySdk.Logger.LogInfo(log => +{ + log.SetAttribute("orderId", "order_123"); + log.SetAttribute("userId", user.Id); + log.SetAttribute("amount", 149.99); + log.SetAttribute("paymentMethod", "stripe"); +}, "Order completed"); ``` ```ruby {tabTitle: Ruby} @@ -187,16 +189,20 @@ sentry_sdk.logger.warning("Login failed", ```csharp {tabTitle: .NET} // After successful authentication -SentrySdk.Logger.Info("User logged in", logger => logger - .SetAttribute("userId", user.Id) - .SetAttribute("authMethod", "oauth") - .SetAttribute("provider", "google")); +SentrySdk.Logger.LogInfo(log => +{ + log.SetAttribute("userId", user.Id); + log.SetAttribute("authMethod", "oauth"); + log.SetAttribute("provider", "google"); +}, "User logged in"); // After authentication fails -SentrySdk.Logger.Warning("Login failed", logger => logger - .SetAttribute("email", maskedEmail) - .SetAttribute("reason", "invalid_password") - .SetAttribute("attemptCount", 3)); +SentrySdk.Logger.LogWarning(log => +{ + log.SetAttribute("email", maskedEmail); + log.SetAttribute("reason", "invalid_password"); + log.SetAttribute("attemptCount", 3); +}, "Login failed"); ``` ```ruby {tabTitle: Ruby} @@ -306,12 +312,14 @@ sentry_sdk.logger.error("Payment failed", ```csharp {tabTitle: .NET} // After payment gateway returns an error -SentrySdk.Logger.Error("Payment failed", logger => logger - .SetAttribute("orderId", "order_123") - .SetAttribute("amount", 99.99) - .SetAttribute("gateway", "stripe") - .SetAttribute("errorCode", "card_declined") - .SetAttribute("cartItems", 3)); +SentrySdk.Logger.LogError(log => +{ + log.SetAttribute("orderId", "order_123"); + log.SetAttribute("amount", 99.99); + log.SetAttribute("gateway", "stripe"); + log.SetAttribute("errorCode", "card_declined"); + log.SetAttribute("cartItems", 3); +}, "Payment failed"); ``` ```ruby {tabTitle: Ruby} @@ -435,17 +443,21 @@ $response = $shippingApi->getRates($items); var stopwatch = Stopwatch.StartNew(); var response = await shippingApi.GetRatesAsync(items); -SentrySdk.Logger.Info("Shipping rates fetched", logger => logger - .SetAttribute("service", "shipping-provider") - .SetAttribute("endpoint", "/rates") - .SetAttribute("durationMs", stopwatch.ElapsedMilliseconds) - .SetAttribute("rateCount", response.Rates.Count)); +SentrySdk.Logger.LogInfo(log => +{ + log.SetAttribute("service", "shipping-provider"); + log.SetAttribute("endpoint", "/rates"); + log.SetAttribute("durationMs", stopwatch.ElapsedMilliseconds); + log.SetAttribute("rateCount", response.Rates.Count); +}, "Shipping rates fetched"); // Webhook received -SentrySdk.Logger.Info("Webhook received", logger => logger - .SetAttribute("source", "stripe") - .SetAttribute("eventType", "payment_intent.succeeded") - .SetAttribute("paymentId", eventData.Object.Id)); +SentrySdk.Logger.LogInfo(log => +{ + log.SetAttribute("source", "stripe"); + log.SetAttribute("eventType", "payment_intent.succeeded"); + log.SetAttribute("paymentId", eventData.Object.Id); +}, "Webhook received"); ``` ```ruby {tabTitle: Ruby} @@ -587,16 +599,20 @@ sentry_sdk.logger.error("Job failed", ```csharp {tabTitle: .NET} // Inside background job handler -SentrySdk.Logger.Info("Job started", logger => logger - .SetAttribute("jobType", "email-digest") - .SetAttribute("jobId", "job_456") - .SetAttribute("queue", "notifications")); +SentrySdk.Logger.LogInfo(log => +{ + log.SetAttribute("jobType", "email-digest"); + log.SetAttribute("jobId", "job_456"); + log.SetAttribute("queue", "notifications"); +}, "Job started"); -SentrySdk.Logger.Error("Job failed", logger => logger - .SetAttribute("jobType", "email-digest") - .SetAttribute("jobId", "job_456") - .SetAttribute("retryCount", 3) - .SetAttribute("lastError", "SMTP timeout")); +SentrySdk.Logger.LogError(log => +{ + log.SetAttribute("jobType", "email-digest"); + log.SetAttribute("jobId", "job_456"); + log.SetAttribute("retryCount", 3); + log.SetAttribute("lastError", "SMTP timeout"); +}, "Job failed"); ``` ```ruby {tabTitle: Ruby} @@ -716,14 +732,18 @@ sentry_sdk.logger.warning("Config reloaded", ```csharp {tabTitle: .NET} // When feature flag is checked or config changes -SentrySdk.Logger.Info("Feature flag evaluated", logger => logger - .SetAttribute("flag", "new-checkout-flow") - .SetAttribute("enabled", true) - .SetAttribute("userId", user.Id)); +SentrySdk.Logger.LogInfo(log => +{ + log.SetAttribute("flag", "new-checkout-flow"); + log.SetAttribute("enabled", true); + log.SetAttribute("userId", user.Id); +}, "Feature flag evaluated"); -SentrySdk.Logger.Warning("Config reloaded", logger => logger - .SetAttribute("reason", "env-change") - .SetAttribute("changedKeys", new[] { "API_TIMEOUT", "MAX_CONNECTIONS" })); +SentrySdk.Logger.LogWarning(log => +{ + log.SetAttribute("reason", "env-change"); + log.SetAttribute("changedKeys", "API_TIMEOUT,MAX_CONNECTIONS"); +}, "Config reloaded"); ``` ```ruby {tabTitle: Ruby} @@ -842,7 +862,6 @@ SentrySdk.Init(options => options.Dsn = "..."; options.Environment = "development"; options.TracesSampleRate = 1.0; // 100% of traces - options.EnableLogs = true; }); ``` @@ -918,9 +937,9 @@ sentry_sdk.logger.error("Payment failed", reason="Insufficient Funds") ``` ```csharp {tabTitle: .NET} -SentrySdk.Logger.Info("Checkout started", l => l.SetAttribute("userId", "882")); -SentrySdk.Logger.Info("Discount applied", l => l.SetAttribute("code", "WINTER20")); -SentrySdk.Logger.Error("Payment failed", l => l.SetAttribute("reason", "Insufficient Funds")); +SentrySdk.Logger.LogInfo(log => log.SetAttribute("userId", "882"), "Checkout started"); +SentrySdk.Logger.LogInfo(log => log.SetAttribute("code", "WINTER20"), "Discount applied"); +SentrySdk.Logger.LogError(log => log.SetAttribute("reason", "Insufficient Funds"), "Payment failed"); ``` ```ruby {tabTitle: Ruby} @@ -988,14 +1007,16 @@ sentry_sdk.logger.error("Checkout failed", ``` ```csharp {tabTitle: .NET} -SentrySdk.Logger.Error("Checkout failed", logger => logger - .SetAttribute("userId", "882") - .SetAttribute("orderId", "order_pc_991") - .SetAttribute("cartTotal", 142.50) - .SetAttribute("discountCode", "WINTER20") - .SetAttribute("paymentMethod", "stripe") - .SetAttribute("errorReason", "Insufficient Funds") - .SetAttribute("itemCount", 4)); +SentrySdk.Logger.LogError(log => +{ + log.SetAttribute("userId", "882"); + log.SetAttribute("orderId", "order_pc_991"); + log.SetAttribute("cartTotal", 142.50); + log.SetAttribute("discountCode", "WINTER20"); + log.SetAttribute("paymentMethod", "stripe"); + log.SetAttribute("errorReason", "Insufficient Funds"); + log.SetAttribute("itemCount", 4); +}, "Checkout failed"); ``` ```ruby {tabTitle: Ruby} @@ -1087,4 +1108,3 @@ To pipe Supabase infrastructure logs into Sentry and alert on them, see [Set up ## Next Steps Explore the [Logs product walkthrough guides](/product/logs/) to learn more about the Sentry interface and discover additional tips. - diff --git a/docs/get-started/guides/metrics.mdx b/docs/get-started/guides/metrics.mdx index 78a102a3c46ec..ae464b75c6a27 100644 --- a/docs/get-started/guides/metrics.mdx +++ b/docs/get-started/guides/metrics.mdx @@ -46,10 +46,11 @@ sentry_sdk.metrics.count("checkout.failed", 1, attributes={ ``` ```csharp {tabTitle: .NET} -SentrySdk.Metrics.Counter("checkout.failed") - .Tag("user_tier", "premium") - .Tag("failure_reason", "payment_declined") - .Increment(); +SentrySdk.Metrics.EmitCounter("checkout.failed", 1, new Dictionary +{ + ["user_tier"] = "premium", + ["failure_reason"] = "payment_declined", +}); ``` ```ruby {tabTitle: Ruby} @@ -121,15 +122,17 @@ sentry_sdk.metrics.count("checkout.failed", 1, attributes={ ``` ```csharp {tabTitle: .NET} -SentrySdk.Metrics.Counter("checkout.completed") - .Tag("user_tier", "premium") - .Tag("payment_method", "card") - .Increment(); +SentrySdk.Metrics.EmitCounter("checkout.completed", 1, new Dictionary +{ + ["user_tier"] = "premium", + ["payment_method"] = "card", +}); -SentrySdk.Metrics.Counter("checkout.failed") - .Tag("user_tier", "premium") - .Tag("failure_reason", "payment_declined") - .Increment(); +SentrySdk.Metrics.EmitCounter("checkout.failed", 1, new Dictionary +{ + ["user_tier"] = "premium", + ["failure_reason"] = "payment_declined", +}); ``` ```ruby {tabTitle: Ruby} @@ -229,20 +232,23 @@ sentry_sdk.metrics.count("job.processed", 1, attributes={ ``` ```csharp {tabTitle: .NET} -SentrySdk.Metrics.Counter("email.sent") - .Tag("email_type", "welcome") - .Tag("provider", "sendgrid") - .Increment(); +SentrySdk.Metrics.EmitCounter("email.sent", 1, new Dictionary +{ + ["email_type"] = "welcome", + ["provider"] = "sendgrid", +}); -SentrySdk.Metrics.Counter("email.failed") - .Tag("email_type", "welcome") - .Tag("error", "rate_limited") - .Increment(); +SentrySdk.Metrics.EmitCounter("email.failed", 1, new Dictionary +{ + ["email_type"] = "welcome", + ["error"] = "rate_limited", +}); -SentrySdk.Metrics.Counter("job.processed") - .Tag("job_type", "invoice-generation") - .Tag("queue", "billing") - .Increment(); +SentrySdk.Metrics.EmitCounter("job.processed", 1, new Dictionary +{ + ["job_type"] = "invoice-generation", + ["queue"] = "billing", +}); ``` ```ruby {tabTitle: Ruby} @@ -341,13 +347,15 @@ use \Sentry\Metrics\Unit; ``` ```csharp {tabTitle: .NET} -SentrySdk.Metrics.Gauge("queue.depth") - .Tag("queue_name", "notifications") - .Set(queue.Size); +SentrySdk.Metrics.EmitGauge("queue.depth", queue.Size, MeasurementUnit.None, new Dictionary +{ + ["queue_name"] = "notifications", +}); -SentrySdk.Metrics.Gauge("pool.connections_active") - .Tag("pool_name", "postgres-primary") - .Set(pool.ActiveConnections); +SentrySdk.Metrics.EmitGauge("pool.connections_active", pool.ActiveConnections, MeasurementUnit.None, new Dictionary +{ + ["pool_name"] = "postgres-primary", +}); ``` ```ruby {tabTitle: Ruby} @@ -436,15 +444,17 @@ use \Sentry\Metrics\Unit; ``` ```csharp {tabTitle: .NET} -SentrySdk.Metrics.Distribution("api.latency", responseTimeMs, - unit: MeasurementUnit.Duration.Millisecond) - .Tag("endpoint", "/api/orders") - .Tag("method", "POST"); +SentrySdk.Metrics.EmitDistribution("api.latency", responseTimeMs, MeasurementUnit.Duration.Millisecond, new Dictionary +{ + ["endpoint"] = "/api/orders", + ["method"] = "POST", +}); -SentrySdk.Metrics.Distribution("db.query_time", queryDurationMs, - unit: MeasurementUnit.Duration.Millisecond) - .Tag("table", "orders") - .Tag("operation", "select"); +SentrySdk.Metrics.EmitDistribution("db.query_time", queryDurationMs, MeasurementUnit.Duration.Millisecond, new Dictionary +{ + ["table"] = "orders", + ["operation"] = "select", +}); ``` ```ruby {tabTitle: Ruby} @@ -543,15 +553,17 @@ use \Sentry\Metrics\Unit; ``` ```csharp {tabTitle: .NET} -SentrySdk.Metrics.Distribution("order.amount", order.TotalUsd, - unit: MeasurementUnit.Custom("usd")) - .Tag("user_tier", "premium") - .Tag("region", "us-west"); +SentrySdk.Metrics.EmitDistribution("order.amount", (double)order.TotalUsd, MeasurementUnit.Custom("usd"), new Dictionary +{ + ["user_tier"] = "premium", + ["region"] = "us-west", +}); -SentrySdk.Metrics.Distribution("upload.size", fileSizeBytes, - unit: MeasurementUnit.Information.Byte) - .Tag("file_type", "image") - .Tag("source", "profile-update"); +SentrySdk.Metrics.EmitDistribution("upload.size", fileSizeBytes, MeasurementUnit.Information.Byte, new Dictionary +{ + ["file_type"] = "image", + ["source"] = "profile-update", +}); ``` ```ruby {tabTitle: Ruby} @@ -637,4 +649,3 @@ You can also [create dashboards with an AI coding agent](https://sentry.io/cookb All three are trace-connected. Start wherever makes sense and navigate to the others. Explore the [Application Metrics product walkthrough](/product/metrics/) to learn more about the Sentry interface and discover additional tips. - diff --git a/docs/integrations/debugging/index.mdx b/docs/integrations/debugging/index.mdx index 7cb86699008a9..5aec6a0c5f517 100644 --- a/docs/integrations/debugging/index.mdx +++ b/docs/integrations/debugging/index.mdx @@ -11,8 +11,8 @@ description: "Learn more about Sentry's debugging integrations." - [Foam](/integrations/debugging/foamai/) - [Google Cloud Platform for Seer](/integrations/debugging/gcp-seer/) - [Grafana for Seer](/integrations/debugging/grafana-seer/) +- [Linear for Seer](/integrations/debugging/linear-seer/) - [Logicstar](/integrations/debugging/logicstar/) - [Rookout](/integrations/debugging/rookout/) - [Sourcery](/integrations/debugging/sourcery/) - [Tembo](/integrations/debugging/tembo/) - diff --git a/docs/integrations/debugging/linear-seer/index.mdx b/docs/integrations/debugging/linear-seer/index.mdx new file mode 100644 index 0000000000000..a120182baac9d --- /dev/null +++ b/docs/integrations/debugging/linear-seer/index.mdx @@ -0,0 +1,64 @@ +--- +title: Linear Seer Integration +sidebar_order: 1 + +description: "Learn how adding Linear data to Seer's context helps you debug and fix issues." +--- + + + +The Linear for Seer integration gives [Seer Agent](/product/ai-in-sentry/seer/#seer-agent) read-only access to issues, projects, and comments in your Linear workspace. Seer can then use Linear data to enhance or supplement Sentry telemetry in issue analysis or investigations. + +The connection is shared across your Sentry organization. You can connect one Linear workspace per Sentry organization. + +Sentry installs the integration as an app in your Linear workspace, so Seer reads Linear as the app instead of as the person who connected it. Seer connects through [Linear's read-only MCP server](https://linear.app/docs/mcp), which only exposes read tools, so Seer can't create or change anything in Linear. + +This integration is separate from the [Linear issue tracking integration](/integrations/issue-tracking/linear/), which is built by Linear and lets you create and link Linear issues from Sentry. + +## Install the Linear for Seer Integration + + + +Sentry Owner, Manager, or Admin permissions are required to install this integration. + +You also need to be a Linear workspace admin, because installing an app in a Linear workspace requires admin permissions. A Linear workspace admin can complete these steps for you. + + + +1. Navigate to [Seer Connector Settings](https://sentry.io/orgredirect/organizations/:orgslug/settings/seer/connectors/). +2. Select the Linear for Seer integration and click **Add Workspace**. +3. Click **Authorize Linear**. A Linear authorization window opens. If it doesn't, allow popups from Sentry in your browser and click **Authorize Linear** again. +4. In the Linear window, select the workspace you want to connect, review the requested access, and approve it. + + Linear's authorization screen lists read and write permissions. Seer only uses Linear's read-only MCP server, so it can only read data from your workspace. + + If Linear asks which teams the app can access, select every team whose issues and projects you want Seer to read. Seer can't see data from teams the app can't access. + +5. After you approve, Sentry checks that it can read the workspace before completing installation. The new connection appears as **Linear (_Workspace Name_)**. + + If the check fails, the error appears in the setup modal. Correct the problem and click **Authorize Linear** again. You can retry in the same setup modal. + +## Configure + +The integration has no settings to edit. Sentry refreshes the Linear access token automatically, so you don't need to rotate it. + +To reauthorize the workspace, click the **Configurations** tab on the [Linear for Seer settings page](https://sentry.io/orgredirect/organizations/:orgslug/settings/integrations/linear/?tab=configurations), click **Configure** for the workspace, then click **Reconnect Linear** and approve access in Linear again. Choose the same workspace you connected originally. To connect a different workspace, uninstall the current connection first, then install the integration again. + +To change which teams Seer can read, update the app's team access in Linear's [Applications settings](https://linear.app/settings/applications). Only Linear workspace admins can change an app's team access. + +When you uninstall the integration, Sentry revokes the app's access in Linear. If another Sentry organization is connected to the same Linear workspace, Sentry keeps the app's access in Linear so that organization's connection keeps working. + +## Troubleshooting + +If the connection needs attention: + +- **Linear authorization was canceled:** You closed or declined the Linear authorization window. Click **Authorize Linear** to try again. +- **The authorization popup was blocked:** Allow popups from Sentry in your browser, then click **Authorize Linear** again. +- **Could not reach Linear:** Linear could not be reached during setup. Wait a moment, then try again. +- **Linear authorization failed:** Linear rejected the authorization. Confirm that you're a Linear workspace admin and approved the requested access, then authorize the workspace again. If this appears for an existing connection, the app's access was likely revoked in Linear. Click **Reconnect Linear** to restore it. +- **The app can't read your Linear workspace:** The app was installed but can't read workspace data. Check the app's access in Linear's [Applications settings](https://linear.app/settings/applications). If your workspace requires approval for third-party apps, make sure an admin has approved it. See Linear's [third-party app approvals](https://linear.app/docs/third-party-application-approvals). +- **Remove the current Linear connection before connecting a different workspace:** Your Sentry organization is already connected to a different Linear workspace. Uninstall that connection, or select the original workspace when you reconnect. +- **The integration was disabled:** Sentry disables the connection if Linear stops accepting its credentials, for example after someone revokes the app's access in Linear. Click **Reconnect Linear** to authorize the workspace again. +- **Seer can't find issues or projects you expect:** Check that the app has access to the teams that own them in Linear's [Applications settings](https://linear.app/settings/applications). + +After correcting the setup, click **Authorize Linear** during installation or **Reconnect Linear** in the integration settings. diff --git a/docs/integrations/index.mdx b/docs/integrations/index.mdx index c56b7d5a84f5c..825b76241e863 100644 --- a/docs/integrations/index.mdx +++ b/docs/integrations/index.mdx @@ -96,7 +96,7 @@ For more details, see the [full Integration Platform documentation](/integration | Integration | Link Issue to user sessions | | ------------------------------------------------------ | --------------------------- | | [Atlas](/integrations/session-replay/atlas/) | X | -| [BetterBugs](/integrations/session-replay/betterbugs/) | X | +| [BetterBugs](/integrations/session-replay/betterbugs/) | X | | [FullStory](/integrations/session-replay/fullstory/) | X | | [Jam](/integrations/session-replay/jam/) | X | | [OpenReplay](/integrations/session-replay/openreplay/) | X | @@ -119,6 +119,7 @@ For more details, see the [full Integration Platform documentation](/integration | [Foam](/integrations/debugging/foamai/) | | | [Google Cloud Platform for Seer](/integrations/debugging/gcp-seer/) | | | [Grafana for Seer](/integrations/debugging/grafana-seer/) | | +| [Linear for Seer](/integrations/debugging/linear-seer/) | | | [Logicstar](/integrations/debugging/logicstar/) | | | [Rookout](/integrations/debugging/rookout/) | X | | [Sourcery](/integrations/debugging/sourcery/) | | diff --git a/docs/integrations/notification-incidents/slack/img/slack-agent-dms.png b/docs/integrations/notification-incidents/slack/img/slack-agent-dms.png deleted file mode 100644 index 072d9a837fd12..0000000000000 Binary files a/docs/integrations/notification-incidents/slack/img/slack-agent-dms.png and /dev/null differ diff --git a/docs/integrations/notification-incidents/slack/img/slack-agent-notifications.png b/docs/integrations/notification-incidents/slack/img/slack-agent-notifications.png deleted file mode 100644 index 0c6a48c982c58..0000000000000 Binary files a/docs/integrations/notification-incidents/slack/img/slack-agent-notifications.png and /dev/null differ diff --git a/docs/integrations/notification-incidents/slack/img/slack-agent-panel.png b/docs/integrations/notification-incidents/slack/img/slack-agent-panel.png deleted file mode 100644 index 45c8494346296..0000000000000 Binary files a/docs/integrations/notification-incidents/slack/img/slack-agent-panel.png and /dev/null differ diff --git a/docs/integrations/notification-incidents/slack/index.mdx b/docs/integrations/notification-incidents/slack/index.mdx index a811125c7dc9c..96e6d91e02c85 100644 --- a/docs/integrations/notification-incidents/slack/index.mdx +++ b/docs/integrations/notification-incidents/slack/index.mdx @@ -92,10 +92,6 @@ It has all the capabilities of the web version, but also automatically gathers c ![Seer Agent initially mentioned in a Slack channel =600x](./img/slack-agent-mention.png) -For [paid Slack Workspaces with access to AI assistant apps](https://slack.com/pricing), you can also open Seer Agent as an Agent in Slack, using the dropdown in the top-right of your Slack window. This will open a new persistent panel in your Slack window for private conversations with Seer Agent. In these conversations, you don't have to mention it every time, and new chats will open with a few example prompts to get you started. - -![Open Seer Agent conversation panel in Slack with suggested prompts =600x](./img/slack-agent-panel.png) - If you have a single Slack Workspace connected to multiple Sentry organizations, Seer Agent will automatically try to infer the Sentry organization to search based on thread context (e.g. Sentry links). If this behaviour doesn't fit your needs, you can use `/sentry set org [organization_slug]` to manually set your preference when interacting with Seer Agent. Your chats and mentions will fallback to the set organization if no organization can be inferred. ![Example set default organization Slack command =600x](./img/slack-preference-command.png) @@ -106,7 +102,6 @@ In order for Sentry to be able to notify and debug your issues from Slack, we re | Required Bot Scope | Usage | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -| `assistant:write` | Allows Seer to act as an [AI Assistant in Slack](https://slack.com/help/articles/33076000248851-Understand-AI-apps-in-Slack). | | `app_mentions:read` | Allows Slack to notify Sentry when a user has @mentioned the bot. | | `channels:read` | Allows Sentry to view info about, list, and validate public channels in your workspace. Used primarily for configuring alerts. | | `chat:write` | Allows Sentry to send/update messages, such as alerts, notifications, and responses. | @@ -140,18 +135,6 @@ More details on the scopes and their technical usage can be found on the [self-h ## Troubleshooting -### Disabling the AI Assistant Experience - -If you've enabled the Sentry Slack app to act as an AI Assistant, you may notice a change in appearance for your personal notifications. Each one appears now as a separate chat you can have with Seer Agent. - -![Example notification feed from Slack Agent =600x](./img/slack-agent-notifications.png) - -This is a Slack feature that more clearly divides conversations, and gives a few benefits like a persistent panel for chats, a quick launcher for new conversations, and few prompts to get you started when interacting with Seer Agent. However, if you'd rather keep the regular direct message experience you can disable the _AI assistant experience_ when managing your Slack Workspace by following this [Slack help article](https://slack.com/help/articles/33077521383059-Manage-app-agents-and-assistants). - -Disabling this feature applies to the whole Slack workspace, and will revert your interactions to a direct message conversation, with 'chats' appearing as regular threads. You'll still be able to chat with Seer Agent without @mentioning every time, but you'll lose a few Slack benefits mentioned above. - -![Example of Seer chats now in Slack App DMs =600x](./img/slack-agent-dms.png) - ### Rate Limiting Error If you're attempting to save a Slack alert and are receiving the following error: "Requests to slack were rate limited. Please try again later.", you may enter in the channel or user ID in addition to the channel name. diff --git a/docs/platforms/android/configuration/using-ndk.mdx b/docs/platforms/android/configuration/using-ndk.mdx index a3b851fc57013..100fb8d7fd658 100644 --- a/docs/platforms/android/configuration/using-ndk.mdx +++ b/docs/platforms/android/configuration/using-ndk.mdx @@ -136,6 +136,99 @@ You can also configure these options in `AndroidManifest.xml`, which is useful w For details about the native watchdog and heartbeat behavior, see the [Native SDK app hang documentation](/platforms/native/app-hangs/). +## Out-of-Process Crash Handling + +By default, the NDK integration handles a native crash inside the crashing process, and the SDK sends it the next time the app starts. With out-of-process crash handling, a crash service in a separate process captures the crash and sends it right away. This way, you see native crashes even from users who don't open the app again. + + + +Out-of-process crash handling is experimental. It requires Android 11 (API level 30) or later. On older Android versions, the SDK doesn't report native crashes in this mode. + + + +To enable it, add `sentry-android-ndk-outproc` and exclude `sentry-native-ndk`, which the `sentry-android` bundle includes: + +```groovy {filename:app/build.gradle} +dependencies { + implementation "io.sentry:sentry-android-ndk-outproc:{{@inject packages.version('sentry.java.android', '8.64.0') }}" +} + +configurations.configureEach { + exclude group: "io.sentry", module: "sentry-native-ndk" +} +``` + +```kotlin {filename:app/build.gradle.kts} +dependencies { + implementation("io.sentry:sentry-android-ndk-outproc:{{@inject packages.version('sentry.java.android', '8.64.0') }}") +} + +configurations.configureEach { + exclude(group = "io.sentry", module = "sentry-native-ndk") +} +``` + +You don't need to exclude `sentry-native-ndk` if you use `sentry-android-core` instead of the `sentry-android` bundle. If the build contains both native packages, Gradle fails with a conflict on the capability `io.sentry:sentry-ndk-backend`. + +If you [link against the NDK libraries](#allowing-the-compiler-to-link-libraries), keep your `CMakeLists.txt`, but depend on `io.sentry:sentry-native-ndk-outproc` instead of `io.sentry:sentry-native-ndk`. + +Keep in mind: + +- The crash service runs in a separate process, `.sentry_ndk_crash`, while your app runs, and uses additional memory. +- Android creates a second instance of your `Application` in that process. See [Second Application Instance](#second-application-instance). +- With the [Tombstone Integration](/platforms/android/configuration/tombstones/) enabled on Android 12 (API level 31) or later, the crash service merges the tombstone into the native crash event before it sends it. +- If the crash service can't finish sending the crash, the SDK sends it on a later app start. This can happen without a network connection, or on Android 14 (API level 34) and later, where Android freezes the service 10 seconds after the app exits. + +### Second Application Instance + +Android creates a second instance of your `Application` class in the crash service process. The SDK skips its own initialization there, so only one SDK runs and sessions aren't tracked twice. + + + +Code in `Application.onCreate` also runs in the crash service process, which can initialize libraries twice, repeat background work, or cause conflicts over shared files. + + + +To run startup code only in the main process, return early from `Application.onCreate` in other processes: + +```kotlin {filename:MyApplication.kt} +class MyApplication : Application() { + override fun onCreate() { + super.onCreate() + if (!isMainProcess()) return + + // your startup work + } + + private fun isMainProcess() = + Build.VERSION.SDK_INT < Build.VERSION_CODES.P || + Application.getProcessName() == applicationInfo.processName + // or, to skip only the crash service process: + // !Application.getProcessName().endsWith(".sentry_ndk_crash") +} +``` + +```java {filename:MyApplication.java} +public class MyApplication extends Application { + @Override + public void onCreate() { + super.onCreate(); + if (!isMainProcess()) { + return; + } + + // your startup work + } + + private boolean isMainProcess() { + return Build.VERSION.SDK_INT < Build.VERSION_CODES.P + || Application.getProcessName().equals(getApplicationInfo().processName); + // or, to skip only the crash service process: + // || !Application.getProcessName().endsWith(".sentry_ndk_crash"); + } +} +``` + ## Disable NDK Integration You can disable the NDK integration by adding the following to your `AndroidManifest.xml`: diff --git a/docs/platforms/android/troubleshooting/index.mdx b/docs/platforms/android/troubleshooting/index.mdx index f3a6786fae980..b9fa8464e5d99 100644 --- a/docs/platforms/android/troubleshooting/index.mdx +++ b/docs/platforms/android/troubleshooting/index.mdx @@ -199,7 +199,7 @@ If you set up the Sentry SDK and it's not sending any data to Sentry: - Check that you have configured a DSN and that you are passing it to the `dsn` option in `SentryAndroid.init()` or `AndroidManifest`. - When a crash happens or the app closes, the system allows only a short time to handle it before terminating the process. The SDK might not have enough time to send the event, spans, profile, or replay data. In these cases, simply relaunching the app should allow the SDK to send the remaining data. -- An ad-blocker (e.g. [DuckDuckGo's App Tracking Protection](https://duckduckgo.com/duckduckgo-help-pages/p-app-tracking-protection/what-is-app-tracking-protection)) or network restrictions might be preventing the SDK from reaching Sentry's servers. As a workaround, you can use [tunneling](/platforms/javascript/troubleshooting/#using-the-tunnel-option) to proxy Sentry events through your own server. Then you can add the [proxy option](/platforms/android/configuration/options/#proxy) to your SDK configuration. +- An ad-blocker (e.g. [DuckDuckGo's App Tracking Protection](https://duckduckgo.com/duckduckgo-help-pages/p-app-tracking-protection/what-is-app-tracking-protection)) or network restrictions might be preventing the SDK from reaching Sentry's servers. As a workaround, you can use [tunneling](/platforms/javascript/configuration/tunneling/) to proxy Sentry events through your own server. Then you can add the [proxy option](/platforms/android/configuration/options/#proxy) to your SDK configuration. - Set `debug: true` in the `SentryAndroid.init()` or the manifest options and observe your Logcat output when you start your application. The SDK may tell you why it is not sending any data. - Check the [Stats](https://sentry.io/orgredirect/organizations/:orgslug/stats/) and [Subscription](https://sentry.io/orgredirect/organizations/:orgslug/settings/billing/overview/) pages in Sentry. You may be out of quota. diff --git a/docs/platforms/apple/common/configuration/options.mdx b/docs/platforms/apple/common/configuration/options.mdx index e6f2993048545..9f2e35905ebf3 100644 --- a/docs/platforms/apple/common/configuration/options.mdx +++ b/docs/platforms/apple/common/configuration/options.mdx @@ -30,7 +30,9 @@ Note that setting this to `false` doesn't prevent all overhead from Sentry instr -Turns debug mode on or off. If debug is enabled, SDK will attempt to print out useful debugging information if something goes wrong with sending the event. It's generally not recommended to turn it on in production, though this will not cause any safety concerns. +Turns debug mode on or off. If debug is enabled, SDK will attempt to print out useful debugging information if something goes wrong with sending the event. + +We don't recommend enabling debug mode in production. The SDK writes debug logs to the console synchronously, on the thread that logs them. When the SDK logs a lot, for example while tracing many view controllers, this can noticeably slow down your app and even cause app hangs. To log fewer messages while debugging, set to a less verbose level, such as `warning`. @@ -1103,6 +1105,14 @@ Learn more in the + +Connects the traces of every `WKWebView` in the app with the app's trace, without calling `SentryWebViewTracing.addTracePropagation` for each WebView. Only pages on the hosts in `allowedHosts` receive the trace. Requires `enableSwizzling`. Not available on tvOS and watchOS. + +Learn more in the WebView documentation. + + + When enabled, the SDK tracks performance for file I/O reads and writes with NSData if auto performance tracking and `enableSwizzling` are enabled. diff --git a/docs/platforms/apple/common/configuration/webview.mdx b/docs/platforms/apple/common/configuration/webview.mdx index 950046e2d746a..52961b70b6b18 100644 --- a/docs/platforms/apple/common/configuration/webview.mdx +++ b/docs/platforms/apple/common/configuration/webview.mdx @@ -73,7 +73,46 @@ The injected trace context carries no secrets or PII by default: the root span n -The injected trace is a snapshot taken when you call `addTracePropagation`, and every later page load in that web view reuses it. To connect a later page load to a newer trace, call `addTracePropagation` again before the navigation. It replaces the script Sentry added earlier and keeps your own user scripts. +The injected trace is a snapshot taken when you call `addTracePropagation`, and every later page load in that web view reuses it. To connect a later page load to a newer trace, call `addTracePropagation` again before the navigation, or use [automatic trace propagation](#automatic-trace-propagation), which does this for you. It replaces the script Sentry added earlier and keeps your own user scripts. + + + +### Automatic Trace Propagation + + + +`options.webViewTracing` is available from Cocoa SDK version `9.34.0`. + + + +Instead of calling `addTracePropagation` for each web view, you can set `webViewTracing` when you start the SDK. The SDK then adds trace propagation to every `WKWebView` in the app, including SwiftUI `WebPage` and `WebView(url:)`, right before it loads a page: + +```swift {tabTitle:Swift} +import Sentry + +SentrySDK.start { options in + options.dsn = "___PUBLIC_DSN___" + options.webViewTracing = SentryWebViewTracingOptions(allowedHosts: ["example.com"]) +} +``` + +```objc {tabTitle:Objective-C (SentryObjC)} +#import + +[SentryObjCSDK startWithConfigureOptions:^(SentryObjCOptions *options) { + options.dsn = @"___PUBLIC_DSN___"; + options.webViewTracing = + [[SentryObjCWebViewTracingOptions alloc] initWithAllowedHosts:@[ @"example.com" ]]; +}]; +``` + +The SDK also keeps the injected trace current: when the app's current trace changes, it updates the trace for later page loads, including links followed and reloads inside the web view. A page restored from the back/forward cache keeps the trace it was loaded with, because the Browser SDK doesn't start a new pageload for it either. + +Automatic trace propagation requires `enableSwizzling`, which is enabled by default. Web views you pass to `addTracePropagation` keep the `allowedHosts` of that call, and the SDK keeps their trace current too. + + + +`webViewTracing` applies to every `WKWebView` in the app, including in-app browsers and web views created by other SDKs, such as ads, payments, or sign-in. They receive the trace when they load a host in `allowedHosts`, so only list hosts whose content you trust. If your app has a web view that loads untrusted content alongside allowed hosts, use `addTracePropagation` on specific web views instead. @@ -104,7 +143,7 @@ struct ContentView: View { } ``` -`WebView(url:)` creates its page internally, so it can't receive the trace. Create a `WebPage` as shown above instead. This requires Xcode 26 or later. +`WebView(url:)` creates its page internally, so `addTracePropagation` can't reach it. Create a `WebPage` as shown above instead, or use [automatic trace propagation](#automatic-trace-propagation), which also covers `WebView(url:)`. This requires Xcode 26 or later. ### Limitations diff --git a/docs/platforms/apple/common/logs/swift-log.mdx b/docs/platforms/apple/common/logs/swift-log.mdx index 9a0917176e8e1..b413d7c85b065 100644 --- a/docs/platforms/apple/common/logs/swift-log.mdx +++ b/docs/platforms/apple/common/logs/swift-log.mdx @@ -17,7 +17,7 @@ Add the package via Swift Package Manager: ```swift dependencies: [ - .package(url: "https://github.com/getsentry/sentry-apple-swift-log", from: "1.0.0") + .package(url: "https://github.com/getsentry/sentry-apple-swift-log", from: "9.0.0") ] ``` @@ -29,7 +29,7 @@ By default, the integration uses precompiled Sentry binary xcframeworks. If you ```swift dependencies: [ - .package(url: "https://github.com/getsentry/sentry-apple-swift-log", from: "1.0.0", traits: ["SentryFromSource"]) + .package(url: "https://github.com/getsentry/sentry-apple-swift-log", from: "9.0.0", traits: ["SentryFromSource"]) ] ``` diff --git a/docs/platforms/apple/common/troubleshooting/index.mdx b/docs/platforms/apple/common/troubleshooting/index.mdx index a6347e3013cdd..fc2b16924a56e 100644 --- a/docs/platforms/apple/common/troubleshooting/index.mdx +++ b/docs/platforms/apple/common/troubleshooting/index.mdx @@ -5,6 +5,17 @@ sidebar_order: 9000 sidebar_section: configuration --- +## "The signing certificate has been revoked" when building with pre-built XCFrameworks + +Since November 13, 2026, Xcode may fail to validate the signature of the pre-built Sentry XCFrameworks and show an error like this: + +```txt +The signature of "Sentry.xcframework" cannot be validated and may have been compromised. +Validation Error: The signing certificate has been revoked (CSSMERR_TP_CERT_REVOKED) +``` + +This may affect projects that use the pre-built binary products (`Sentry`, `Sentry-Dynamic`, and others) from versions `9.34.0` and earlier, which were signed with a revoked certificate. To solve this, follow the guidance in [this GitHub issue](https://github.com/getsentry/sentry-cocoa/issues/9645). + ## Can I Initialize the SDK From a Background Thread? Yes, but we recommend initializing the SDK on the main thread as early as possible. When you call `SentrySDK.start` from a background thread, the SDK starts asynchronously on the main thread because some initialization steps, such as collecting view hierarchy information, require it. diff --git a/docs/platforms/dart/common/index.mdx b/docs/platforms/dart/common/index.mdx index a15ba542b8fb8..f07037199fb88 100644 --- a/docs/platforms/dart/common/index.mdx +++ b/docs/platforms/dart/common/index.mdx @@ -1,6 +1,6 @@ --- title: Dart -description: Learn how to set up Sentry in your Dart app, capture your first errors and traces, and view them in Sentry. +description: Learn how to set up Sentry in your Dart app, capture your first events, and view them in Sentry. caseStyle: camelCase supportLevel: production sdk: sentry.dart @@ -33,9 +33,8 @@ dependencies: ## Configure -Choose the features you want to configure, and this guide will show you how: - - +Initialize **Error Monitoring** with `Sentry.init()` and run your application in its `appRunner` callback to capture uncaught exceptions and unhandled asynchronous errors. **Logs** and **Application Metrics** are enabled by default in SDK v10, and you'll learn how to send them in steps [#3](#send-logs) and [#4](#send-application-metrics-). +This guide also enables **Tracing**. @@ -43,40 +42,83 @@ Choose the features you want to configure, and this guide will show you how: Configuration should happen as **early as possible** in your application's lifecycle. -Import and initialize the SDK in your app's entry point: +Import and initialize the SDK in your app's entry point as shown in the code snippet below. + +The snippet also turns on: + +- Tracing: via `tracesSampleRate` +- Additional user and request data: via `sendDefaultPii` + +To skip tracing, omit `tracesSampleRate`. To discard logs or metrics, return `null` from `beforeSendLog` or `beforeSendMetric`. ```dart import 'package:sentry/sentry.dart'; Future main() async { - await Sentry.init((options) { - options.dsn = '___PUBLIC_DSN___'; - // Adds request headers and IP for users, for more info visit: - // https://docs.sentry.io/platforms/dart/data-management/data-collected/ - options.sendDefaultPii = true; - // ___PRODUCT_OPTION_START___ performance - // Set tracesSampleRate to 1.0 to capture 100% of transactions for tracing. - // We recommend adjusting this value in production. - options.tracesSampleRate = 1.0; - // ___PRODUCT_OPTION_END___ performance - }); - - // you can also configure SENTRY_DSN, SENTRY_RELEASE, SENTRY_DIST, and - // SENTRY_ENVIRONMENT via Dart environment variable (--dart-define) + await Sentry.init( + (options) { + options.dsn = '___PUBLIC_DSN___'; + + // Allows sending default personal data, such as IP addresses, + // when available from the SDK's integrations. + options.sendDefaultPii = true; + + // Enables Tracing. + // Set to 1.0 to capture 100% of spans for tracing. + // We recommend reducing this value in production. + options.tracesSampleRate = 1.0; + }, + appRunner: () async { + // Start your application here. + }, + ); + + // You can also configure SENTRY_DSN, SENTRY_RELEASE, SENTRY_DIST, and + // SENTRY_ENVIRONMENT via Dart environment variables (--dart-define). } ``` -## Verify Your Setup +The `appRunner` callback runs in a guarded error zone. This is required for automatic error capture on Dart web, where isolate error listeners are unavailable. For additional isolates, register an error listener with [`addSentryErrorListener`](https://pub.dev/documentation/sentry/latest/sentry_io/SentryIsolateExtension/addSentryErrorListener.html) from `package:sentry/sentry_io.dart`. -Let's test your setup and confirm that data reaches your Sentry project. +For finite command-line applications, call `await Sentry.close()` after all awaited application work finishes to flush buffered telemetry and close SDK resources, including the isolate error-listener port. -### Issues +## Send Logs -To verify that Sentry captures errors and creates issues in your Sentry project, add this intentional error to your application: +Call `Sentry.logger` from your application code after initialization to send structured logs at different levels. You can add attributes to make logs easier to search and filter. + +See Set Up Logs for all available logging methods and message formatting. ```dart -import 'package:sentry/sentry.dart'; +Sentry.logger.info('Order completed', attributes: { + 'order_id': SentryAttribute.string('12345'), + 'total': SentryAttribute.double(99.99), +}); + +Sentry.logger.warn('Slow operation detected'); +Sentry.logger.error('Validation failed'); +``` + +If you use the Dart `logging` package, add the `sentry_logging` integration to send its records to Sentry. + +## Send Application Metrics + +Call `Sentry.metrics` from your application code after initialization to send counters, gauges, and distributions. Add attributes to filter and group metrics in Sentry. + +See Set Up Metrics for metric types, attributes, and configuration options. +```dart +Sentry.metrics.count('checkout.failed', 1); +Sentry.metrics.gauge('queue.depth', 42); +Sentry.metrics.distribution('api_latency', 187, unit: 'millisecond'); +``` + +## Verify Your Setup + +Let's test your setup and confirm that data reaches your Sentry project. + +Add this inside the async `appRunner` callback to trigger and capture a test error: + +```dart try { throw StateError('Sentry Test Error'); } catch (exception, stackTrace) { @@ -87,16 +129,6 @@ try { } ``` - - - - - - - - - - ### View Captured Data in Sentry Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). @@ -105,16 +137,11 @@ Now, head over to your project on [Sentry.io](https://sentry.io) to view the col ## Next Steps -At this point, you should have integrated Sentry into your Dart application and should already be sending data to your Sentry project. - -Now's a good time to customize your setup and look into more advanced topics. -Our next recommended steps for you are: +At this point, you should have integrated Sentry into your Dart application. Here's what to explore next: - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Continue to customize your configuration - Learn more about manually capturing errors or messages -- Learn about the features of Sentry's Dart SDK -- Add performance instrumentation to your app +- Add performance instrumentation to your app diff --git a/docs/platforms/dart/guides/flutter/index.mdx b/docs/platforms/dart/guides/flutter/index.mdx index 95d9486c7c955..ee03b862a1d1a 100644 --- a/docs/platforms/dart/guides/flutter/index.mdx +++ b/docs/platforms/dart/guides/flutter/index.mdx @@ -1,6 +1,6 @@ --- title: Flutter -description: Learn how to set up Sentry in your Flutter app, capture your first errors and traces, and view them in Sentry. +description: Learn how to set up Sentry in your Flutter app, capture your first events, and view them in Sentry. caseStyle: camelCase supportLevel: production sdk: sentry.dart.flutter @@ -28,34 +28,34 @@ brew install getsentry/tools/sentry-wizard && sentry-wizard -i flutter ``` ```powershell {tabTitle:Windows} -$downloadUrl = "https://github.com/getsentry/sentry-wizard/releases/download/v5.1.0/sentry-wizard-win-x64.exe" +$downloadUrl = "https://github.com/getsentry/sentry-wizard/releases/download/v9.1.0/sentry-wizard-win-x64.exe" Invoke-WebRequest $downloadUrl -OutFile sentry-wizard.exe ./sentry-wizard.exe -i flutter ``` ```bash {tabTitle:macOS (Intel/x64)} -downloadUrl="https://github.com/getsentry/sentry-wizard/releases/download/v5.1.0/sentry-wizard-darwin-x64" +downloadUrl="https://github.com/getsentry/sentry-wizard/releases/download/v9.1.0/sentry-wizard-darwin-x64" curl -L $downloadUrl -o sentry-wizard chmod +x sentry-wizard ./sentry-wizard -i flutter ``` ```bash {tabTitle:macOS (Apple Silicon/arm64)} -downloadUrl="https://github.com/getsentry/sentry-wizard/releases/download/v5.1.0/sentry-wizard-darwin-arm64" +downloadUrl="https://github.com/getsentry/sentry-wizard/releases/download/v9.1.0/sentry-wizard-darwin-arm64" curl -L $downloadUrl -o sentry-wizard chmod +x sentry-wizard ./sentry-wizard -i flutter ``` ```bash {tabTitle:Linux (x64)} -downloadUrl="https://github.com/getsentry/sentry-wizard/releases/download/v5.1.0/sentry-wizard-linux-x64" +downloadUrl="https://github.com/getsentry/sentry-wizard/releases/download/v9.1.0/sentry-wizard-linux-x64" curl -L $downloadUrl -o sentry-wizard chmod +x sentry-wizard ./sentry-wizard -i flutter ``` ```bash {tabTitle:Linux (arm64)} -downloadUrl="https://github.com/getsentry/sentry-wizard/releases/download/v5.1.0/sentry-wizard-linux-arm64" +downloadUrl="https://github.com/getsentry/sentry-wizard/releases/download/v9.1.0/sentry-wizard-linux-arm64" curl -L $downloadUrl -o sentry-wizard chmod +x sentry-wizard ./sentry-wizard -i flutter @@ -65,7 +65,7 @@ chmod +x sentry-wizard npx @sentry/wizard@latest -i flutter ``` -This will patch your project and configure the SDK. You only need to patch the project once, then you can add the patched files to your version control system. +This will patch your project and configure the SDK. **Logs** and **Application Metrics** are enabled by default in SDK v10, and you'll learn how to send them in steps [#2](#send-logs) and [#3](#send-application-metrics-). You only need to patch the project once, then you can add the patched files to your version control system. If you prefer, you can also [set up the SDK manually](/platforms/dart/guides/flutter/manual-setup/). @@ -77,37 +77,47 @@ If you prefer, you can also [set up the SDK manually](/platforms/dart/guides/flu -The wizard will prompt you to enable optional features. Select the same options here so this guide can show you how to verify them: +## Send Logs - +Call `Sentry.logger` from your application code after initialization to send structured logs at different levels. You can add attributes to make logs easier to search and filter. - +See Set Up Logs for all available logging methods and message formatting. -## Verify Your Setup +```dart +Sentry.logger.info('Order completed', attributes: { + 'order_id': SentryAttribute.string('12345'), + 'total': SentryAttribute.double(99.99), +}); -Let's test your setup and confirm that data reaches your Sentry project. +Sentry.logger.warn('Slow operation detected'); +Sentry.logger.error('Validation failed'); +``` -### Issues +If you use the Dart `logging` package, add the `sentry_logging` integration to send its records to Sentry. -The wizard added a sample exception to `main.dart` that is captured when the app starts. Run your app to send it to Sentry: +## Send Application Metrics -```bash -flutter run -``` +Call `Sentry.metrics` from your application code after initialization to send counters, gauges, and distributions. Add attributes to filter and group metrics in Sentry. -After you've confirmed the issue in Sentry, remove the sample exception from `main.dart` so it isn't captured on every launch. +See Set Up Metrics for metric types, attributes, and configuration options. + +```dart +Sentry.metrics.count('checkout.failed', 1); +Sentry.metrics.gauge('queue.depth', 42); +Sentry.metrics.distribution('api_latency', 187, unit: 'millisecond'); +``` - +## Verify Your Setup - +Let's test your setup and confirm that data reaches your Sentry project. - +The wizard added a sample exception to main.dart that is captured when the app starts. Run your app to send it to Sentry: - +```bash +flutter run +``` - +After you've confirmed the issue in Sentry, remove the sample exception from `main.dart` so it isn't captured on every launch. ### View Captured Data in Sentry @@ -117,16 +127,12 @@ Now, head over to your project on [Sentry.io](https://sentry.io) to view the col ## Next Steps -At this point, you should have integrated Sentry into your Flutter application and should already be sending data to your Sentry project. - -Now's a good time to customize your setup and look into more advanced topics. -Our next recommended steps for you are: +At this point, you should have integrated Sentry into your Flutter application. Here's what to explore next: - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Continue to customize your configuration -- Add readable stack traces to errors -- Learn about the features of Sentry's Flutter SDK -- Add performance instrumentation to your app +- Upload debug symbols and source maps for readable production stack traces. The wizard configures `sentry_dart_plugin`; run `dart run sentry_dart_plugin` after each production build to upload the files. In CI, provide `SENTRY_AUTH_TOKEN` to the upload step. +- Learn about Session Replay and its privacy controls +- Add performance instrumentation to your app diff --git a/docs/platforms/dart/guides/flutter/manual-setup.mdx b/docs/platforms/dart/guides/flutter/manual-setup.mdx index 01831e8b2c5d4..33ab575b30990 100644 --- a/docs/platforms/dart/guides/flutter/manual-setup.mdx +++ b/docs/platforms/dart/guides/flutter/manual-setup.mdx @@ -1,10 +1,14 @@ --- title: Manual Setup sidebar_order: 1 -description: "Learn how to set up the Sentry Flutter SDK manually." +description: "Learn how to manually set up Sentry in your Flutter app, capture your first events, and view them in Sentry." --- -If you can't (or prefer not to) run the [automatic setup](/platforms/dart/guides/flutter/#install), you can follow the instructions below to configure your application manually. + + +Looking for automatic setup with the Flutter wizard? Follow the Flutter Quick Start instead. Continue with this guide to set up the SDK manually. + + @@ -36,19 +40,24 @@ Keep CocoaPods if other plugins still require it. Flutter can use both dependenc ## Configure -Choose the features you want to configure, and this guide will show you how: - - +Initialize **Error Monitoring** with `Sentry.init()` and run your application in its `appRunner` callback to capture uncaught exceptions and unhandled asynchronous errors. **Logs** and **Application Metrics** are enabled by default in SDK v10, and you'll learn how to send them in steps [#3](#send-logs) and [#4](#send-application-metrics-). +This guide also enables **Tracing** and **Session Replay**. ### Initialize the Sentry SDK -Configuration should happen as **early as possible** in your application's lifecycle. Logs and metrics are enabled by default; use `Sentry.logger` and `Sentry.metrics` after initialization without an enable flag. +Configuration should happen as **early as possible** in your application's lifecycle. + +Import and initialize the SDK in your app's entry point as shown in the code snippet below. -Import and initialize the SDK in your app's `main` function: +The snippet also turns on: + +- Tracing: via `tracesSampleRate` +- Session Replay: sampled with `replay.sessionSampleRate` and `replay.onErrorSampleRate` +- Additional user and request data: via `sendDefaultPii` + +To skip tracing, omit `tracesSampleRate`. To skip automatic Session Replay recording, omit both replay sample rates. To discard logs or metrics, return `null` from `beforeSendLog` or `beforeSendMetric`. ```dart import 'package:flutter/widgets.dart'; @@ -58,19 +67,20 @@ Future main() async { await SentryFlutter.init( (options) { options.dsn = '___PUBLIC_DSN___'; - // Adds request headers and IP for users, for more info visit: - // https://docs.sentry.io/platforms/dart/guides/flutter/data-management/data-collected/ + + /// Allows sending default personal data, such as IP addresses, + // when available from the SDK's integrations. options.sendDefaultPii = true; - // ___PRODUCT_OPTION_START___ performance - // Set tracesSampleRate to 1.0 to capture 100% of transactions for tracing. - // We recommend adjusting this value in production. + + // Enables Tracing. + // Set to 1.0 to capture 100% of spans for tracing. + // We recommend reducing this value in production. options.tracesSampleRate = 1.0; - // ___PRODUCT_OPTION_END___ performance - // ___PRODUCT_OPTION_START___ session-replay - // Record session replays for 100% of errors and 10% of sessions + + // Capture replays for 10% of all sessions, + // plus for 100% of sessions with an error options.replay.onErrorSampleRate = 1.0; options.replay.sessionSampleRate = 0.1; - // ___PRODUCT_OPTION_END___ session-replay }, appRunner: () => runApp( SentryWidget( @@ -84,13 +94,41 @@ Future main() async { } ``` +## Send Logs + +Call `Sentry.logger` from your application code after initialization to send structured logs at different levels. You can add attributes to make logs easier to search and filter. + +See Set Up Logs for all available logging methods and message formatting. + +```dart +Sentry.logger.info('Order completed', attributes: { + 'order_id': SentryAttribute.string('12345'), + 'total': SentryAttribute.double(99.99), +}); + +Sentry.logger.warn('Slow operation detected'); +Sentry.logger.error('Validation failed'); +``` + +If you use the Dart `logging` package, add the `sentry_logging` integration to send its records to Sentry. + +## Send Application Metrics + +Call `Sentry.metrics` from your application code after initialization to send counters, gauges, and distributions. Add attributes to filter and group metrics in Sentry. + +See Set Up Metrics for metric types, attributes, and configuration options. + +```dart +Sentry.metrics.count('checkout.failed', 1); +Sentry.metrics.gauge('queue.depth', 42); +Sentry.metrics.distribution('api_latency', 187, unit: 'millisecond'); +``` + ## Verify Your Setup Let's test your setup and confirm that data reaches your Sentry project. -### Issues - -To verify that Sentry captures errors and creates issues in your Sentry project, add this intentional error to your application: +Add this intentional error to your application: ```dart import 'package:sentry_flutter/sentry_flutter.dart'; @@ -105,15 +143,11 @@ try { } ``` - - - - - +Run your app to send the test error to Sentry: - - - +```bash +flutter run +``` ### View Captured Data in Sentry @@ -129,9 +163,7 @@ Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are: - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Continue to customize your configuration - Add readable stack traces to errors -- Learn about the features of Sentry's Flutter SDK - Add performance instrumentation to your app diff --git a/docs/platforms/dotnet/common/configuration/options.mdx b/docs/platforms/dotnet/common/configuration/options.mdx index 93cc6b25e6fec..20a4e356a7740 100644 --- a/docs/platforms/dotnet/common/configuration/options.mdx +++ b/docs/platforms/dotnet/common/configuration/options.mdx @@ -111,17 +111,32 @@ Sets the distribution of the application. Distributions are used to disambiguate Sets the release. The SDK will try to automatically configure a release out of the box but it's a better idea to manually set it to guarantee that the release is in sync with your deploy integrations or source map uploads. Release names are strings, but some formats are detected by Sentry and might be rendered differently. Learn more about how to send release data so Sentry can tell you about regressions between releases and identify the potential source in [the releases documentation](/product/releases/) or the sandbox. -By default the SDK will try to read this value from the `SENTRY_RELEASE` environment variable (in the browser SDK, this will be read off of the `window.SENTRY_RELEASE.id` if available). +If you don't set it, the SDK reads the `SENTRY_RELEASE` environment variable. If that isn't set either, the SDK uses the app package's version on Android, iOS and Mac Catalyst, and the entry assembly's version on other platforms. Setting a Release describes the format. + + + +In earlier versions, the release from the app package took precedence over `SENTRY_RELEASE`. + + - + Sets the environment. This string is freeform and set by default. A release can be associated with more than one environment to separate them in the UI (think `staging` vs `prod` or similar). -By default, the SDK reports `debug` when the debugger is attached. Otherwise, the default environment is `production`. +If you don't set it in code or configuration, the SDK reads the `SENTRY_ENVIRONMENT` environment variable. If that isn't set either: + +- ASP.NET Core, Blazor WebAssembly, Google Cloud Functions and [.NET Generic Host](/platforms/dotnet/guides/extensions-hosting/) apps (such as worker services) use the .NET host environment. The SDK lowercases `Production`, `Staging` and `Development` (for consistency with other Sentry SDKs), and keeps other names as they are. Set `AdjustStandardEnvironmentNameCasing` to `false` to keep the original casing. +- Other apps, such as console, MAUI and desktop apps, report `debug` when a debugger is attached, and `production` otherwise. So do ASP.NET Core and Generic Host apps that start Sentry with `SentrySdk.Init` instead of `UseSentry`. + +Setting `Scope.Environment` overrides the environment for everything captured with that scope: events, transactions, logs, metrics, sessions, check-ins and trace propagation. Set it to `null` to go back to the default. Sessions and traces use the environment from when they start, so changes to `Scope.Environment` don't affect a session or trace that's already running. -Additionally, if you are running with the ASP.NET Core integration, you will also see the environment named as `staging`, if running in staging, or `development`, if running in development mode. + + +In earlier versions, `Scope.Environment` applied only to events and transactions. + + @@ -387,7 +402,7 @@ A function responsible for determining the percentage chance a given transaction - + HTTP status codes that shouldn't be traced. When an incoming request results in one of these status codes, the SDK doesn't send its transaction to Sentry. Outgoing `HttpClient` requests aren't affected. @@ -405,8 +420,15 @@ Starting with version 7.0.0, the default is `301`, `305–399`, and `401–404`, options.TraceIgnoreStatusCodes.Clear(); ``` -In ASP.NET Core, you can also set this option in the `Sentry` section of `appsettings.json`. The configured list replaces the default and only takes single status codes, not ranges: - +In ASP.NET Core, you can also set this option in the `Sentry` section of `appsettings.json`. The configured list replaces the default and only takes single status codes, not ranges: + +```json {filename:appsettings.json} +{ + "Sentry": { + "TraceIgnoreStatusCodes": [404, 429] + } +} +``` diff --git a/docs/platforms/dotnet/common/crons/index.mdx b/docs/platforms/dotnet/common/crons/index.mdx index da4e734feb635..938a28eb809c8 100644 --- a/docs/platforms/dotnet/common/crons/index.mdx +++ b/docs/platforms/dotnet/common/crons/index.mdx @@ -10,7 +10,7 @@ Once implemented, it'll allow you to get alerts and metrics to help you solve er -If you are using [Hangfire](https://www.hangfire.io/), please see how to setup monitoring for Hangfire jobs. +If you are using [Hangfire](https://www.hangfire.io/), please see how to setup monitoring for Hangfire jobs. If you are using [Quartz.NET](https://www.quartz-scheduler.net/), see how to set up monitoring for Quartz.NET jobs. diff --git a/docs/platforms/dotnet/common/crons/quartz/index.mdx b/docs/platforms/dotnet/common/crons/quartz/index.mdx new file mode 100644 index 0000000000000..4b91e7739f96a --- /dev/null +++ b/docs/platforms/dotnet/common/crons/quartz/index.mdx @@ -0,0 +1,170 @@ +--- +title: Quartz.NET +description: "Learn how to monitor your Quartz.NET jobs." +sidebar_order: 5002 +--- + +The `Sentry.Quartz` and `Sentry.Quartz3` packages monitor your [Quartz.NET](https://www.quartz-scheduler.net/) jobs by [creating check-ins for them](/product/monitors-and-alerts/monitors/crons/job-monitoring/). They're available from SDK version 6.13.0. Use `Sentry.Quartz` with Quartz.NET 4.x and `Sentry.Quartz3` with Quartz.NET 3.x (3.6 and later). + +## Install + +```shell {tabTitle:.NET Core CLI} +dotnet add package Sentry.Quartz +``` + +```powershell {tabTitle:Package Manager} +Install-Package Sentry.Quartz +``` + +For Quartz.NET 3.x, install `Sentry.Quartz3` instead. With Quartz.NET 4.x, `Sentry.Quartz3` sends no check-ins and logs an error in debug mode. + +## Configure + +Initialize Sentry as usual, then add Sentry to your scheduler. + +### Quartz.NET 4.x + +Call `AddSentry` when you configure Quartz.NET: + +```csharp +using Quartz; +using Sentry.Quartz; + +builder.Services.AddQuartz(q => +{ + q.AddSentry(); +}); +``` + +Each job then runs in its own Sentry scope and trace, tagged with `quartz.job`, and the SDK captures the exceptions jobs throw in that scope. + +### Quartz.NET 3.x + +Add `SentryJobListener` to your scheduler. If you register Quartz.NET with dependency injection, `AddQuartz` comes from the `Quartz.Extensions.DependencyInjection` package, or from `Quartz.Extensions.Hosting` if you also run the scheduler as a hosted service: + +```csharp +using Quartz; +using Sentry.Quartz; + +builder.Services.AddQuartz(q => +{ + q.AddJobListener(); +}); +``` + +Or add the listener to a scheduler directly: + +```csharp +scheduler.ListenerManager.AddJobListener(new SentryJobListener()); +``` + +## Choose Which Jobs to Monitor + +For each monitored job, the SDK captures a check-in with `CheckInStatus.InProgress` when the job starts. When the job finishes, it updates the check-in to `CheckInStatus.Ok`, or to `CheckInStatus.Error` if the job threw an exception or was cancelled, along with how long the job ran. + +With Quartz.NET 4.x, the SDK captures each exception a job throws once, in the job's scope, so it's tagged with `quartz.job` and shares a trace with the check-in. + +With Quartz.NET 3.x, the SDK doesn't capture the exceptions jobs throw. A failed run still sends an error check-in, but Quartz.NET handles the exception itself and logs it as an error. That log entry only reaches Sentry if you use one of Sentry's hosting integrations, such as `Sentry.Extensions.Hosting` or `Sentry.AspNetCore`, or one of its logging integrations, such as `Sentry.Extensions.Logging`. These events aren't tagged with `quartz.job` and don't share a trace with the check-in. + +### Monitor All Jobs + +We recommend monitoring every scheduled job. Set `MonitorAllJobs`, and jobs whose trigger has a schedule Sentry can send are monitored without adding an attribute to each class. Jobs aren't monitored when the trigger that started them has a schedule Sentry can't send (see [Monitor Schedule](#monitor-schedule)), or when they're built without `WithIdentity`. Jobs whose triggers have different schedules, or that share a slug with a job on a different schedule, aren't monitored either, since Sentry can't create one monitor for them. + +To skip some jobs, add them to `ExcludedJobs`. A string matches a job whose name or full key (`group.name`) is equal to it, and a `Regex` matches a job whose name or full key it matches. Jobs with `[SentryMonitorSlug]` are monitored even when they match. + +```csharp {tabTitle:Quartz.NET 4.x} +q.AddSentry(options => +{ + options.MonitorAllJobs = true; + options.ExcludedJobs.Add("reports.AdhocExport"); + options.ExcludedJobs.Add(new Regex(@"^maintenance\.")); +}); +``` + +```csharp {tabTitle:Quartz.NET 3.x} +var options = new SentryQuartzOptions { MonitorAllJobs = true }; +options.ExcludedJobs.Add("reports.AdhocExport"); +q.AddJobListener(_ => new SentryJobListener(options)); +``` + +These jobs use the slug of their job key, described below. + +### Monitor Specific Jobs + +To monitor only some jobs, add the `SentryMonitorSlug` attribute to each job class you want to monitor. Jobs without it aren't monitored unless `MonitorAllJobs` is set. + +```csharp +[SentryMonitorSlug] +public class PricingUpdateJob : IJob +{ + // ... +} +``` + +With `MonitorAllJobs` on, a job with the attribute still sends one check-in per run, using the attribute's slug and settings. + +## Monitor Slugs + +To choose the slug, pass it to the attribute: + +```csharp +[SentryMonitorSlug("update-pricing")] +public class PricingUpdateJob : IJob +``` + +Without one, the slug is the job's group and name joined by `-`, or only the name for jobs in the default group, normalized the same way Sentry normalizes monitor slugs: lowercased, accents removed, spaces and dashes replaced by a single `-`, other characters dropped, and cut to 50 characters. For example, the job `billing.PricingUpdate` reports to `billing-pricingupdate`, `reports.Daily_Email (v2)` reports to `reports-daily_email-v2`, and the job `Cleanup` in the default group reports to `cleanup`. A job whose key leaves nothing is not monitored unless you set a slug. + +A job built without `WithIdentity` gets a new random name each time it's created, so the SDK uses the name of the job's class instead, such as `pricingupdatejob`. Give the job an identity or a slug to keep its monitor the same. If triggers that share a slug have different schedules, the SDK doesn't send a schedule for them. + +To use a different slug for one job or trigger, set `SentryMonitorSlugAttribute.JobDataKey` in its data map: + +```csharp +var job = JobBuilder.Create() + .WithIdentity("PricingUpdate", "billing") + .UsingJobData(SentryMonitorSlugAttribute.JobDataKey, "update-pricing") + .Build(); +``` + +## Monitor Schedule + +Sentry only creates a monitor from a check-in that includes a schedule. For monitored jobs, the SDK sends the schedule of the trigger that started the job: + +- Cron triggers, with the trigger's time zone. Quartz.NET cron triggers use the server's local time zone unless you set one with `InTimeZone`, so set it if your servers don't all use the same time zone. The cron expression must use a fixed number of seconds and no year, `L`, `W`, or `#`. Quartz.NET 3.x needs `?` in exactly one of the two day fields. Quartz.NET 4.x also accepts `*` or values in both. When both have values, the job runs on days that match either field, and Sentry reads the schedule the same way. +- Simple triggers that repeat forever every whole number of minutes, hours, or days. + +Other triggers, triggers with a calendar, and time zones without an IANA ID (Windows time zone IDs on .NET Framework) are sent without a schedule. So are triggers that share a slug but have different schedules, for example two triggers of the same job. To give each trigger its own monitor, set a different slug in each trigger's data map. + +Sentry can't create a monitor from a check-in without a schedule, so `MonitorAllJobs` skips these jobs. To monitor one anyway, add `[SentryMonitorSlug]` to it, and either create its monitor in Sentry or set its schedule with [`ConfigureMonitorOptions`](#monitor-settings). + +Sentry sets the monitor's schedule and time zone from every check-in that includes them, so changes you make to those two settings in Sentry are overwritten. Other monitor settings are kept. To stop sending the schedule for one job, set `SendMonitorConfig` on its attribute: + +```csharp +[SentryMonitorSlug(SendMonitorConfig = false)] +public class PricingUpdateJob : IJob +``` + +To stop sending it for all jobs, set `SendMonitorConfig` in the options: + +```csharp {tabTitle:Quartz.NET 4.x} +q.AddSentry(options => options.SendMonitorConfig = false); +``` + +```csharp {tabTitle:Quartz.NET 3.x} +q.AddJobListener(_ => new SentryJobListener(new SentryQuartzOptions { SendMonitorConfig = false })); +``` + +If you delete a monitor while its job is still monitored, the next run that sends a schedule creates it again. To stop monitoring a job, disable the monitor in Sentry, remove the attribute, or add the job to `ExcludedJobs`. + +## Monitor Settings + +To set other monitor settings, such as the thresholds or the maximum runtime, use `ConfigureMonitorOptions`. It runs before each in-progress check-in with the job's `IJobExecutionContext`, unless `SendMonitorConfig` is off. A schedule or time zone you set here is used instead of the trigger's. Sentry only receives these settings along with a schedule, from the trigger or set here, so you can also use it to set the schedule of a trigger the SDK can't send: + +```csharp +q.AddSentry(options => options.ConfigureMonitorOptions = (context, monitorOptions) => +{ + monitorOptions.MaxRuntime = TimeSpan.FromMinutes(30); + monitorOptions.FailureIssueThreshold = 3; +}); +``` + +With Quartz.NET 3.x, set it on the `SentryQuartzOptions` you pass to `SentryJobListener`. diff --git a/docs/platforms/dotnet/common/migration/v6-to-v7/index.mdx b/docs/platforms/dotnet/common/migration/v6-to-v7/index.mdx index 1e14ccb57b112..5bf6354d61167 100644 --- a/docs/platforms/dotnet/common/migration/v6-to-v7/index.mdx +++ b/docs/platforms/dotnet/common/migration/v6-to-v7/index.mdx @@ -74,6 +74,10 @@ The [Interactive 7.x Migration Guide](./interactive/) lets you check off complet +### Category Log Levels No Longer Filter Breadcrumbs and Events + + + ### Logging Frameworks No Longer Close Sentry diff --git a/docs/platforms/dotnet/common/tracing/instrumentation/opentelemetry-otlp.mdx b/docs/platforms/dotnet/common/tracing/instrumentation/opentelemetry-otlp.mdx index d502c3171ef3d..7f10623335e07 100644 --- a/docs/platforms/dotnet/common/tracing/instrumentation/opentelemetry-otlp.mdx +++ b/docs/platforms/dotnet/common/tracing/instrumentation/opentelemetry-otlp.mdx @@ -67,19 +67,56 @@ SentrySdk.Init(options => Under the hood, the OTLP exporter sets up the following parts: -* An OTLP exporter that automatically configures the ingestion endpoint from your Sentry DSN. This enables tracing in Sentry. **Note:** _Do not_ also set up tracing via the Sentry SDK (i.e. do not set `TracesSampleRate`). -* A `SentryPropagator` that injects `sentry-trace` and `baggage` headers alongside the standard W3C `traceparent` for compatibility with services using Sentry's native tracing +* An OTLP exporter that automatically configures the ingestion endpoint from your Sentry DSN. This enables tracing in Sentry. * Trace/Span linking for all other Sentry events such as Errors, Logs, and Metrics - +Calling `UseOtlp()` on `SentryOptions` turns off Sentry's automatic span creation from `SentryHttpMessageHandler`, `DiagnosticSource` listener, and Entity Framework interception to avoid duplicate spans. -The automatic propagator setup will be removed in the next major version. Configure propagators manually using the [OpenTelemetry propagation API](https://opentelemetry.io/docs/concepts/context-propagation/) instead. +## Sampling + +Because Sentry doesn't create transactions of its own when you call `UseOtlp()`, `TracesSampleRate` and `TracesSampler` have no effect. OpenTelemetry decides which spans are exported, so configure sampling on the `TracerProvider` instead: + +```csharp +using var tracerProvider = Sdk.CreateTracerProviderBuilder() + .AddSource("MyApp") + .SetSampler(new ParentBasedSampler(new TraceIdRatioBasedSampler(0.25))) + .AddSentryOtlpExporter("___PUBLIC_DSN___") + .Build(); +``` + +## Trace Propagation + +The OTLP exporter doesn't configure an OpenTelemetry propagator, so OpenTelemetry's default applies: it sends and reads W3C `traceparent`, `tracestate`, and `baggage` headers. Traces connect across services that use OpenTelemetry without additional configuration. See [Exporters, Event Linking, and Propagation](/concepts/otlp/sentry-with-otel/#exporters-event-linking-and-propagation) for details. + + + +Earlier versions of `AddSentryOtlpExporter` set `SentryPropagator` as OpenTelemetry's default propagator, and accepted a `defaultTextMapPropagator` parameter (as did `UseOtlp`) to use a different one. Version 7.0.0 removed the automatic setup and the parameter. To keep propagating `sentry-trace` headers, set the propagator yourself as shown below. -Cross-service trace propagation uses OTel's default W3C `traceparent` headers and does not require additional configuration. See [Exporters, Event Linking, and Propagation](/concepts/otlp/sentry-with-otel/#exporters-event-linking-and-propagation) for details. +Requests sent through `SentryHttpMessageHandler` also get a `sentry-trace` header. `UseOtlp()` stops the handler from creating spans, but not from adding headers. Sentry adds this handler to `IHttpClientFactory` clients automatically when you initialize Sentry through dependency injection, for example with `UseSentry()` in ASP.NET Core. -Calling `UseOtlp()` on `SentryOptions` sets `DisableSentryTracing = true`, which turns off Sentry's automatic span creation from `SentryHttpMessageHandler`, `DiagnosticSource` listener, and Entity Framework interception to avoid duplicate spans. +### Services That Use Sentry's Tracing + +Services that use a Sentry SDK's own tracing, rather than OpenTelemetry, continue traces from `sentry-trace` and `baggage` headers. When they receive a request that didn't go through `SentryHttpMessageHandler`, they start a new trace. + +To send a `sentry-trace` header on every request OpenTelemetry instruments, and to continue traces from incoming `sentry-trace` headers, add `SentryPropagator` (included in `Sentry.OpenTelemetry.Exporter`) next to the W3C propagator when configuring the OpenTelemetry SDK at startup: + +```csharp +using OpenTelemetry; +using OpenTelemetry.Context.Propagation; +using Sentry.OpenTelemetry; + +Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[] +{ + new TraceContextPropagator(), + new SentryPropagator(), +})); +``` + +If you only need to continue traces from services that call this one, enable [`propagateTraceparent`](/concepts/otlp/sentry-with-otel/#linking-sentry-and-otlp-traces) in their Sentry SDKs instead. They then also send a `traceparent` header, which OpenTelemetry reads by default. In .NET, that's the `PropagateTraceparent` option. You don't need it in the service that uses the OTLP exporter, because OpenTelemetry already sends `traceparent` from there. + +If the calling service hasn't made a sampling decision, for example because tracing is turned off there, its `traceparent` header is marked as not sampled (`-00`), since W3C trace context can't express an undecided state. OpenTelemetry's parent-based sampler then doesn't record this service's spans for those requests. ## Options @@ -93,12 +130,8 @@ Calling `UseOtlp()` on `SentryOptions` sets `DisableSentryTracing = true`, which URL of your own OpenTelemetry collector. When set, the exporter will send traces to this URL instead of the Sentry OTLP endpoint derived from the DSN. -- `defaultTextMapPropagator` (TextMapPropagator, optional): - - Override the default propagator. Defaults to `SentryPropagator`, which propagates `sentry-trace`, `baggage`, and W3C `traceparent` headers. This option will be removed alongside the automatic propagator setup in the next major version. - ## Supported Versions - .NET: 8.0+ / .NET Standard 2.0+ / .NET Framework 4.6.2+ - Sentry: 6.5.0+ -- OpenTelemetry: 1.10.0+ +- OpenTelemetry: 1.12.0+ diff --git a/docs/platforms/dotnet/guides/android/index.mdx b/docs/platforms/dotnet/guides/android/index.mdx index 275826bcbcc2c..3d2aa82fedf3d 100644 --- a/docs/platforms/dotnet/guides/android/index.mdx +++ b/docs/platforms/dotnet/guides/android/index.mdx @@ -32,7 +32,7 @@ On .NET for Android, you also get: - [Capture Application Not Responding (ANR) errors](/platforms/android/configuration/app-not-respond/) when the app is unresponsive - Automatically [attach screenshots to Java exceptions](/platforms/android/enriching-events/screenshots/) - Automatic breadcrumbs for Activity lifecycle, App lifecycle, System and Network events and User Interactions - - Automatic [Activity lifecycle tracing](/platforms/android/tracing/instrumentation/automatic-instrumentation/#activity-instrumentation) and [User Interaction tracing](/platforms/android/tracing/instrumentation/automatic-instrumentation/#user-interaction-instrumentation) + - Opt-in automatic [Activity lifecycle tracing](/platforms/android/tracing/instrumentation/automatic-instrumentation/#activity-instrumentation) and [User Interaction tracing](/platforms/android/tracing/instrumentation/automatic-instrumentation/#user-interaction-instrumentation) through the embedded Android SDK. See `Native.EnableTracing`. - Device Root checking - Native crash reporting for Android, leveraging our [Android NDK](/platforms/android/configuration/using-ndk/) - Automatic session tracking and [release health](/product/releases/) @@ -46,7 +46,12 @@ The snippet also turns on: Don't need a feature? Remove its options from the snippet. -```csharp +```csharp {filename:MainActivity.cs} +using Android.App; +using Android.OS; +using Sentry; +using Sentry.Android; + [Activity(Label = "@string/app_name", MainLauncher = true)] public class MainActivity : Activity { @@ -66,7 +71,7 @@ public class MainActivity : Activity #endif // Android specific .NET features are under the Android properties: - options.Android.LogCatIntegration = LogCatIntegrationType.Errors; // Get logcat logs for both handled and unhandled errors; default is unhandled only + options.Android.LogCatIntegration = LogCatIntegrationType.Errors; // Attach logcat logs to handled and unhandled errors; default is None. options.Android.LogCatMaxLines = 1000; // Defaults to 1000 // Native Android SDK options are available via options.Native @@ -163,7 +168,7 @@ Let's test your setup and confirm that data reaches your Sentry project. ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Next Steps diff --git a/docs/platforms/dotnet/guides/apple/index.mdx b/docs/platforms/dotnet/guides/apple/index.mdx index cacafbc17d0c4..025420afd9fd2 100644 --- a/docs/platforms/dotnet/guides/apple/index.mdx +++ b/docs/platforms/dotnet/guides/apple/index.mdx @@ -22,30 +22,35 @@ Install-Package Sentry -Version {{@inject packages.version('sentry.dotnet') }} **Error Monitoring** starts working as soon as you call `SentrySdk.Init()`. **Logs** sent through `SentrySdk.Logger` and **Application Metrics** need no extra configuration. You'll learn how to send them in [Send Logs](#send-logs) and [Send Application Metrics](#send-application-metrics-). -This guide also enables **Tracing**, **Profiling**, and **Session Replay** (experimental). +This guide also enables **Tracing**. The iOS and Mac Catalyst setup enables **Profiling**, and the iOS setup enables experimental **Session Replay**. -On .NET for iOS, macOS, and Mac Catalyst, you also get: +On all three platforms, you get the features of the main [.NET SDK](/platforms/dotnet/) for your managed code. On iOS and Mac Catalyst, the embedded [Cocoa SDK](/platforms/apple/) also provides: -- All the features of our main [.NET SDK](/platforms/dotnet/), for your managed code -- Native crash reporting for Apple platforms, leveraging our [Cocoa SDK](/platforms/apple/) including: +- Native crash reporting, including: - Automatically [attach screenshots to Native exceptions](/platforms/apple/guides/ios/configuration/options/#attachScreenshot) - Detect [App Hangs](/platforms/apple/configuration/app-hangs/) - - [Automatic performance tracing](/platforms/apple/tracing/) + - Opt-in [automatic performance tracing](/platforms/apple/tracing/). See `Native.EnableTracing`. - [Automatic breadcrumbs](/platforms/apple/enriching-events/breadcrumbs/#automatic-breadcrumbs) - [Swizzling](/platforms/apple/configuration/swizzling/) - Automatic session tracking and [release health](/product/releases/) -In your `AppDelegate.cs` file, call `SentrySdk.Init` in the `FinishedLaunching` event and include any options you would like to set. The `Dsn` is the only required parameter. +### iOS and Mac Catalyst + +In your `AppDelegate.cs` file, call `SentrySdk.Init` in `FinishedLaunching`. Keep your existing window and application setup after the Sentry initialization. The `Dsn` is the only required setting. The snippet also turns on: - Tracing: via `TracesSampleRate` - Profiling: via `ProfilesSampleRate`. On iOS and Mac Catalyst, the SDK adds the native profiling integration automatically, so you don't need the `Sentry.Profiling` package. -- Session Replay: via `Native.ExperimentalOptions.SessionReplay` +- Session Replay on iOS: via `Native.ExperimentalOptions.SessionReplay` Don't need a feature? Remove its options from the snippet. -```csharp +```csharp {filename:AppDelegate.cs} +using Foundation; +using Sentry; +using UIKit; + [Register("AppDelegate")] public class AppDelegate : UIApplicationDelegate { @@ -75,9 +80,11 @@ public class AppDelegate : UIApplicationDelegate // https://docs.sentry.io/platforms/apple/guides/ios/configuration/options/#attachScreenshot options.Native.AttachScreenshot = true; - // Session Replay is currently available via the ExperimentalOptions +#if IOS + // Session Replay is available on iOS via ExperimentalOptions. options.Native.ExperimentalOptions.SessionReplay.OnErrorSampleRate = 1.0; options.Native.ExperimentalOptions.SessionReplay.SessionSampleRate = 1.0; +#endif options.SetBeforeSend(evt => { @@ -103,11 +110,43 @@ public class AppDelegate : UIApplicationDelegate For a full list of native options, see Apple Native Options. +### macOS + +For an AppKit application targeting `net*-macos`, initialize Sentry in `NSApplicationDelegate.DidFinishLaunching`. This target doesn't include the Cocoa integration's `options.Native` or `OnCrashedLastRun` APIs. + +```csharp {filename:AppDelegate.cs} +using AppKit; +using Foundation; +using Sentry; + +[Register("AppDelegate")] +public class AppDelegate : NSApplicationDelegate +{ + public override void DidFinishLaunching(NSNotification notification) + { + SentrySdk.Init(options => + { + options.Dsn = "___PUBLIC_DSN___"; + options.SendDefaultPii = true; + options.IsGlobalModeEnabled = true; + options.TracesSampleRate = 1.0; +#if DEBUG + options.Debug = true; +#endif + }); + + // Keep the rest of your application startup here. + } +} +``` + +For custom transactions, see [Verify Your Setup](#verify-your-setup). The Cocoa profiling and replay configuration above doesn't apply to this target. + ### Options The .NET for iOS, macOS, and Mac Catalyst integration is part of [Sentry](/platforms/dotnet/). Please refer to the documentation for that package for information about platform agnostic options. -For configuration of the embedded Sentry Cocoa SDK, see Apple Native Options. +For configuration of the embedded Sentry Cocoa SDK on iOS and Mac Catalyst, see Apple Native Options. ## Send Logs @@ -141,9 +180,11 @@ Let's test your setup and confirm that data reaches your Sentry project. + + ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Next Steps @@ -152,4 +193,4 @@ At this point, you should have integrated Sentry into your .NET for iOS, macOS, - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup - Learn how to [manually capture errors](/platforms/dotnet/usage/) - Explore [Tracing](/platforms/dotnet/tracing/) -- Configure the embedded Cocoa SDK with Apple Native Options +- On iOS and Mac Catalyst, configure the embedded Cocoa SDK with Apple Native Options diff --git a/docs/platforms/dotnet/guides/aspnet/index.mdx b/docs/platforms/dotnet/guides/aspnet/index.mdx index a49d3a19ad296..d1dc0d15405d6 100644 --- a/docs/platforms/dotnet/guides/aspnet/index.mdx +++ b/docs/platforms/dotnet/guides/aspnet/index.mdx @@ -33,20 +33,18 @@ You configure the SDK in the `Global.asax.cs`: The snippet also turns on: - Tracing: via `TracesSampleRate` -- Logs from logging integrations: via `EnableLogs` Don't need a feature? Remove its options from the snippet. -```csharp +```csharp {filename:Global.asax.cs} using System; using System.Web; +using Sentry; using Sentry.AspNet; -using Sentry.EntityFramework; // If you also installed Sentry.EntityFramework -using Sentry.Extensibility; public class MvcApplication : HttpApplication { - private IDisposable _sentry; + private static IDisposable _sentry; protected void Application_Start() { @@ -58,14 +56,11 @@ public class MvcApplication : HttpApplication options.Debug = true; // Adds request URL and headers, IP and name for users, etc. options.SendDefaultPii = true; - options.EnableLogs = true; // Enables Tracing. // Set to 1.0 to capture 100% of spans for tracing. // We recommend reducing this value in production. options.TracesSampleRate = 1.0; - // If you also installed the Sentry.EntityFramework package - options.AddEntityFramework(); options.AddAspNet(); }); } @@ -90,6 +85,8 @@ public class MvcApplication : HttpApplication } ``` +If you also use Entity Framework 6, install `Sentry.EntityFramework` and add `options.AddEntityFramework()` to the same initialization callback. See the [Entity Framework guide](/platforms/dotnet/guides/entityframework/) for setup details. + ### Capturing the affected user When opting-in to [SendDefaultPii](#senddefaultpii), the SDK will automatically read the user from the request by inspecting `HttpContext.User`. Default claim values like `NameIdentifier` for the _Id_ will be used. @@ -104,7 +101,7 @@ options.SendDefaultPii = true; ### SendDefaultPii -Although this setting is part of the [Sentry](/platforms/dotnet/) package, in the context of ASP.NET Core, it means reporting the user by reading the frameworks `HttpContext.User`. The strategy to create the `SentryUser` can be customized. +Although this setting is part of the [Sentry](/platforms/dotnet/) package, in ASP.NET it also enables reporting the user from `HttpContext.User`. ### IncludeRequestPayload @@ -117,9 +114,15 @@ options.AddAspNet(RequestSize.Always); ## Send Logs -Use `SentrySdk.Logger` to send logs at different levels without an additional option. If you also send logs through an integration, set `EnableLogs = true` in the initialization snippet. +Use `SentrySdk.Logger` to send logs at different levels without an additional option. + +If you use Serilog, NLog, or log4net, see the documented [Serilog](/platforms/dotnet/guides/serilog/), [NLog](/platforms/dotnet/guides/nlog/), and [log4net](/platforms/dotnet/guides/log4net/) integrations. They send logs as soon as you add them. To drop logs you don't want, return `null` from `SetBeforeSendLog`. + + + +In earlier versions, the logging integrations only sent logs when `EnableLogs` was set to `true` in `SentrySdk.Init`. -If you use Serilog, NLog, or log4net, see the documented [Serilog](/platforms/dotnet/guides/serilog/), [NLog](/platforms/dotnet/guides/nlog/), and [log4net](/platforms/dotnet/guides/log4net/) integrations. + See Set Up Logs for all available logging methods and formatting options. @@ -151,7 +154,7 @@ Let's test your setup and confirm that data reaches your Sentry project. ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Troubleshooting diff --git a/docs/platforms/dotnet/guides/aspnetcore/index.mdx b/docs/platforms/dotnet/guides/aspnetcore/index.mdx index 4b33240722ece..55e5da0d84fd1 100644 --- a/docs/platforms/dotnet/guides/aspnetcore/index.mdx +++ b/docs/platforms/dotnet/guides/aspnetcore/index.mdx @@ -18,7 +18,7 @@ dotnet add package Sentry.AspNetCore -v {{@inject packages.version('sentry.dotne ``` ```shell {tabTitle:Paket CLI} -paket add Sentry --version {{@inject packages.version('sentry.dotnet.aspnetcore') }} +paket add Sentry.AspNetCore --version {{@inject packages.version('sentry.dotnet.aspnetcore') }} ``` This package extends [Sentry.Extensions.Logging](/platforms/dotnet/guides/extensions-logging/). This means that besides the ASP.NET Core related features, through this package you'll also get access to all the framework's logging integration and also the features available in the main [Sentry](/platforms/dotnet/) SDK. @@ -29,9 +29,9 @@ This package extends [Sentry.Extensions.Logging](/platforms/dotnet/guides/extens This guide also enables **Tracing**. -The simplest way to initialize Sentry in ASP.NET Core is by using the `UseSentry` extension method from the `Sentry.AspNetCore` package in conjunction with the [framework configuration system](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-7.0). +The simplest way to initialize Sentry in ASP.NET Core is by using the `UseSentry` extension method from the `Sentry.AspNetCore` package in conjunction with the [framework configuration system](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/). -Call `UseSentry` with your DSN and the options you want. The SDK provides this as extension methods to support ASP.NET Core `2.X`, `3.X`, and `5.X` and later. +`Sentry.AspNetCore` 6.x requires .NET 8 or later. Call `UseSentry` with your DSN and the options you want. For .NET 6 or 7, use `Sentry.AspNetCore` 4.x. The snippet also turns on: @@ -82,11 +82,12 @@ public static IWebHost BuildWebHost(string[] args) => // We recommend reducing this value in production. options.TracesSampleRate = 1.0; }) + .Build(); ``` ### Additional configuration -The framework takes configuration settings from `appsettings.json`, environment variables, or from code. These settings get applied to `Sentry.AspNetCore.SentryAspNetCoreOptions`, which extends `Sentry.Extensions.Logging.SentryLoggingOptions`, which in turn extends `Sentry.SentryOptions`. This means options for `Sentry.AspNetCore` as well as all the inner packages are available to be configured through the configuration system. +The framework takes configuration settings from `appsettings.json`, environment variables, or from code. These settings get applied to `SentryAspNetCoreOptions`, which extends `SentryHostOptions`, which in turn extends `SentryOptions`. This means options for `Sentry.AspNetCore` as well as all the inner packages are available to be configured through the configuration system. ### appsettings.json @@ -204,6 +205,21 @@ member this.ConfigureServices(services: IServiceCollection) = services.AddScoped() |> ignore ``` +### Clearing Logger Providers + +`ClearProviders()` removes every logger provider registered before it, including the ones `UseSentry` adds. Without them, `ILogger` entries don't reach Sentry. Call `UseSentry` after it: + +```csharp {filename:Program.cs} +var builder = WebApplication.CreateBuilder(args); +builder.Logging.ClearProviders(); +builder.Logging.AddConsole(); +builder.WebHost.UseSentry(); +``` + +If the app has to clear the providers after `UseSentry`, call `builder.Logging.AddSentry()` after `ClearProviders()`. It adds Sentry's providers back, with the options of `UseSentry`. Leave it out if NLog, Serilog, or log4net already sends your `ILogger` entries to Sentry, because each entry would then arrive twice. + +With `Debug` on, the SDK logs a warning through `ILogger` when the app starts if Sentry's providers were removed and not added back. + ### Options and Initialization As previously mentioned, this package is a wrapper around [Sentry.Extensions.Logging](/platforms/dotnet/guides/extensions-logging/) and [Sentry](/platforms/dotnet/). Please refer to the documentation of these packages to get the options that are defined at those levels. @@ -260,7 +276,7 @@ Opt-in to capture values from [System.Diagnostic.Activity](https://github.com/do ### Tunnel -If events are being logged to Sentry from the client-side, then you should use a [tunnel](/platforms/javascript/troubleshooting/#using-the-tunnel-option). +If events are being logged to Sentry from the client-side, then you should use a [tunnel](/platforms/javascript/configuration/tunneling/). A tunnel is an HTTP endpoint that acts as a proxy between Sentry and your application. Because you control this server, there is no risk of any requests sent to it being blocked. @@ -330,7 +346,7 @@ Let's test your setup and confirm that data reaches your Sentry project. ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Samples diff --git a/docs/platforms/dotnet/guides/aws-lambda/index.mdx b/docs/platforms/dotnet/guides/aws-lambda/index.mdx index 088b899271e1f..43b80991a643b 100644 --- a/docs/platforms/dotnet/guides/aws-lambda/index.mdx +++ b/docs/platforms/dotnet/guides/aws-lambda/index.mdx @@ -115,7 +115,7 @@ Let's test your setup and confirm that data reaches your Sentry project. ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Samples diff --git a/docs/platforms/dotnet/guides/azure-functions-worker/index.mdx b/docs/platforms/dotnet/guides/azure-functions-worker/index.mdx index 7fa4beee87e09..14745799700a8 100644 --- a/docs/platforms/dotnet/guides/azure-functions-worker/index.mdx +++ b/docs/platforms/dotnet/guides/azure-functions-worker/index.mdx @@ -1,34 +1,36 @@ --- title: Azure Functions -sdk: sentry.dotnet.azure.functions.worker +sdk: sentry.dotnet.extensions.hosting description: "Learn about Sentry's .NET integration with Azure Functions." --- -Sentry provides an integration with Azure Functions through the [Sentry.Extensions.Logging](https://www.nuget.org/packages/Sentry.Extensions.Logging) and [Sentry.OpenTelemetry.Exporter](https://www.nuget.org/packages/Sentry.OpenTelemetry.Exporter) NuGet packages. +Sentry provides an integration with Azure Functions through the [Sentry.Extensions.Hosting](https://www.nuget.org/packages/Sentry.Extensions.Hosting) and [Sentry.OpenTelemetry.Exporter](https://www.nuget.org/packages/Sentry.OpenTelemetry.Exporter) NuGet packages. ## Install Add the Sentry dependencies to your Azure Functions application: ```shell {tabTitle:.NET Core CLI} -dotnet add package Sentry.Extensions.Logging -v {{@inject packages.version('sentry.dotnet.extensions.logging') }} +dotnet add package Sentry.Extensions.Hosting -v {{@inject packages.version('sentry.dotnet') }} dotnet add package Sentry.OpenTelemetry.Exporter -v {{@inject packages.version('sentry.dotnet') }} dotnet add package OpenTelemetry.Extensions.Hosting dotnet add package OpenTelemetry.Instrumentation.Http ``` ```powershell {tabTitle:Package Manager} -Install-Package Sentry.Extensions.Logging -Version {{@inject packages.version('sentry.dotnet.extensions.logging') }} +Install-Package Sentry.Extensions.Hosting -Version {{@inject packages.version('sentry.dotnet') }} Install-Package Sentry.OpenTelemetry.Exporter -Version {{@inject packages.version('sentry.dotnet') }} Install-Package OpenTelemetry.Extensions.Hosting Install-Package OpenTelemetry.Instrumentation.Http ``` -The [Sentry.Extensions.Logging](/platforms/dotnet/guides/extensions-logging/) package also provides access to the `ILogger` integration and the other core features available in the [Sentry](/platforms/dotnet/) SDK. +This package extends [Sentry.Extensions.Logging](/platforms/dotnet/guides/extensions-logging/). This means you also get the `ILogger` integration and the other core features available in the [Sentry](/platforms/dotnet/) SDK. ## Configure -**Error Monitoring** starts working as soon as you initialize the SDK by calling `AddSentry` when configuring logging. **Logs** sent through `Microsoft.Extensions.Logging` need `EnableLogs = true`, and **Application Metrics** need no extra configuration. You'll learn how to send them in [Send Logs](#send-logs) and [Send Application Metrics](#send-application-metrics-). +**Error Monitoring** starts working as soon as you call `UseSentry` on the host builder. **Logs** sent through `Microsoft.Extensions.Logging` need `EnableLogs = true`, and **Application Metrics** need no extra configuration. You'll learn how to send them in [Send Logs](#send-logs) and [Send Application Metrics](#send-application-metrics-). + +`UseSentry` starts Sentry when the host is built and closes it when the host stops. It also adds Sentry's `ILogger` integration, which captures `LogError` and higher as events. See the [Generic Host](/platforms/dotnet/guides/extensions-hosting/) guide for its configuration options. This guide also enables **Tracing** through OpenTelemetry. Sentry's OTLP exporter is added to the OpenTelemetry `TracerProviderBuilder`, and `UseOtlp()` tells the Sentry SDK to use OpenTelemetry for tracing. @@ -42,11 +44,17 @@ Don't need a feature? Remove its options from the snippet. ```csharp using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; using OpenTelemetry.Trace; var host = new HostBuilder() .ConfigureFunctionsWorkerDefaults() + .UseSentry(options => + { + options.Dsn = "___PUBLIC_DSN___"; + options.EnableLogs = true; + options.UseOtlp(); // <-- Configure Sentry to use OpenTelemetry for tracing + options.Debug = true; + }) .ConfigureServices(services => { services.AddOpenTelemetry().WithTracing(builder => @@ -56,26 +64,24 @@ var host = new HostBuilder() .AddHttpClientInstrumentation(); // From OpenTelemetry.Instrumentation.Http, instruments outgoing HTTP requests }); }) - .ConfigureLogging(logging => - { - logging.AddSentry(options => - { - options.Dsn = "___PUBLIC_DSN___"; - options.EnableLogs = true; - options.UseOtlp(); // <-- Configure Sentry to use OpenTelemetry for tracing - options.Debug = true; - }); - }) .Build(); await host.RunAsync(); ``` +Apps that use the ASP.NET Core integration, with `ConfigureFunctionsWebApplication()` instead of `ConfigureFunctionsWorkerDefaults()`, call the same `UseSentry`, not the one from `Sentry.AspNetCore`. + + + +In earlier versions, there was no `Sentry.Extensions.Hosting` package. On those versions, install `Sentry.Extensions.Logging` and pass the same options to `logging.AddSentry(options => ...)` in `ConfigureLogging`, instead of calling `UseSentry`. + + + ## Send Logs -Use `Microsoft.Extensions.Logging` to send structured logs from your application. Set `EnableLogs = true` in your Sentry initialization. +Use `Microsoft.Extensions.Logging` to send structured logs from your application. Set `EnableLogs = true` in the options you pass to `UseSentry`. -See [Microsoft.Extensions.Logging](/platforms/dotnet/guides/extensions-logging/) for setup details. +See [Generic Host](/platforms/dotnet/guides/extensions-hosting/#send-logs) for setup details. See Set Up Logs for all available logging methods and formatting options. @@ -119,7 +125,7 @@ Let's test your setup and confirm that data reaches your Sentry project. ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Samples diff --git a/docs/platforms/dotnet/guides/blazor-server/index.mdx b/docs/platforms/dotnet/guides/blazor-server/index.mdx index c05548bffc813..0071c897b4859 100644 --- a/docs/platforms/dotnet/guides/blazor-server/index.mdx +++ b/docs/platforms/dotnet/guides/blazor-server/index.mdx @@ -73,16 +73,30 @@ However, on .NET 10 and later, Blazor emits OpenTelemetry activities for circuit #### Install OpenTelemetry -See OpenTelemetry Support for installation and setup instructions. +Install the OTLP exporter and OpenTelemetry instrumentation: + +```shell {tabTitle:.NET Core CLI} +dotnet add package Sentry.OpenTelemetry.Exporter -v {{@inject packages.version('sentry.dotnet') }} +dotnet add package OpenTelemetry.Extensions.Hosting +dotnet add package OpenTelemetry.Instrumentation.AspNetCore +``` + +```powershell {tabTitle:Package Manager} +Install-Package Sentry.OpenTelemetry.Exporter -Version {{@inject packages.version('sentry.dotnet') }} +Install-Package OpenTelemetry.Extensions.Hosting +Install-Package OpenTelemetry.Instrumentation.AspNetCore +``` + +See OpenTelemetry (OTLP) for sampling and trace propagation. #### Configure OpenTelemetry -Wire up Sentry as an OpenTelemetry exporter, subscribe to the Blazor activity sources, and register helper services for circuit and breadcrumb tracking: +Copy the [helper services](#circuit-lifecycle-tracking-services) into your application and add a `using` directive for their namespace. Then configure the OTLP exporter, subscribe to the Blazor activity sources, and register the helpers: ```csharp {filename:Program.cs} using Microsoft.AspNetCore.Components.Server.Circuits; using OpenTelemetry.Trace; -using Sentry.OpenTelemetry; +using Sentry; var builder = WebApplication.CreateBuilder(args); @@ -95,18 +109,14 @@ builder.Services.AddOpenTelemetry() tracing.AddSource("Microsoft.AspNetCore.Components"); tracing.AddSource("Microsoft.AspNetCore.Components.Server.Circuits"); tracing.AddAspNetCoreInstrumentation(); - // Export traces to Sentry - tracing.AddSentry(); + tracing.SetSampler(new ParentBasedSampler(new TraceIdRatioBasedSampler(0.1))); + tracing.AddSentryOtlpExporter("___PUBLIC_DSN___"); }); builder.WebHost.UseSentry(options => { options.Dsn = "___PUBLIC_DSN___"; - options.UseOpenTelemetry(); - // Enables Tracing. - // Set to 1.0 to capture 100% of spans for tracing. - // We recommend reducing this value in production. - options.TracesSampleRate = 0.1; + options.UseOtlp(); // Rewrites /_blazor SignalR transaction names to the actual Blazor route options.AddEventProcessor(new BlazorEventProcessor()); }); @@ -128,6 +138,8 @@ app.MapFallbackToPage("/_Host"); app.Run(); ``` +OpenTelemetry handles sampling in this configuration. Don't also set `TracesSampleRate` on the Sentry options. + #### Circuit Lifecycle Tracking Services The `BlazorSentryIntegration`, `SentryCircuitHandler`, and `BlazorEventProcessor` services shown above are not part of the Sentry integration. You can copy them from the [Blazor Server sample](https://github.com/getsentry/sentry-dotnet/tree/main/samples/Sentry.Samples.AspNetCore.Blazor.Server/Services) into your application if they prove useful for your use case. @@ -174,7 +186,7 @@ Let's test your setup and confirm that data reaches your Sentry project. ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Samples diff --git a/docs/platforms/dotnet/guides/blazor-webassembly/index.mdx b/docs/platforms/dotnet/guides/blazor-webassembly/index.mdx index bafbb652e24b1..14ca1ffb4818b 100644 --- a/docs/platforms/dotnet/guides/blazor-webassembly/index.mdx +++ b/docs/platforms/dotnet/guides/blazor-webassembly/index.mdx @@ -25,10 +25,7 @@ This package extends [Sentry.Extensions.Logging](/platforms/dotnet/guides/extens This guide also enables **Tracing**. - -Sentry integration with Blazor WebAssembly is done by calling `.UseSentry()` and specifying the options, for example: - - +Sentry integration with Blazor WebAssembly is done by calling `.UseSentry()` and specifying the options. `UseSentry` also adds Sentry's `ILogger` integration, which captures `LogError` and higher as events. The snippet also turns on: @@ -39,7 +36,6 @@ Don't need a feature? Remove its options from the snippet. ```csharp using Microsoft.AspNetCore.Components.WebAssembly.Hosting; -using Microsoft.Extensions.Logging; var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.UseSentry(options => @@ -53,15 +49,14 @@ builder.UseSentry(options => // Enables Tracing. // Set to 1.0 to capture 100% of spans for tracing. // We recommend reducing this value in production. - options.TracesSampleRate = 0.1; + options.TracesSampleRate = 1.0; }); -// Captures logError and higher as events -builder.Logging.AddSentry(o => o.InitializeSdk = false); - await builder.Build().RunAsync(); ``` +`UseSentry` also registers the logging integration. Don't call `builder.Logging.AddSentry` separately. + ## Send Logs Use `Microsoft.Extensions.Logging` to send structured logs from your application. Set `EnableLogs = true` in your Sentry initialization. @@ -108,9 +103,11 @@ Let's test your setup and confirm that data reaches your Sentry project. + + ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Samples diff --git a/docs/platforms/dotnet/guides/entityframework/index.mdx b/docs/platforms/dotnet/guides/entityframework/index.mdx index d08272d0a7fc5..02568c407640b 100644 --- a/docs/platforms/dotnet/guides/entityframework/index.mdx +++ b/docs/platforms/dotnet/guides/entityframework/index.mdx @@ -5,7 +5,7 @@ description: Learn about Sentry's .NET integration with Entity Framework. og_image: /og-images/platforms-dotnet-guides-entityframework.png --- -Sentry provides an integration with `EntityFramework` through the of the [Sentry.EntityFramework NuGet package](https://www.nuget.org/packages/Sentry.EntityFramework). +Sentry provides an integration with Entity Framework 6 through the [Sentry.EntityFramework NuGet package](https://www.nuget.org/packages/Sentry.EntityFramework). > Looking for `EntityFramework Core`? If you're targeting .NET Core 3.1 or newer, that's already built in to the main Sentry .NET SDK. It's also enabled by default for our ASP.NET or ASP.NET Core integrations, even for older targets. For other scenarios, you may need to add the `Sentry.DiagnosticSource` package and call `AddDiagnosticSourceIntegration`, [as described here](/platforms/dotnet/tracing/instrumentation/automatic-instrumentation/#diagnosticsource-integration). (The rest of this page describes our EF6 integration, not EFCore.) @@ -40,7 +40,15 @@ Add the Entity Framework 6 support to your project in one step: ### Example configuration -For example, configuring an ASP.NET app with _global.asax_: +The following example configures an ASP.NET application in `Global.asax.cs`. In addition to `Sentry.EntityFramework`, install [Sentry.AspNet](/platforms/dotnet/guides/aspnet/), which provides request context, request-scoped data, and the HTTP transaction helpers used here: + +```powershell {tabTitle:Package Manager} +Install-Package Sentry.AspNet -Version {{@inject packages.version('sentry.dotnet.aspnet') }} +``` + +```shell {tabTitle:.NET Core CLI} +dotnet add package Sentry.AspNet -v {{@inject packages.version('sentry.dotnet.aspnet') }} +``` The snippet also turns on: @@ -48,14 +56,15 @@ The snippet also turns on: Don't need a feature? Remove its options from the snippet. -```csharp {filename:global.asax} +```csharp {filename:Global.asax.cs} using System; using System.Configuration; +using Sentry; using Sentry.AspNet; public class MvcApplication : System.Web.HttpApplication { - private IDisposable _sentrySdk; + private static IDisposable _sentrySdk; protected void Application_Start() { @@ -69,7 +78,7 @@ public class MvcApplication : System.Web.HttpApplication // Set to 1.0 to capture 100% of spans for tracing. // We recommend reducing this value in production. options.TracesSampleRate = 1.0; - // Add the EntityFramework integration + options.AddAspNet(); options.AddEntityFramework(); }); } @@ -85,10 +94,9 @@ public class MvcApplication : System.Web.HttpApplication { Context.FinishSentryTransaction(); } - public override void Dispose() + protected void Application_End() { - _sentrySdk.Dispose(); - base.Dispose(); + _sentrySdk?.Dispose(); } } ``` @@ -127,11 +135,11 @@ Let's test your setup and confirm that data reaches your Sentry project. ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Sample -Check out a complete working [sample](https://github.com/getsentry/sentry-dotnet-ef/tree/master/samples/Sentry.Samples.AspNet.Mvc) to see it in action. +See the [Entity Framework sample](https://github.com/getsentry/sentry-dotnet/tree/main/samples/Sentry.Samples.EntityFramework) for a standalone application using this integration. ![Sample breadcrumbs in Sentry](./img/dotnet-entityframework.png) diff --git a/docs/platforms/dotnet/guides/extensions-hosting/index.mdx b/docs/platforms/dotnet/guides/extensions-hosting/index.mdx new file mode 100644 index 0000000000000..0dcc874e23160 --- /dev/null +++ b/docs/platforms/dotnet/guides/extensions-hosting/index.mdx @@ -0,0 +1,342 @@ +--- +title: Generic Host +sdk: sentry.dotnet.extensions.hosting +description: "Learn about Sentry's .NET integration with the .NET Generic Host, for worker services, console apps, and Windows services." +--- + +Sentry provides an integration with the [.NET Generic Host](https://learn.microsoft.com/dotnet/core/extensions/generic-host) through the [Sentry.Extensions.Hosting NuGet package](https://www.nuget.org/packages/Sentry.Extensions.Hosting). Use it in worker services, Windows services, and console apps that run on the host. Azure Functions apps on the isolated worker model use it too, with or without the ASP.NET Core integration. + + + +In earlier versions, generic host apps initialized Sentry with `builder.Logging.AddSentry()`. To upgrade, see the migration guide. + + + +## Install + +Add the Sentry dependency: + +```shell {tabTitle:.NET Core CLI} +dotnet add package Sentry.Extensions.Hosting -v {{@inject packages.version('sentry.dotnet') }} +``` + +```powershell {tabTitle:Package Manager} +Install-Package Sentry.Extensions.Hosting -Version {{@inject packages.version('sentry.dotnet') }} +``` + +The package brings in [Sentry.Extensions.Logging](/platforms/dotnet/guides/extensions-logging/) and the core [Sentry](/platforms/dotnet/) SDK, so you don't need to add them yourself. + +## Configure + +**Error Monitoring** starts working as soon as you initialize the SDK. **Logs** sent through `Microsoft.Extensions.Logging` need `EnableLogs = true`, and **Application Metrics** need no extra configuration. You'll learn how to send them in [Send Logs](#send-logs) and [Send Application Metrics](#send-application-metrics-). + +This guide also enables **Tracing**. + +Call `UseSentry` on the host builder. It initializes Sentry, adds Sentry's `ILogger` integration, and registers `IHub`, `ISentryClient`, and `Func` for dependency injection. It's available on: + +- `IHostApplicationBuilder`, which `Host.CreateApplicationBuilder()` returns, on .NET 8 and later. +- `IHostBuilder`, which `Host.CreateDefaultBuilder()` returns, on every target, including [.NET Framework](#net-framework). + +The snippet also turns on: + +- Logs: via `EnableLogs` +- Tracing: via `TracesSampleRate` + +Don't need a feature? Remove its options from the snippet. + +```csharp {tabTitle:IHostApplicationBuilder} {filename:Program.cs} {mdExpandTabs} +var builder = Host.CreateApplicationBuilder(args); +builder.UseSentry(options => +{ + options.Dsn = "___PUBLIC_DSN___"; + // Send ILogger entries to Sentry as logs + options.EnableLogs = true; + // Enables Tracing. + // Set to 1.0 to capture 100% of spans for tracing. + // We recommend reducing this value in production. + options.TracesSampleRate = 1.0; +}); +builder.Services.AddHostedService(); + +await builder.Build().RunAsync(); +``` + +```csharp {tabTitle:IHostBuilder} {filename:Program.cs} +await Host.CreateDefaultBuilder(args) + .UseSentry(options => + { + options.Dsn = "___PUBLIC_DSN___"; + // Send ILogger entries to Sentry as logs + options.EnableLogs = true; + // Enables Tracing. + // Set to 1.0 to capture 100% of spans for tracing. + // We recommend reducing this value in production. + options.TracesSampleRate = 1.0; + }) + .ConfigureServices(services => services.AddHostedService()) + .Build() + .RunAsync(); +``` + +Don't also call `builder.Logging.AddSentry()`. `UseSentry` already adds Sentry's logger providers, so that call has no effect, and the options passed to it are ignored. The one exception is [clearing the logger providers](#clearing-logger-providers). + +A worker has no incoming requests, so Sentry doesn't start transactions on its own. Start one around each unit of work, as shown in Custom Instrumentation. Requests your app makes through `IHttpClientFactory` inside a transaction become spans. + +### Configuration + +`UseSentry` reads its options from the `Sentry` section of your configuration, such as `appsettings.json`, and the log levels from `Logging:Sentry`. Options set in the callback are applied after the configuration, so they win. + +```json {filename:appsettings.json} +{ + "Logging": { + "Sentry": { + "MinimumBreadcrumbLevel": "Debug", + "MinimumEventLevel": "Warning" + } + }, + "Sentry": { + "Dsn": "___PUBLIC_DSN___", + "SendDefaultPii": true, + "EnableLogs": true, + "TracesSampleRate": 1.0 + } +} +``` + +`Logging:Sentry` only takes `LogLevel`, `MinimumBreadcrumbLevel`, and `MinimumEventLevel`. Any other key there, such as `Dsn`, makes `Build()` throw. + +To turn Sentry off, for example during local development, set `"Dsn": ""`. The `SENTRY_DSN` environment variable still takes precedence over an empty `Dsn`. If no DSN is set anywhere, `Build()` throws. + +### Environment + +The SDK uses the host environment as the Sentry environment. The host environment defaults to `Production`, and you usually set it with `DOTNET_ENVIRONMENT`. The SDK lowercases `Production`, `Staging`, and `Development`, and keeps other names as they are. To keep the original casing, set `AdjustStandardEnvironmentNameCasing` to `false`. + +An `Environment` set in code or in the `Sentry` section takes precedence, followed by the `SENTRY_ENVIRONMENT` environment variable. + +### When Sentry Starts and Stops + +`UseSentry` starts the SDK in `Build()`, before any hosted service starts, so code that runs between `Build()` and `Run()` is covered too. That's also the case when the app clears the logger providers or replaces the logger factory. + +The SDK closes when the host raises `ApplicationStopped`, after the hosted services have stopped. Errors logged while the app shuts down are still sent. + +### Clearing Logger Providers + +`ClearProviders()` removes every logger provider registered before it, including the ones `UseSentry` adds. Call `UseSentry` after it: + +```csharp {filename:Program.cs} +var builder = Host.CreateApplicationBuilder(args); +builder.Logging.ClearProviders(); +builder.Logging.AddConsole(); +builder.UseSentry(); +``` + +If the app has to clear the providers after `UseSentry`, call `builder.Logging.AddSentry()` after `ClearProviders()`. It adds Sentry's providers back, with the options of `UseSentry`. Leave it out if NLog, Serilog, or log4net already sends your `ILogger` entries to Sentry, because each entry would then arrive twice. + +With `Debug` on, the SDK logs a warning during `Build()` when Sentry's providers were removed and not added back. + +### ASP.NET Core and MAUI Apps + +Web and MAUI apps use `UseSentry` from [Sentry.AspNetCore](/platforms/dotnet/guides/aspnetcore/) or [Sentry.Maui](/platforms/dotnet/guides/maui/). `WebApplicationBuilder` and `MauiAppBuilder` implement `IHostApplicationBuilder`, so the generic `UseSentry` compiles there too. With only the generic call, those apps miss what their own integration adds: + +- ASP.NET Core apps get no request data on events, and no transactions for incoming requests. +- MAUI apps get no navigation or UI breadcrumbs, and Sentry starts only when the app first uses a logger or `IHub`. + +The generic `UseSentry` warns about this once. In a web app, it logs the warning through `ILogger` when the host starts. In a MAUI app, it writes the warning to standard error. + +If an app calls both, the generic `UseSentry` steps aside, in either order, and the app runs with the ASP.NET Core or MAUI integration and its options. + +### .NET Aspire Service Defaults + +The `AddServiceDefaults` method in an Aspire ServiceDefaults project takes any `IHostApplicationBuilder`, so it runs in web projects as well as workers. Its `Extensions.cs` file is declared in the `Microsoft.Extensions.Hosting` namespace. C# looks for extension methods in the enclosing namespace before the ones from `using` directives, so in that file, `web.UseSentry()` calls the generic `UseSentry`, even on a `WebApplicationBuilder`. Call the ASP.NET Core or MAUI `UseSentry` as a static method instead: + +```csharp {tabTitle:ASP.NET Core} {filename:Extensions.cs} +using Microsoft.AspNetCore.Builder; + +namespace Microsoft.Extensions.Hosting; + +public static class Extensions +{ + public static TBuilder AddServiceDefaults(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + if (builder is WebApplicationBuilder web) + { + SentryWebApplicationBuilderExtensions.UseSentry(web); + } + else + { + builder.UseSentry(); + } + + // ... + return builder; + } +} +``` + +```csharp {tabTitle:MAUI} {filename:Extensions.cs} +using Microsoft.Maui.Hosting; + +namespace Microsoft.Extensions.Hosting; + +public static class Extensions +{ + public static TBuilder AddServiceDefaults(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + if (builder is MauiAppBuilder maui) + { + SentryMauiAppBuilderExtensions.UseSentry(maui); + } + else + { + builder.UseSentry(); + } + + // ... + return builder; + } +} +``` + +The ServiceDefaults project then needs both `Sentry.Extensions.Hosting` and `Sentry.AspNetCore` or `Sentry.Maui`. + +Don't call the ASP.NET Core `UseSentry` again in the web project's `Program.cs`: with two calls, each error is sent twice. The generic `UseSentry` doesn't have that problem. If a worker calls it in `AddServiceDefaults` and again in `Program.cs`, Sentry is set up once, with the options from both calls. + +### .NET Framework + +On .NET Framework, `UseSentry` is only available on `IHostBuilder`. The package supports Microsoft.Extensions.Hosting 3.1 and later there, and `IHostApplicationBuilder` only exists from 8.0. An app that uses `Host.CreateApplicationBuilder()` can switch to `Host.CreateDefaultBuilder()`, as in the `IHostBuilder` example [above](#configure). + +The app can also keep `Host.CreateApplicationBuilder()`, initialize Sentry with `SentrySdk.Init`, and add the logging integration with `builder.Logging.AddSentry()`. It then doesn't read the `Sentry` section, and Sentry doesn't start and close with the host. `Logging.AddSentry()` doesn't register `IHub`, `ISentryClient`, or `Func`, so register them if your services inject them: + +```csharp {filename:Program.cs} +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Sentry.Extensibility; + +using var sentry = SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; +}); + +var builder = Host.CreateApplicationBuilder(args); +builder.Logging.AddSentry(); +builder.Services.AddSingleton(HubAdapter.Instance); +builder.Services.AddSingleton(HubAdapter.Instance); +builder.Services.AddSingleton>(() => HubAdapter.Instance); +builder.Services.AddHostedService(); + +await builder.Build().RunAsync(); +``` + +Disposing the object that `SentrySdk.Init` returns sends any pending events before the app exits. + +### Replacing SentrySdk.Init + +If your app calls `SentrySdk.Init`, remove that call when you add `UseSentry`, unless it's there for [capturing startup crashes](#capturing-startup-crashes). Move its options into the `UseSentry` callback or the `Sentry` section. Whichever initialization runs last wins, and the two don't merge their options. + +If the app also calls `builder.Logging.AddSentry()`, remove that too. With `SentrySdk.Init`, it sent every `ILogger` entry as a structured log. `UseSentry` leaves that off, so set `EnableLogs = true` to keep sending them. + +### Capturing Startup Crashes + +`UseSentry` starts Sentry in `Build()`. If the app crashes before then, for example while it reads configuration or registers services, the crash isn't sent. + +To capture these crashes, also call `SentrySdk.Init` before you create the builder, and capture the exception if startup fails: + +```csharp {filename:Program.cs} +using var sentry = SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; +}); + +try +{ + var builder = Host.CreateApplicationBuilder(args); + builder.UseSentry(options => + { + options.Dsn = "___PUBLIC_DSN___"; + }); + builder.Services.AddHostedService(); + + await builder.Build().RunAsync(); +} +catch (Exception ex) +{ + SentrySdk.CaptureException(ex); + throw; +} +``` + +The two initializations don't share anything: + +- `SentrySdk.Init` runs before the app reads `appsettings.json` or the host environment. Set its DSN in code or with the `SENTRY_DSN` environment variable. To report startup crashes in the same environment as the rest of the app, set `SENTRY_ENVIRONMENT`, which `UseSentry` reads too. +- `UseSentry` doesn't reuse those options. Give it a DSN as well, in its callback or the `Sentry` section. +- In `Build()`, `UseSentry` replaces the first initialization. Crashes before then are sent with the first initialization's options, such as its release and environment. Breadcrumbs added before then aren't carried over. +- Errors after `Build()`, such as a hosted service that fails to start, are sent by `UseSentry`. `CaptureException` doesn't send them a second time. + +## Send Logs + +Use `Microsoft.Extensions.Logging` to send structured logs from your application. Set `EnableLogs = true` in the `UseSentry` options or in the `Sentry` section. It's off by default, as in the ASP.NET Core and MAUI integrations. + +See Set Up Logs for all available logging methods and formatting options. + +```csharp {filename:Worker.cs} +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +public sealed class Worker(ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + logger.LogInformation("Processing batch {BatchId}", Guid.NewGuid()); + await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); + } + } +} +``` + +`EnableLogs` doesn't change how errors and breadcrumbs are captured. Entries at `Error` and above are sent as events, and entries at `Information` and above are kept as breadcrumbs. To change that, set `MinimumEventLevel` and `MinimumBreadcrumbLevel`. + +To drop specific entries before they become breadcrumbs or events, call [`AddLogEntryFilter`](/platforms/dotnet/guides/extensions-logging/#log-entry-filters) in the `UseSentry` callback. + +## Send Application Metrics + +Metrics are enabled by default. Use `SentrySdk.Metrics` to send counters, gauges, and distributions from your app. + +See Set Up Metrics for all available metric types and configuration options. + +```csharp +SentrySdk.Metrics.EmitCounter("button_click", 5, + new Dictionary { ["browser"] = "Firefox" }); +SentrySdk.Metrics.EmitGauge("page_load", 15.0, MeasurementUnit.Duration.Millisecond, + new Dictionary { ["page"] = "/home" }); +SentrySdk.Metrics.EmitDistribution("api_latency", 187, MeasurementUnit.Duration.Millisecond, + new Dictionary { ["endpoint"] = "/api/orders" }); +``` + +## Verify Your Setup + +Let's test your setup and confirm that data reaches your Sentry project. + + + +### View Captured Data in Sentry + +Open your Sentry project to view the captured event. + +## Samples + +- A [worker service](https://github.com/getsentry/sentry-dotnet/tree/main/samples/Sentry.Samples.GenericHost) that calls `UseSentry` and reads its options from `appsettings.json`. (**C#**) +- For [more samples](https://github.com/getsentry/sentry-dotnet-samples) of the .NET SDKs. + +## Next Steps + +At this point, you should have integrated Sentry into your generic host app. Here's what to explore next: + +- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup +- Learn how to manually capture errors +- Explore Tracing +- See all configuration options diff --git a/docs/platforms/dotnet/guides/extensions-logging/index.mdx b/docs/platforms/dotnet/guides/extensions-logging/index.mdx index 058be82f62cc9..570ecd4803f57 100644 --- a/docs/platforms/dotnet/guides/extensions-logging/index.mdx +++ b/docs/platforms/dotnet/guides/extensions-logging/index.mdx @@ -20,7 +20,7 @@ The default value to report a log entry as an event to Sentry is `Error`. This means that out of the box, any `LogError` call will create an `Event` which will include breadcrumbs for all prior log messages of level `Information`, `Warning`, `Error` and `Critical`. -Additionally, when enabled, log messages are sent to Sentry as [Structured Logs](logs/). Filtering to control the minimum log level to capture should be done [via `Microsoft.Extensions.Logging` configuration](https://learn.microsoft.com/dotnet/core/extensions/logging/overview?tabs=command-line#how-filtering-rules-are-applied). +Log messages are also sent to Sentry as [Structured Logs](logs/). Filtering to control the minimum log level to capture should be done [via `Microsoft.Extensions.Logging` configuration](https://learn.microsoft.com/dotnet/core/extensions/logging/overview?tabs=command-line#how-filtering-rules-are-applied). ## Install @@ -34,113 +34,106 @@ Install-Package Sentry.Extensions.Logging -Version {{@inject packages.version('s dotnet add package Sentry.Extensions.Logging -v {{@inject packages.version('sentry.dotnet.extensions.logging') }} ``` +On .NET Framework, also install the `Microsoft.Extensions.Logging` package. The examples on this page need it. + This package extends `Sentry` main SDK. That means that besides the logging related features, through this package you'll also get access to all API and features available in the main `Sentry` SDK. +Generic host apps install the `Sentry.Extensions.Hosting` package instead, which depends on this one. See the [Generic Host](/platforms/dotnet/guides/extensions-hosting/) guide. + -Messages logged from assemblies with the name starting with `Sentry` will not generate events. +The integration excludes the Sentry SDK's own logger categories to avoid capturing its diagnostic messages as events. Application categories that happen to start with `Sentry` aren't excluded solely because of that prefix. ## Configure -There are two ways to add this integration into your project. In both cases it means calling an extension method. The places where it's available are: - -- `ILoggingBuilder` -- `ILoggerFactory` +If your app uses one of these integrations, skip this setup. Call that integration's `UseSentry` instead, which initializes Sentry and adds this logging integration for you: -The `ILoggingBuilder` extension is useful when using a `WebHostBuilder` or a `HostBuilder`, also known as _Generic host_. This extension method is used by the ASP.NET Core integration under the hood to automatically. +- [Generic Host](/platforms/dotnet/guides/extensions-hosting/), for worker services, Windows services and console apps that call `Host.CreateApplicationBuilder` or `Host.CreateDefaultBuilder`. Before 7.0.0, these apps initialized Sentry with `builder.Logging.AddSentry(...)` from this page. +- [ASP.NET Core](/platforms/dotnet/guides/aspnetcore/) +- [MAUI](/platforms/dotnet/guides/maui/) -The extension to `ILoggerFactory` is a convenient way when only the `LoggerFactory` is being used, without any framework integration. +.NET Framework apps that call `Host.CreateApplicationBuilder()` can't use the Generic Host integration's `UseSentry`. See [.NET Framework](/platforms/dotnet/guides/extensions-hosting/#net-framework) in the Generic Host guide. -In both cases the method call is: +Apps without a host initialize Sentry with `SentrySdk.Init`, then add the integration with `AddSentry()`: -**AddSentry()** +```csharp {tabTitle:LoggerFactory} +using Microsoft.Extensions.Logging; -### Example configuration - -#### Through `ILoggingBuilder` +using var sentry = SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; +}); -```csharp -public static Task Main() - => new HostBuilder() - .ConfigureHostConfiguration(c => - { - c.SetBasePath(Directory.GetCurrentDirectory()); - c.AddJsonFile("appsettings.json", optional: false); - }) - .ConfigureLogging((c, l) => - { - l.AddConfiguration(c.Configuration); - // Adding Sentry integration to Microsoft.Extensions.Logging - l.AddSentry(); - }) - .Build(); +using var loggerFactory = LoggerFactory.Create(builder => builder.AddSentry()); +var logger = loggerFactory.CreateLogger(); ``` -In this example, a _generic host_ is being built and the MEL integration with Sentry added through `ConfigureLogging`. The example also demonstrates how to bind the `appsettings.json` configuration to make the values available to the Sentry integration. - -With this approach, options like `Dsn`, `SendDefaultPii`, `MinimumBreadcrumbLevel`, to name a few, can be set in `appsettings.json`. +```csharp {tabTitle:ServiceCollection} +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; -Example using `appsettings.json`: +using var sentry = SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; +}); +var services = new ServiceCollection(); +services.AddLogging(builder => builder.AddSentry()); -```json -{ - "Logging": { - "LogLevel": { - "Default": "Debug", - "Microsoft": "Warning" - } - }, - "Sentry": { - "Dsn": "___PUBLIC_DSN___", - "SendDefaultPii": true, - "MinimumBreadcrumbLevel": "Debug", - "MinimumEventLevel": "Warning", - "MaxBreadcrumbs": 50 - } -} +using var provider = services.BuildServiceProvider(); +var logger = provider.GetRequiredService>(); ``` -Above we set the application wide minimum log level to `Debug` and we configure a minimum log level for Microsoft specific logs to `Warning`. Sentry specific settings are set under the `Sentry` property. Options are documented below. +Set other [SDK options](/platforms/dotnet/guides/extensions-logging/configuration/options/) in `SentrySdk.Init` too. Disposing the object it returns sends any pending events before your app exits. -#### Through `ILoggerFactory` +Every `ILogger` entry that passes your `Microsoft.Extensions.Logging` filters is also sent as a structured log. To send fewer, set `LogLevel` under `Logging:Sentry`, as shown in [Logging Configuration](#logging-configuration), or return `null` from `SetBeforeSendLog`. +`AddSentry()` doesn't register `IHub`, `ISentryClient` or `Func`. If your services inject them, register them with `HubAdapter.Instance`. Otherwise resolving those services fails with `Unable to resolve service for type 'Sentry.IHub'`: ```csharp -using (var loggerFactory = new LoggerFactory() - .AddConsole(LogLevel.Trace) - .AddSentry(o => o.Dsn = "___PUBLIC_DSN___")) -{ - var logger = loggerFactory.CreateLogger(); -} +using Sentry.Extensibility; + +services.AddSingleton(HubAdapter.Instance); +services.AddSingleton(HubAdapter.Instance); +services.AddSingleton>(() => HubAdapter.Instance); ``` -This approach doesn't include any of the framework's configuration system. Since the DSN is being provided via parameter, the SDK will be initialized. +You only need the lines for the types your services inject. -More settings can be passed via the callback configuring the `SentryOptions`. + -## Options and Initialization +Prior to version 7.0.0, `AddSentry` could also initialize the SDK itself, registered `IHub` and `ISentryClient`, and only sent log entries as structured logs when `EnableLogs` was `true`. On those versions, set the DSN in `AddSentry(options => ...)` instead of calling `SentrySdk.Init`. To upgrade, see Migrate from 6.x to 7.x. -In cases where `AddSentry` is called without arguments, it's worth noting that an overload exists where `SentryOptions` can be configured just like if `SentrySdk.Init` had been called. + - +### Logging Configuration -The SDK needs to be initialized only once. If the `DSN` is made available to this integration, by default it **will** initialize the SDK. If you do not wish to initialize the SDK via this configuration, set the `InitializeSdk` flag to **false**. Not providing a DSN or leaving it as an _empty string_ will disable the SDK. +If you add your configuration to the logging builder, for example with `builder.AddConfiguration(configuration.GetSection("Logging"))`, the integration reads its settings from the `Logging:Sentry` section: - +```json {filename:appsettings.json} +{ + "Logging": { + "Sentry": { + "LogLevel": { + "Default": "Information" + }, + "MinimumBreadcrumbLevel": "Debug", + "MinimumEventLevel": "Warning" + } + } +} +``` -For example: +`LogLevel` controls which entries are sent as [structured logs](logs/). `MinimumBreadcrumbLevel` and `MinimumEventLevel` are described under [Options](#options). -```csharp -using (var loggerFactory = new LoggerFactory() - .AddSentry(o => o.InitializeSdk = false)) -{ } -``` +The `Logging:Sentry` section only accepts these three keys. Any other key, such as `Dsn` or `EnableLogs`, makes the app fail at startup. Set SDK options in `SentrySdk.Init`. ### Options +Set these in `AddSentry(options => ...)`. You can also set the two levels in the `Logging:Sentry` configuration section. + #### MinimumBreadcrumbLevel A `LogLevel` which indicates the minimum level a log message has to be included as a breadcrumb. By default this value is `Information`. @@ -149,13 +142,22 @@ A `LogLevel` which indicates the minimum level a log message has to be included A `LogLevel` which indicates the minimum level a log message has to be sent to Sentry as an event. By default this value is `Error`. -#### InitializeSdk +#### Log Entry Filters + +Filters run before a log entry is processed. They get the entry's `Microsoft.Extensions.Logging` data, so you can drop the entry before it becomes a `Breadcrumb` or an `Event`. Return `true` to drop it: -Whether or not this integration should initialize the SDK. If you intend to call `SentrySdk.Init` yourself, you should set this flag to `false`. +```csharp +using Microsoft.Extensions.Logging; +using Sentry.Extensions.Logging; -#### Filters +using var loggerFactory = LoggerFactory.Create(builder => builder.AddSentry(options => +{ + options.AddLogEntryFilter((category, level, eventId, exception) => + level < LogLevel.Critical && exception is DivideByZeroException); +})); +``` -A list of filters which are invoked before processing log messages. This allows you to inspect the details of the log entry before they become a `Breadcrumb` or an `Event` with full access to the `Microsoft.Extensions.Logging` data. +With a host integration, call `AddLogEntryFilter` on the options you pass to `UseSentry` instead. @@ -163,11 +165,9 @@ These filters only apply to breadcrumbs and events. They don't control which log -#### TagFilters +### TagFilters -A list of filters which are invoked before processing any log message to filter out undesired tags. - -For example, to remove all tags starting with `PROC_`, add a tag filter to your `SentryOptions` when initializing the SDK. +`TagFilters` is an SDK option, so set it in `SentrySdk.Init`. It drops any tag set on the scope whose key contains one of its entries, including the tags this integration adds from `BeginScope` state. An entry can also be a `Regex`, such as `new Regex("^PROC_")` to match only keys that start with `PROC_`. For example, to drop tags whose key contains `PROC_`: ```csharp options.TagFilters.Add("PROC_"); @@ -175,14 +175,18 @@ options.TagFilters.Add("PROC_"); ## Verify -This snippet includes an intentional error, so you can test that everything is working as soon as you set it up. +After creating a logger with one of the configurations above, send an informational log and an error to verify both providers: + +```csharp +logger.LogInformation("Sentry logging verification"); +logger.LogError("Sentry error-event verification"); +``` - +Check **Logs** for the informational log and **Issues** for the error event. Run this code before disposing the logger factory or service provider. ## Samples - A [simple example](https://github.com/getsentry/sentry-dotnet/tree/main/samples/Sentry.Samples.ME.Logging) using simply the `LoggerFactory`. -- An [example](https://github.com/getsentry/sentry-dotnet/tree/main/samples/Sentry.Samples.GenericHost) using the _generic host_. ## Next Steps diff --git a/docs/platforms/dotnet/guides/google-cloud-functions/index.mdx b/docs/platforms/dotnet/guides/google-cloud-functions/index.mdx index 9b0f8af3ffd38..98cec74c19281 100644 --- a/docs/platforms/dotnet/guides/google-cloud-functions/index.mdx +++ b/docs/platforms/dotnet/guides/google-cloud-functions/index.mdx @@ -30,7 +30,7 @@ This package extends `Sentry.AspNetCore`, which in turn extends `Sentry`'s main -Messages logged from assemblies with the name starting with `Sentry` will not generate events. +The logging integration excludes the Sentry SDK's own logger categories to avoid capturing its diagnostic messages as events. @@ -104,10 +104,12 @@ using Microsoft.AspNetCore.Http; public class Function : IHttpFunction { + public Task HandleAsync(HttpContext context) => + context.Response.WriteAsync("Hello from Google Cloud Functions"); } ``` -Some of the settings require actual code. For those, like the `BeforeSend` callback, you will need to create a new class implementing the abstract class `FunctionsStartup` to set it up: +Some settings, such as the `BeforeSend` callback, require code. Keep the `SentryStartup` assembly registration above and add another `FunctionsStartup` registration for your custom configuration: ```csharp using Google.Cloud.Functions.Hosting; @@ -144,13 +146,13 @@ Much of the behavior of the Google cloud functions integration with Sentry can b When opting in to `SendDefaultPii`, the SDK will automatically read the user from the request by inspecting `HttpContext.User`. Default claim values like `NameIdentifier` for the _Id_ will be used. -If you wish to change the behavior of how to read the user from the request, you can register a new `IUserFactory` into the container: +To customize how Sentry reads the user from the request, implement `ISentryUserFactory` and register it in the container. Keep the `SentryStartup` registration when adding this startup class: ```csharp using Google.Cloud.Functions.Hosting; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; -using Sentry.AspNetCore; +using Sentry; [assembly: FunctionsStartup(typeof(UserFactoryStartup))] @@ -159,7 +161,7 @@ public class UserFactoryStartup : FunctionsStartup public override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services) { base.ConfigureServices(context, services); - services.AddSingleton(); + services.AddSingleton(); } } ``` @@ -191,7 +193,7 @@ Let's test your setup and confirm that data reaches your Sentry project. ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Next Steps diff --git a/docs/platforms/dotnet/guides/log4net/index.mdx b/docs/platforms/dotnet/guides/log4net/index.mdx index 99c61499a86b4..9fb998888317a 100644 --- a/docs/platforms/dotnet/guides/log4net/index.mdx +++ b/docs/platforms/dotnet/guides/log4net/index.mdx @@ -7,9 +7,9 @@ og_image: /og-images/platforms-dotnet-guides-log4net.gif Sentry provides an integration with log4net through the [Sentry.Log4Net NuGet package](https://www.nuget.org/packages/Sentry.Log4Net). -Without any code change, this package is able to initialize the Sentry SDK and capture events while including additional properties like `Exception` data and more. +The `SentryAppender` captures log events as Sentry events and breadcrumbs, including additional properties like `Exception` data and more. -Additionally, when enabled, log messages are sent to Sentry as [Structured Logs](logs/). +Log messages are also sent to Sentry as [Structured Logs](logs/). ## Install @@ -27,41 +27,121 @@ This package extends `Sentry` main SDK. That means besides the log4net `Appender ## Configure -Once the log4net integration package is installed in your project, you can modify your configuration file to add the appender. +Initialize Sentry first, with `SentrySdk.Init` or a host integration such as [ASP.NET Core](/platforms/dotnet/guides/aspnetcore/): + +```csharp +SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; +}); +``` + +Then add the appender to your log4net configuration. This can be done, for example, via the `app.config` for console and desktop apps or `web.config` in case of ASP.NET. ```xml {filename:app.config} - + + ``` - +Other [SDK options](/platforms/dotnet/guides/log4net/configuration/options/) can also be configured when calling `SentrySdk.Init`. + +The appender drops log events while Sentry isn't initialized. If a DSN can be found anyway, for example in the `SENTRY_DSN` environment variable, the appender also writes a warning to standard error the first time it drops an event. To fix it, initialize Sentry at startup as shown above. + +### Apps That Call UseSentry + + -Only a subset of the options are exposed via the log4net appender configuration. If you wish to access an [SDK option](/platforms/dotnet/configuration/options/) which is not listed below, you'll need to initialize the SDK via [SentrySdk.Init](/platforms/dotnet/) instead of doing it via this integration as described below. +### Capturing Startup Crashes - +`UseSentry` starts Sentry when the host is built or, in ASP.NET Core, when the app starts running. If the app crashes before then, the appender drops the crash. + +To send these crashes, also call `SentrySdk.Init` before you create the builder, and log the crash if startup fails: + +```csharp {filename:Program.cs} +using log4net; + +using var sentry = SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; +}); + +var logger = LogManager.GetLogger(typeof(Program)); + +try +{ + var builder = WebApplication.CreateBuilder(args); + builder.UseSentry(options => + { + options.Dsn = "___PUBLIC_DSN___"; + }); + + var app = builder.Build(); + app.Run(); +} +catch (Exception ex) +{ + logger.Fatal("Application terminated unexpectedly", ex); + throw; +} +finally +{ + LogManager.Shutdown(); +} +``` + +The two initializations don't share anything: + +- `SentrySdk.Init` runs before the app reads `appsettings.json`, so set its DSN in code or with the `SENTRY_DSN` environment variable. +- `UseSentry` doesn't reuse those options. Give it a DSN as well, in its callback or the `Sentry` section. +- Once `UseSentry` starts Sentry, it replaces the first initialization. Crashes before then are sent with the first initialization's options, such as its release and environment. Breadcrumbs logged before then aren't carried over. +- Crashes after then, such as a port that's already in use, are sent by `UseSentry`. `logger.Fatal` doesn't send them a second time. ### SendIdentity In the example above, the `SendIdentity` flag was switched on. The SDK then will take the log4net `Identity` value and report to Sentry as the user's id. -### DSN +## Verify -Also in the example above, you can find the DSN being set. That will instruct the `SentryAppender` to initialize the SDK. +Ensure log4net loads your configuration and the appender is referenced by a logger. For example, add this inside your `` element alongside the appender: -This is only one of the ways to initialize the SDK. If you wish to configure the SDK programmatically, you could **leave the DSN out** from the appender configuration section. The SDK needs to be initialized only **once** and since other integrations (like ASP.NET) are also able to initialize the SDK, you only need to pass the DSN to one of these integrations. -One common case to not add the DSN to the XML configuration file (which would initialize it via the log4net integration) is to have full access to the [SDK option](/platforms/dotnet/guides/log4net/configuration/options/). +```xml {filename:app.config} + + + + +``` -## Verify +After initializing Sentry, run this code to verify error capture: + +```csharp +using System; +using log4net; +using log4net.Config; +using Sentry; + +XmlConfigurator.Configure(); +var logger = LogManager.GetLogger("SentryVerification"); -This snippet includes an intentional error, so you can test that everything is working as soon as you set it up. +try +{ + throw new InvalidOperationException("Sentry log4net verification"); +} +catch (Exception exception) +{ + logger.Error("Sentry error-event verification", exception); +} + +SentrySdk.FlushAsync().GetAwaiter().GetResult(); +``` - +Check **Issues** for the error event and **Logs** for the log entry. ## Sample diff --git a/docs/platforms/dotnet/guides/maui/index.mdx b/docs/platforms/dotnet/guides/maui/index.mdx index 1688daecfafc0..3a071e18b50b7 100644 --- a/docs/platforms/dotnet/guides/maui/index.mdx +++ b/docs/platforms/dotnet/guides/maui/index.mdx @@ -12,12 +12,31 @@ Sentry has an integration for the [.NET Multi-platform App UI (MAUI)](https://do - All the features of our main [.NET SDK](/platforms/dotnet/), for your managed code - Native crash reporting for Android, leveraging our [Android SDK](/platforms/android/) - Native crash reporting for iOS and Mac Catalyst, leveraging our [Cocoa SDK for iOS](/platforms/apple/guides/ios/) -- Managed crash reporting (unhandled exceptions), on all MAUI platforms (iOS, Android, Windows, Mac Catalyst, and Tizen) +- Managed crash reporting (unhandled exceptions), on all MAUI platforms (iOS, Android, Windows, and Mac Catalyst) - Line numbers for your .NET stack traces when PDBs are uploaded to Sentry - Automatic breadcrumbs for MAUI app lifecycle and UI events - Detailed device and runtime information passed on every event - Automatic session tracking enabled, to support [release health](/product/releases/) +## Supported Versions + +`Sentry.Maui` supports .NET 10 and .NET 11. Set `SupportedOSPlatformVersion` in your project file to at least these platform versions: + +| Platform | .NET 10 | .NET 11 | +| ----------------- | --------------------------- | --------------------------- | +| Android API level | 21 | 24 | +| iOS | 15.0 | 15.0 | +| Mac Catalyst | 15.0 | 17.0 | +| Windows | 10.0.17763.0 (version 1809) | 10.0.17763.0 (version 1809) | + +To build for iOS and Mac Catalyst, use the Xcode version that your .NET iOS and Mac Catalyst workloads require. The [.NET for iOS and Mac Catalyst release notes](https://github.com/dotnet/macios/releases) list it for each release. + + + +Version 6.x supports .NET 9 and .NET 10. See Supported .NET Versions and Platforms in the migration guide. + + + ## Install Add the Sentry dependency to your .NET MAUI application: @@ -79,7 +98,7 @@ public static MauiApp CreateMauiApp() options.AttachScreenshot = true; // Other Sentry options can be set here. - }) + }); // ... the remainder of your MAUI app setup @@ -176,7 +195,7 @@ Let's test your setup and confirm that data reaches your Sentry project. ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Next Steps diff --git a/docs/platforms/dotnet/guides/nlog/configuration/advanced-configuration-example.mdx b/docs/platforms/dotnet/guides/nlog/configuration/advanced-configuration-example.mdx index 4d0fe3d543278..197b3eae432d3 100644 --- a/docs/platforms/dotnet/guides/nlog/configuration/advanced-configuration-example.mdx +++ b/docs/platforms/dotnet/guides/nlog/configuration/advanced-configuration-example.mdx @@ -10,7 +10,32 @@ For more information on how to dynamically set event data via `NLog.config`, see -The SDK can be configured via `NLog.config` XML file: +Call `SentrySdk.Init` to initialize the SDK first. SDK options, such as the environment and release, go here: + +```csharp +SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; + options.Environment = "Development"; + options.Release = "my-project-name@2.3.12"; + options.AttachStacktrace = true; + options.SendDefaultPii = true; // Send Personal Identifiable information like the username of the user logged in to the device + options.ShutdownTimeout = TimeSpan.FromSeconds(5); +}); +``` + +```fsharp +SentrySdk.Init(fun options -> + options.Dsn <- "___PUBLIC_DSN___" + options.Environment <- "Development" + options.Release <- "my-project-name@2.3.12" + options.AttachStacktrace <- true + options.SendDefaultPii <- true // Send Personal Identifiable information like the username of the user logged in to the device + options.ShutdownTimeout <- TimeSpan.FromSeconds 5.0) +|> ignore +``` + +Then configure the Sentry target in an `NLog.config` XML file: ```xml {tabTitle:NLog.config} @@ -26,28 +51,15 @@ The SDK can be configured via `NLog.config` XML file: - - - - - true - + minimumEventLevel="Error" + minimumLogLevel="Info"> @@ -77,10 +89,9 @@ The SDK can be configured via `NLog.config` XML file: ``` -Or the SDK can be configured via code: +Or configure the target in code: ```csharp -// Other overloads exist, for example, configure the SDK with only the DSN or no parameters at all. LogManager.Configuration.AddSentry(o => { o.Layout = "${message}"; @@ -88,16 +99,9 @@ LogManager.Configuration.AddSentry(o => o.MinimumBreadcrumbLevel = LogLevel.Debug; // Debug and higher are stored as breadcrumbs (default is Info) o.MinimumEventLevel = LogLevel.Error; // Error and higher is sent as event (default is Error) - - // If DSN is not set, the SDK will look for an environment variable called SENTRY_DSN. If - // nothing is found, SDK is disabled. - o.Dsn = DsnSample; - - o.AttachStacktrace = true; - o.SendDefaultPii = true; // Send Personal Identifiable information like the username of the user logged in to the device + o.MinimumLogLevel = LogLevel.Info; // Info and higher are sent as logs (default is Info) o.IncludeEventDataOnBreadcrumbs = true; // Optionally include event properties with breadcrumbs - o.ShutdownTimeoutSeconds = 5; //Optionally specify user properties via NLog (here using MappedDiagnosticsLogicalContext as an example) o.User = new SentryNLogUser @@ -119,7 +123,6 @@ LogManager.Configuration.AddSentry(o => ``` ```fsharp -// Other overloads exist, for example, configure the SDK with only the DSN or no parameters at all. LogManager.Configuration.AddSentry( fun o -> o.Layout <- "${message}" @@ -127,16 +130,9 @@ LogManager.Configuration.AddSentry( o.MinimumBreadcrumbLevel <- LogLevel.Debug // Debug and higher are stored as breadcrumbs (default is Info) o.MinimumEventLevel <- LogLevel.Error // Error and higher is sent as event (default is Error) - - // If DSN is not set, the SDK will look for an environment variable called SENTRY_DSN. If - // nothing is found, SDK is disabled. - o.Dsn <- DsnSample - - o.AttachStacktrace <- true - o.SendDefaultPii <- true // Send Personal Identifiable information like the username of the user logged in to the device + o.MinimumLogLevel <- LogLevel.Info // Info and higher are sent as logs (default is Info) o.IncludeEventDataOnBreadcrumbs <- true // Optionally include event properties with breadcrumbs - o.ShutdownTimeoutSeconds <- 5 //Optionally specify user properties via NLog (here using MappedDiagnosticsLogicalContext as an example) o.User <- diff --git a/docs/platforms/dotnet/guides/nlog/index.mdx b/docs/platforms/dotnet/guides/nlog/index.mdx index c597b48a3b510..b0ff3130c8402 100644 --- a/docs/platforms/dotnet/guides/nlog/index.mdx +++ b/docs/platforms/dotnet/guides/nlog/index.mdx @@ -18,9 +18,9 @@ By default, Sentry will keep any message with log level `Info` or higher as a `B The default value to report a log entry as an event to Sentry is `Error`. -This means that out of the box, any `Error` call will create an `Event` which will include all log messages of level `Info`, `Warn` and also `Error` and `Critical`. +This means that out of the box, any `Error` call will create an `Event` which will include all log messages of level `Info`, `Warn`, `Error`, and `Fatal` stored as breadcrumbs. -Additionally, when enabled, log messages are sent to Sentry as [Structured Logs](logs/). +Log messages at `Info` or higher are also sent to Sentry as [Structured Logs](logs/). Set [`MinimumLogLevel`](#minimumloglevel) to change that level. ## Install @@ -36,12 +36,6 @@ dotnet add package Sentry.NLog -v {{@inject packages.version('sentry.dotnet.nlog This package extends `Sentry` main SDK. That means that besides the logging related features, through this package you'll also get access to all API and features available in the main `Sentry` SDK. - - -Messages logged from assemblies with the name starting with `Sentry` will not generate events. - - - ## Configure @@ -50,55 +44,45 @@ For more information on how to dynamically set event data via `NLog.config`, see -You can configure the Sentry NLog target via code as follows: +Initialize Sentry first, with `SentrySdk.Init` or a host integration such as [ASP.NET Core](/platforms/dotnet/guides/aspnetcore/), then add the target. You can add it in code: ```csharp -LogManager.Configuration = new LoggingConfiguration(); -LogManager.Configuration - .AddSentry(options => - { - // Optionally specify a separate format for message - options.Layout = "${message}"; - // Optionally specify a separate format for breadcrumbs - options.BreadcrumbLayout = "${logger}: ${message}"; - - // Debug and higher are stored as breadcrumbs (default is Info) - options.MinimumBreadcrumbLevel = LogLevel.Debug; - // Error and higher is sent as event (default is Error) - options.MinimumEventLevel = LogLevel.Error; - - // Send the logger name as a tag - options.AddTag("logger", "${logger}"); - - // All Sentry Options are accessible here. - }); +using NLog; +using NLog.Config; + +SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; +}); + +var config = new LoggingConfiguration(); +config.AddSentry(options => +{ + // Optionally specify a separate format for message + options.Layout = "${message}"; + // Optionally specify a separate format for breadcrumbs + options.BreadcrumbLayout = "${logger}: ${message}"; + + // Debug and higher are stored as breadcrumbs (default is Info) + options.MinimumBreadcrumbLevel = LogLevel.Debug; + // Error and higher is sent as event (default is Error) + options.MinimumEventLevel = LogLevel.Error; + // Info and higher are sent as logs (default is Info) + options.MinimumLogLevel = LogLevel.Info; + + // Send the logger name as a tag + options.AddTag("logger", "${logger}"); +}); +LogManager.Configuration = config; ``` -It's also possible to initialize the SDK through the NLog integration (as opposed to using `SentrySdk.Init`). -This is useful when NLog is the only integration being used in your application. To initialize the Sentry SDK through the NLog integration, provide it with the DSN: - - -```csharp -LogManager.Configuration = new LoggingConfiguration(); -LogManager.Configuration - .AddSentry(o => - { - // The NLog integration will initialize the SDK if DSN is set: - o.Dsn = "___PUBLIC_DSN___"; - }); -``` - - - -The SDK needs to be initialized only once. If a `DSN` is made available to this integration, by default it **will** initialize the SDK. If you do not wish to initialize the SDK via this integration, set the `InitializeSdk` flag to **false**. Not providing a DSN or leaving it as `null` instructs the integration not to initialize the SDK and unless another integration initializes it or you call `SentrySdk.Init`, the SDK will stay disabled. - - +The target drops log events while Sentry isn't initialized. If a DSN can be found anyway, for example in the `SENTRY_DSN` environment variable, the target also writes a warning to standard error the first time it drops an event. To fix it, initialize Sentry at startup as shown above. ### Minimum log level -Two log levels are used to configure this integration (see options below). One will configure the lowest level required for a log message to become an event (`MinimumEventLevel`) sent to Sentry. The other option (`MinimumBreadcrumbLevel`) configures the lowest level a message has to be to become a breadcrumb. Breadcrumbs are kept in memory (by default the last 100 records) and are sent with events. For example, by default, if you log 100 entries with `logger.Info` or `logger.Warn`, no event is sent to Sentry. If you then log with `logger.Error`, an event is sent to Sentry which includes those 100 `Info` or `Warn` messages. For this to work, `SentryTarget` needs to receive **all** log entries in order to decide what to keep as breadcrumb or sent as event. Make sure to set the `NLog` `LogLevel` configuration to a value lower than what you set for the `MinimumBreadcrumbLevel` and `MinimumEventLevel` to make sure `SentryTarget` receives these log messages. +Three log levels configure this integration. See [Options](#options) below. `MinimumEventLevel` is the lowest level for a log message to become an event sent to Sentry. `MinimumBreadcrumbLevel` is the lowest level for a message to become a breadcrumb. `MinimumLogLevel` is the lowest level for a message to be sent as a structured log. Breadcrumbs are kept in memory, by default the last 100 records, and are sent with events. For example, by default, if you log 100 entries with `logger.Info` or `logger.Warn`, no event is sent to Sentry. If you then log with `logger.Error`, an event is sent to Sentry which includes those 100 `Info` or `Warn` messages. For this to work, `SentryTarget` needs to receive **all** log entries in order to decide what to keep as breadcrumb or sent as event. `AddSentry` adds a rule that passes the target every entry at the lowest of the three levels or higher. If you write the rule yourself, for example in `NLog.config`, make sure its minimum level isn't higher than `MinimumBreadcrumbLevel`, `MinimumEventLevel` or `MinimumLogLevel`, so `SentryTarget` receives these log messages. -The SDK can also be configured via `NLog.config` XML file: +The target can also be configured in an `NLog.config` XML file: ```xml {tabTitle:NLog.config} @@ -112,23 +96,12 @@ The SDK can also be configured via `NLog.config` XML file: - - - - - true - + minimumEventLevel="Error" + minimumLogLevel="Info" + includeEventDataOnBreadcrumbs="true"> @@ -144,6 +117,61 @@ The SDK can also be configured via `NLog.config` XML file: ``` +### Apps That Call UseSentry + + + +### Capturing Startup Crashes + +`UseSentry` starts Sentry when the host is built or, in ASP.NET Core, when the app starts running. If the app crashes before then, for example while it reads configuration or registers services, the crash isn't sent. + +To send these crashes, also call `SentrySdk.Init` before you create the builder, and log the crash if startup fails: + +```csharp {filename:Program.cs} +using NLog; +using NLog.Config; +using NLog.Extensions.Logging; + +using var sentry = SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; +}); + +var config = new LoggingConfiguration(); +config.AddSentry(); +LogManager.Configuration = config; +var logger = LogManager.GetCurrentClassLogger(); + +try +{ + var builder = WebApplication.CreateBuilder(args); + builder.Logging.AddNLog(new NLogProviderOptions { ReplaceLoggerFactory = true }); + builder.UseSentry(options => + { + options.Dsn = "___PUBLIC_DSN___"; + }); + + var app = builder.Build(); + app.Run(); +} +catch (Exception ex) +{ + logger.Fatal(ex, "Application terminated unexpectedly"); + throw; +} +finally +{ + LogManager.Shutdown(); +} +``` + +The two initializations don't share anything: + +- `SentrySdk.Init` runs before the app reads `appsettings.json`, so set its DSN in code or with the `SENTRY_DSN` environment variable. +- `UseSentry` doesn't reuse those options. Give it a DSN as well, in its callback or the `Sentry` section. +- Once `UseSentry` starts Sentry, it replaces the first initialization. Crashes before then are sent with the first initialization's options, such as its release and environment. Breadcrumbs logged before then aren't carried over. +- Crashes after then, such as a port that's already in use, are sent by `UseSentry`. `logger.Fatal` doesn't send them a second time. + ### Options #### MinimumBreadcrumbLevel @@ -154,9 +182,9 @@ A `LogLevel` that indicates the minimum level a log message needs to be in order A `LogLevel` which indicates the minimum level a log message has to be sent to Sentry as an event. By default this value is `Error`. -#### InitializeSdk +#### MinimumLogLevel -Whether or not this integration should initialize the SDK. If you intend to call `SentrySdk.Init` yourself you should set this flag to `false`. +A `LogLevel` which indicates the minimum level a log message needs to be sent to Sentry as a structured log. By default this value is `Info`. Set it to `Off` to send no logs. #### IgnoreEventsWithNoException @@ -202,13 +230,21 @@ You can provide a `user` entry matching the following example user. See [Identif ## Verify -This snippet includes an intentional error, so you can test that everything is working as soon as you set it up. +After configuring NLog, send an informational log and an error: + +```csharp +var logger = LogManager.GetCurrentClassLogger(); +logger.Info("Sentry logging verification"); +logger.Error("Sentry error-event verification"); +LogManager.Flush(); +``` - +The informational message appears in **Logs**. The error message also creates an event in **Issues**. Call `LogManager.Shutdown()` when your application exits to dispose the target and flush pending data. ## Samples - A [simple example](https://github.com/getsentry/sentry-dotnet/tree/main/samples/Sentry.Samples.NLog). +- An [example with ASP.NET Core](https://github.com/getsentry/sentry-dotnet/tree/main/samples/Sentry.Samples.AspNetCore.NLog). - Example of [advanced configuration](configuration/advanced-configuration-example/) ## Next Steps diff --git a/docs/platforms/dotnet/guides/serilog/index.mdx b/docs/platforms/dotnet/guides/serilog/index.mdx index be1d4e29a9ed2..4416969cd2da9 100644 --- a/docs/platforms/dotnet/guides/serilog/index.mdx +++ b/docs/platforms/dotnet/guides/serilog/index.mdx @@ -18,9 +18,9 @@ By default, any message with log level `Information` or higher will be kept as a The default value to report a log entry as an event to Sentry is `Error`. -This means that out of the box, any `LogError` call will create an `Event` which will include breadcrumbs for all prior log messages of level `Information`, `Warning`, `Error` and `Critical`. +This means that out of the box, any `Log.Error` call will create an `Event` which will include breadcrumbs for prior log messages of level `Information`, `Warning`, `Error`, and `Fatal`. -Additionally, when enabled, log messages are sent to Sentry as [Structured Logs](logs/). You can control which logs are captured using the [Serilog MinimumLogLevel](https://github.com/serilog/serilog/wiki/Configuration-Basics#minimum-level). +Log messages are also sent to Sentry as [Structured Logs](logs/). You can control which logs are captured using the [Serilog MinimumLogLevel](https://github.com/serilog/serilog/wiki/Configuration-Basics#minimum-level). ## Install @@ -38,16 +38,28 @@ This package extends `Sentry` main SDK. That means that besides the logging rela -Messages logged from assemblies with the name starting with `Sentry` will not generate events. +The integration excludes the Sentry SDK's own logger categories to avoid capturing its diagnostic messages as events. Application categories that happen to start with `Sentry` aren't excluded solely because of that prefix. ## Configure -You can configure the Sentry Serilog sink as follows: +Initialize Sentry first, with `SentrySdk.Init` or a host integration such as [ASP.NET Core](/platforms/dotnet/guides/aspnetcore/), then add the sink: ```csharp +using Sentry.Serilog; +using Serilog; +using Serilog.Events; + +using var sentry = SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; + // Adds properties from the Serilog LogContext to Sentry events + options.UseSerilog(); +}); + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Debug() .WriteTo.Sentry(o => { // Debug and higher are stored as breadcrumbs (default is Information) @@ -58,6 +70,8 @@ Log.Logger = new LoggerConfiguration() .CreateLogger(); ``` +You can also configure the sink in `appsettings.json`: + ```json {filename:appsettings.json} { "Serilog": { @@ -78,36 +92,68 @@ Log.Logger = new LoggerConfiguration() } ``` -It's also possible to initialize the SDK through the Serilog integration. This is useful when the Serilog is the only integration being used in your application. To initialize the Sentry SDK through the Serilog integration, provide it with the DSN: +The sink drops log events while Sentry isn't initialized. If a DSN can be found anyway, for example in the `SENTRY_DSN` environment variable, the sink also writes a warning to standard error the first time it drops an event. To fix it, initialize Sentry at startup as shown above. +### Apps That Call UseSentry + + + +### Serilog Properties on Events + +`UseSerilog()` copies the properties in Serilog's `LogContext` onto Sentry events as tags. If you initialize Sentry through a host integration, call it on that integration's options, for example in `UseSentry(options => options.UseSerilog())`. + +If you don't call it, the sink does this for you once it's running, so only events captured before then miss the properties. + +### Capturing Startup Crashes + +`UseSentry` starts Sentry when the host is built or, in ASP.NET Core, when the app starts running. If the app crashes before then, for example while it reads configuration or registers services, the crash isn't sent. + +Apps that use Serilog's [two-stage initialization](https://github.com/serilog/serilog-aspnetcore#two-stage-initialization) log these crashes with a bootstrap logger. To send them to Sentry too, also call `SentrySdk.Init` before you create the builder: + +```csharp {filename:Program.cs} +using Sentry.Serilog; +using Serilog; + +using var sentry = SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; + options.UseSerilog(); +}); -```csharp Log.Logger = new LoggerConfiguration() - .WriteTo.Sentry(o => o.Dsn = "___PUBLIC_DSN___") - .CreateLogger(); -``` + .WriteTo.Sentry() + .CreateBootstrapLogger(); -```json {filename:appsettings.json} +try { - "Serilog": { - "Using": [ "Sentry.Serilog" ], - "WriteTo": [ - { - "Name": "Sentry", - "Args": { - "dsn": "___PUBLIC_DSN___" - } - } - ] - } + var builder = WebApplication.CreateBuilder(args); + builder.Services.AddSerilog(config => config.WriteTo.Sentry()); + builder.UseSentry(options => + { + options.Dsn = "___PUBLIC_DSN___"; + options.UseSerilog(); + }); + + var app = builder.Build(); + app.Run(); +} +catch (Exception ex) +{ + Log.Fatal(ex, "Application terminated unexpectedly"); + throw; +} +finally +{ + Log.CloseAndFlush(); } ``` - +The two initializations don't share anything: -The SDK only needs to be initialized once. If a `DSN` is made available to this integration, by default it **will** initialize the SDK. If you do not wish to initialize the SDK via this integration, set the `InitializeSdk` flag to **false**. Not providing a DSN or leaving it as `null` instructs the integration not to initialize the SDK and unless another integration initializes it or you call `SentrySdk.Init`, the SDK will stay disabled. - - +- `SentrySdk.Init` runs before the app reads `appsettings.json`, so set its DSN in code or with the `SENTRY_DSN` environment variable. +- `UseSentry` doesn't reuse those options. Give it a DSN as well, in its callback or the `Sentry` section, and call `UseSerilog()` again. +- Once `UseSentry` starts Sentry, it replaces the first initialization. Crashes before then are sent with the first initialization's options, such as its release and environment. Breadcrumbs logged before then aren't carried over. +- Crashes after then, such as a port that's already in use, are sent by `UseSentry`. `Log.Fatal` doesn't send them a second time. ### Options @@ -119,10 +165,6 @@ A `LogLevel` which indicates the minimum level a log message has to be included A `LogLevel` which indicates the minimum level a log message has to be sent to Sentry as an event. By default this value is `Error`. -#### InitializeSdk - -Whether or not this integration should initialize the SDK. If you intend to call `SentrySdk.Init` yourself you should set this flag to `false`. - #### RestrictedToMinimumLevel `MinimumBreadcrumbLevel` and `MinimumEventLevel` determine what the sink does with a log event, but every log event the logger captures still reaches the sink. If your logger's minimum level is verbose — for example, because another sink writes debug logs to a file — you can use Serilog's [per-sink minimum level](https://github.com/serilog/serilog/wiki/Configuration-Basics#overriding-per-sink) to stop lower-level log events from reaching Sentry entirely. @@ -141,9 +183,14 @@ An optional `LoggingLevelSwitch` that allows the sink's minimum level to be chan ## Verify -This snippet includes an intentional error, so you can test that everything is working as soon as you set it up. +After configuring Serilog, send an informational log and an error: + +```csharp +Log.Information("Sentry logging verification"); +Log.Error("Sentry error-event verification"); +``` - +The informational message appears in **Logs**. The error message also creates an event in **Issues**. In a short-lived app, dispose the object that `SentrySdk.Init` returns, or call `SentrySdk.Flush()`, before the app exits. ## Samples diff --git a/docs/platforms/dotnet/guides/winforms/index.mdx b/docs/platforms/dotnet/guides/winforms/index.mdx index 0c2e5915b5bd2..2113a6d6dd3cc 100644 --- a/docs/platforms/dotnet/guides/winforms/index.mdx +++ b/docs/platforms/dotnet/guides/winforms/index.mdx @@ -36,6 +36,7 @@ Don't need a feature? Remove its options from the snippet. ```csharp using System; using System.Windows.Forms; +using Sentry; namespace WindowsFormsApp1 { @@ -123,18 +124,21 @@ Module Program Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException) ' Configure the options for Sentry - Dim sentryOptions = New SentryOptions With - { - .Dsn = "___PUBLIC_DSN___", + Dim sentryOptions As New SentryOptions() + With sentryOptions + .Dsn = "___PUBLIC_DSN___" ' Adds request URL and headers, IP and name for users, etc. - .SendDefaultPii = True, + .SendDefaultPii = True + + ' Enable tracing; reduce this value in production. + .TracesSampleRate = 1.0 ' Enable Global Mode since this is a client app - .IsGlobalModeEnabled = True, + .IsGlobalModeEnabled = True ' any other options you need go here - } + End With ' Initialize Sentry and run the main form of the application Using SentrySdk.Init(sentryOptions) @@ -184,18 +188,21 @@ Namespace My Private Sub MyApplication_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup ' Configure the options for Sentry - Dim sentryOptions = New SentryOptions With - { - .Dsn = "___PUBLIC_DSN___", + Dim sentryOptions As New SentryOptions() + With sentryOptions + .Dsn = "___PUBLIC_DSN___" ' Adds request URL and headers, IP and name for users, etc. - .SendDefaultPii = True, + .SendDefaultPii = True + + ' Enable tracing; reduce this value in production. + .TracesSampleRate = 1.0 ' Enable Global Mode since this is a client app - .IsGlobalModeEnabled = True, + .IsGlobalModeEnabled = True ' any other options you need go here - } + End With ' Initialize Sentry _sentry = SentrySdk.Init(sentryOptions) @@ -257,9 +264,11 @@ Let's test your setup and confirm that data reaches your Sentry project. + + ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Resources diff --git a/docs/platforms/dotnet/guides/winui/index.mdx b/docs/platforms/dotnet/guides/winui/index.mdx index 16f84ae9841b2..86f90536fa229 100644 --- a/docs/platforms/dotnet/guides/winui/index.mdx +++ b/docs/platforms/dotnet/guides/winui/index.mdx @@ -83,6 +83,8 @@ Do not initialize the SDK in the `OnLaunched` event of the application or the `H ```csharp // Add these to your existing using statements. +using System.Security; +using Sentry; using Sentry.Protocol; using UnhandledExceptionEventArgs = Microsoft.UI.Xaml.UnhandledExceptionEventArgs; @@ -181,9 +183,11 @@ Let's test your setup and confirm that data reaches your Sentry project. + + ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Next Steps diff --git a/docs/platforms/dotnet/guides/wpf/index.mdx b/docs/platforms/dotnet/guides/wpf/index.mdx index f9a1444911649..2edb664cae488 100644 --- a/docs/platforms/dotnet/guides/wpf/index.mdx +++ b/docs/platforms/dotnet/guides/wpf/index.mdx @@ -28,6 +28,8 @@ Don't need a feature? Remove its options from the snippet. ```csharp using System.Windows; +using System.Windows.Threading; +using Sentry; public partial class App : Application { @@ -97,9 +99,11 @@ Let's test your setup and confirm that data reaches your Sentry project. + + ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Next Steps diff --git a/docs/platforms/dotnet/guides/xamarin/index.mdx b/docs/platforms/dotnet/guides/xamarin/index.mdx index 2e7800b29932c..03e78239148a7 100644 --- a/docs/platforms/dotnet/guides/xamarin/index.mdx +++ b/docs/platforms/dotnet/guides/xamarin/index.mdx @@ -8,7 +8,7 @@ Sentry's .NET SDK works with Xamarin applications through the [Sentry Xamarin Nu The SDK is compatible with the following versions or higher: -- Xamarin.Android 9.0 +- Xamarin.Android 11.0 - Xamarin.iOS 10.14 - Universal Windows Platform 10.0.16299 - Tizen 4.0 @@ -37,7 +37,8 @@ Don't need a feature? Remove its options from the snippet. ```csharp SentryXamarin.Init(options => { - options.AddXamarinFormsIntegration(); + // Add this only if you installed Sentry.Xamarin.Forms: + // options.AddXamarinFormsIntegration(); // Tells which project in Sentry to send events to: options.Dsn = "___PUBLIC_DSN___"; // When configuring for the first time, to see what the SDK is doing: diff --git a/docs/platforms/dotnet/index.mdx b/docs/platforms/dotnet/index.mdx index d6803feaf506d..5973764f5dd46 100644 --- a/docs/platforms/dotnet/index.mdx +++ b/docs/platforms/dotnet/index.mdx @@ -69,7 +69,7 @@ SentrySdk.Init(options => -Profiling for .NET is in Alpha and needs .NET 8 or later. On .NET Framework, `Sentry.Profiling` installs without a warning, but `AddProfilingIntegration()` doesn't compile. +Profiling for .NET is in Alpha. The `Sentry.Profiling` package requires .NET 8 or later and doesn't support .NET Framework. For iOS and Mac Catalyst, use the built-in profiler described in the [Apple guide](/platforms/dotnet/guides/apple/#configure). @@ -125,9 +125,11 @@ Let's test your setup and confirm that data reaches your Sentry project. + + ### View Captured Data in Sentry -Open your Sentry project to view the captured event. + ## Next Steps diff --git a/docs/platforms/godot/configuration/options.mdx b/docs/platforms/godot/configuration/options.mdx index 393107d70380c..5fe81105ac684 100644 --- a/docs/platforms/godot/configuration/options.mdx +++ b/docs/platforms/godot/configuration/options.mdx @@ -276,6 +276,12 @@ options.SetBeforeSendLog(log => ## Metrics Options + + +Configures automatic performance metrics. All automatic metrics are disabled by default and don't affect manually emitted metrics. Configure them in the Project Settings under **Sentry > Auto Metrics** or through `options.auto_metrics` during initialization. See Application Metrics Options for available settings and configuration examples. + + + **Deprecated:** This compatibility option is a no-op: it always returns `true`, and assigning it has no effect. It will be removed in version 3.0. @@ -470,6 +476,36 @@ Applies only when `android.enable_anr_detection` is enabled, and only to the V2 +## Web Options + +These options configure Web-specific behavior, such as tunneling. Set them programmatically through `options.web`, or in the **Project Settings** under **Sentry > Web**. See Web Tunneling for client and server setup. + + + +Sends uploads through a server on your game's origin to help avoid ad blockers. Your server must handle the tunnel route and forward envelopes to Sentry. The `dsn` is still required. + +When disabled, uploads go directly to Sentry and the other tunnel options are ignored. + + + + + +The tunnel path on your game's origin, such as `/events`. An empty string derives a stable path from the DSN. Your server must handle the same path. + + + + + +Prefixes the tunnel path, including an explicitly configured `web.tunnel_path`. For example, `/game` with `/events` sends uploads to `/game/events`. An empty string adds no prefix. + + + + + +Appends `/` to the tunnel path, including a DSN-derived path. Enable this when your server route requires a trailing slash. + + + ## Hooks These options can be used to hook the SDK in various ways to customize the reporting of events. diff --git a/docs/platforms/godot/configuration/tunneling.mdx b/docs/platforms/godot/configuration/tunneling.mdx new file mode 100644 index 0000000000000..cd169f67a82af --- /dev/null +++ b/docs/platforms/godot/configuration/tunneling.mdx @@ -0,0 +1,64 @@ +--- +title: Web Tunneling +sidebar_order: 102 +description: Send Sentry events from Godot Web exports through your own server to help avoid ad blockers. +--- + +Ad blockers can prevent your Web game from sending events to Sentry. Tunneling helps avoid this by sending uploads through a route on your game's origin, where your server forwards them to Sentry. + +Tunneling applies only to Web exports. Your server must provide an endpoint that forwards uploads to Sentry; enabling tunneling in Godot doesn't create that endpoint. + +## Configure the Game + +In **Project Settings > Sentry > Web**, enable tunneling and set the tunnel path to `/events`. Keep your Sentry DSN configured as usual. Leave **Base Path** empty and **Trailing Slash** disabled for this example. + +Alternatively, follow the programmatic initialization instructions and set the options in your initialization callback: + +```GDScript +SentrySDK.init(func(options: SentryOptions) -> void: + options.dsn = "___PUBLIC_DSN___" + options.web.enable_tunnel = true + options.web.tunnel_path = "/events" +) +``` + +This sends uploads to `/events` on the game's origin. For example, a game at `https://example.com/game/` sends uploads to `https://example.com/events`. + +## Configure the Server + +Your server must accept uploads at `/events` and forward them to Sentry. For a JavaScript server that uses Fetch API `Request` and `Response` objects, install `@sentry/core` and use its `handleTunnelRequest` helper: + +```javascript +import { handleTunnelRequest } from "@sentry/core"; + +export default { + async fetch(request) { + if ( + request.method === "POST" && + new URL(request.url).pathname === "/events" + ) { + return handleTunnelRequest({ + request, + allowedDsns: ["___PUBLIC_DSN___"], + }); + } + + return new Response("Not found", { status: 404 }); + }, +}; +``` + +Set `allowedDsns` to the same DSN configured in Godot. + +Preserve the incoming `Content-Length` header when creating the Fetch API request. The handler returns `411 Length required` when this header is missing. Configure request size limits in your server or hosting platform. + +The handler validates the envelope's DSN and forwards it to Sentry. + +## Verify the Setup + +To check that events reach Sentry through your tunnel: + +1. Export and run your game on Web. +2. Capture a test event with `SentrySDK.capture_message("Tunnel test")`. +3. In the browser's network panel, confirm that the upload goes to your tunnel route and receives a successful response. +4. Confirm that the event appears in Sentry. A successful HTTP response alone doesn't prove that your server forwarded the envelope. diff --git a/docs/platforms/godot/metrics/index.mdx b/docs/platforms/godot/metrics/index.mdx index d55b55792a0c8..0227d27af0a56 100644 --- a/docs/platforms/godot/metrics/index.mdx +++ b/docs/platforms/godot/metrics/index.mdx @@ -1,7 +1,7 @@ --- title: Set Up Metrics sidebar_title: Application Metrics -description: "Metrics let you to send, view, and query counters, gauges, and distributions from your Godot Engine game. Use these to track application health and drill down into related traces, logs, and errors." +description: "Metrics allow you to send, view, and query counters, gauges, and distributions from your Godot Engine game to track application health and drill down into related traces, logs, and errors." sidebar_order: 5700 new: true --- @@ -14,8 +14,131 @@ new: true +## Automatic Metrics + +Automatic metrics help you compare frame performance, rendering load, memory use, and multiplayer connectivity across devices and scenes. Automatic metrics are disabled by default and independent of metrics you send manually. + +Enable automatic metrics in the **Project Settings** under **Sentry** > **Auto Metrics**, or configure `options.auto_metrics` during programmatic initialization. See [Options](#options) for available settings. + +Collection pauses when the application loses focus or the operating system pauses it. Headless applications ignore focus changes but still respect OS pause. `SceneTree.paused` and `Engine.time_scale` don't affect collection. + +Automatic metrics include the following attributes when available, in addition to the [default attributes](#default-attributes) attached to every metric. These aren't added to manually emitted metrics. + +| Attribute | Description | +| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `gpu.name` | GPU model name; omitted in headless mode | +| `cpu.cores` | Logical CPU core count reported by Godot | +| `ram.gb` | Physical RAM reported by the OS, in GiB; unavailable on Web | +| `res.x`, `res.y` | Root viewport target width and height in pixels, before window stretching and after 3D scaling; omitted in headless mode | +| `scene` | Full resource path of the current scene, such as `res://levels/forest.tscn`; falls back to the scene node name if no resource path is available | + +Use these attributes to group performance data by hardware, resolution, or scene. + +### Frame Time and FPS + + + +Use frame metrics to track frame duration and frame rate across players' devices. + +| Metric | Type | Description | +| ---------------------- | ----------------- | ---------------------------------------------- | +| `game.perf.frame_time` | Distribution (ms) | Sampled elapsed time between process callbacks | +| `game.perf.fps` | Gauge | Engine-reported frames per second | + +The SDK randomly selects one frame from each collection interval and reports its frame time, including time spent waiting for VSync or frame limiting. Sampling may miss brief hitches. + +### Rendering + + + +Rendering metrics help identify scenes with high rendering load or video memory use. + +| Metric | Type | Description | +| ----------------------------------- | ------------- | --------------------------------------------------------------------------------- | +| `game.perf.render.draw_calls` | Gauge | Draw calls in the last rendered frame | +| `game.perf.render.primitives` | Gauge | Vertices or indices rendered in the last frame, including depth and shadow passes | +| `game.perf.render.video_mem_used` | Gauge (bytes) | Total video memory used, including texture, buffer, and other allocations | +| `game.perf.render.texture_mem_used` | Gauge (bytes) | Texture memory used | +| `game.perf.render.buffer_mem_used` | Gauge (bytes) | Render buffer memory used | + +### Memory + + + +Memory metrics help track process memory use and growth in object and node counts. Process memory usage is unavailable on Web; object and node counts are still collected. + +| Metric | Type | Description | +| ------------------------ | ------------- | ------------------------------------------- | +| `game.perf.used_memory` | Gauge (bytes) | RAM used by the game process | +| `game.perf.object_count` | Gauge | Instantiated objects, including nodes | +| `game.perf.node_count` | Gauge | Nodes in the scene tree, including its root | + +### Network + + + +Network metrics help diagnose multiplayer latency and traffic volume. Network metrics use only the default `SceneTree` multiplayer API; custom multiplayer APIs assigned to subtrees aren't monitored. Client, server, and mesh sessions are supported. No network metrics are emitted without an active multiplayer connection. + +Peer counts work across all transports. All other measurements require ENet. + +| Metric | Type | Description | +| --------------------------------- | ------------- | -------------------------------------------------------------------------- | +| `game.perf.net.num_peers` | Gauge | Connected remote peers, excluding this instance; server and mesh only | +| `game.perf.net.ping` | Gauge (ms) | Client round-trip time to the server | +| `game.perf.net.ping_peer_avg` | Gauge (ms) | Average peer round-trip time; server and mesh only | +| `game.perf.net.ping_peer_max` | Gauge (ms) | Highest peer round-trip time; server and mesh only | +| `game.perf.net.packet_loss_ratio` | Gauge (ratio) | ENet's estimated outgoing packet-loss ratio toward the server; client only | +| `game.perf.net.in_rate` | Gauge (bytes) | Bytes received per second; client and server only | +| `game.perf.net.out_rate` | Gauge (bytes) | Bytes sent per second; client and server only | +| `game.perf.net.in_packets` | Gauge | UDP datagrams received per second; client and server only | +| `game.perf.net.out_packets` | Gauge | UDP datagrams sent per second; client and server only | + +Ping includes Godot's network-processing delays, so it reflects latency experienced by the game rather than network delay alone. Traffic rates include ENet protocol traffic and retransmissions; packet rates count UDP datagrams, not RPCs or game messages. + + + Traffic collection resets ENet's shared byte and packet counters. Other code + reading and resetting those counters affects these measurements, and vice + versa. + + ## Options +Configure these properties on `options.auto_metrics`, or use the corresponding settings in the **Project Settings** under **Sentry > Auto Metrics**. Each interval applies only when the corresponding metrics are enabled. + +| Option | Default | Available Since | Description | +| -------------------------------- | ------- | --------------- | ----------------------------------------- | +| `enable_frame_metrics` | `false` | 2.4.0 | Collect frame time and FPS | +| `enable_rendering_metrics` | `false` | 2.4.0 | Collect rendering metrics | +| `enable_memory_metrics` | `false` | 2.4.0 | Collect memory, object, and node metrics | +| `enable_network_metrics` | `false` | 2.5.0 | Collect network metrics | +| `frame_metrics_interval_sec` | `1.0` | 2.4.0 | Frame collection interval, in seconds | +| `rendering_metrics_interval_sec` | `1.0` | 2.4.0 | Rendering collection interval, in seconds | +| `memory_metrics_interval_sec` | `60.0` | 2.4.0 | Memory collection interval, in seconds | +| `network_metrics_interval_sec` | `10.0` | 2.5.0 | Network collection interval, in seconds | + +For example, enable automatic metrics and adjust the memory interval during initialization: + +```GDScript {tabTitle:GDScript} {mdExpandTabs} +SentrySDK.init(func(options: SentryOptions) -> void: + options.auto_metrics.enable_frame_metrics = true + options.auto_metrics.enable_rendering_metrics = true + options.auto_metrics.enable_memory_metrics = true + options.auto_metrics.enable_network_metrics = true + options.auto_metrics.memory_metrics_interval_sec = 30.0 +) +``` + +```csharp {tabTitle:C#} +SentrySdk.Init(options => +{ + options.AutoMetrics.EnableFrameMetrics = true; + options.AutoMetrics.EnableRenderingMetrics = true; + options.AutoMetrics.EnableMemoryMetrics = true; + options.AutoMetrics.EnableNetworkMetrics = true; + options.AutoMetrics.MemoryMetricsIntervalSec = 30.0; +}); +``` + ## Default Attributes diff --git a/docs/platforms/java/common/configuration/options.mdx b/docs/platforms/java/common/configuration/options.mdx index d8885bdac0f43..97c4899548623 100644 --- a/docs/platforms/java/common/configuration/options.mdx +++ b/docs/platforms/java/common/configuration/options.mdx @@ -368,7 +368,7 @@ When set, a proxy can be configured that should be used for outbound requests. T -Controls how many seconds to wait before shutting down. The SDK sends events from a background queue. This queue is given a certain amount to drain pending events. The default is two seconds. Setting this value too low may cause problems for sending events from command line applications. Setting the value too high will cause the application to block for a long time for users experiencing network connectivity problems. +Controls how many milliseconds to wait before shutting down. The SDK sends events from a background queue. This queue is given a certain amount to drain pending events. The default is `2000` (two seconds). Setting this value too low may cause problems for sending events from command line applications. Setting the value too high will cause the application to block for a long time for users experiencing network connectivity problems. diff --git a/docs/platforms/java/common/integrations/quartz.mdx b/docs/platforms/java/common/integrations/quartz.mdx index 306141d22fb6b..288cf74d36409 100644 --- a/docs/platforms/java/common/integrations/quartz.mdx +++ b/docs/platforms/java/common/integrations/quartz.mdx @@ -79,3 +79,40 @@ Setting the monitor slug on the `Trigger` will override what is set on the `JobD Setting a global job listener using a `SchedulerFactoryBeanCustomizer` in Spring Boot, will override the listener set by Sentry. For Sentry to work properly, you need to add a new `SentryJobListener` instance to the global job listeners. + +## Monitor Config + +From Sentry Java SDK version `8.64.0`, `SentryJobListener` can send a monitor config derived from the job's trigger with each check-in, so Sentry creates the monitor (or updates its schedule) from your code. + +To turn it on for a job, set `SentryJobListener.SENTRY_UPSERT_MONITOR_CONFIG_KEY` to the string `"true"` in the job data map, next to the monitor slug. Like the slug, it also works in the trigger's job data map: + +```java +Map jobData = new HashMap<>(); +jobData.put(SentryJobListener.SENTRY_SLUG_KEY, ""); +jobData.put(SentryJobListener.SENTRY_UPSERT_MONITOR_CONFIG_KEY, "true"); + +JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean(); +jobDetailFactory.setJobDataAsMap(jobData); +``` + +The config is derived like this: + +- `CronTrigger`: the cron expression and the trigger's time zone. The seconds field must be a fixed number, and the year field, if set, must be `*`. If the seconds field isn't `0`, a check-in margin of 2 minutes is sent too, since the job checks in up to 59 seconds after the minute Sentry expects. This replaces a margin set in Sentry; set a larger `options.cron` default check-in margin to keep it. +- `SimpleTrigger` that repeats forever: the repeat interval, if it's a whole number of minutes. + +No monitor config is sent for: + +- Other trigger types +- Triggers with a `Calendar` +- Jobs with more than one trigger +- Cron expressions with syntax Sentry doesn't support, such as `15W`, `L-3`, or wrap-around ranges like `FRI-MON` +- Cron expressions with a step after a day or month name, such as `MON/2` (which Quartz runs every Monday) +- Time zones that aren't IANA time zone IDs, except whole-hour offsets such as `GMT+2`, which are sent as `Etc/GMT-2` + +For these, create the monitor in Sentry first. + + + +When you turn this on for a monitor you created in Sentry, it takes its schedule and time zone from the trigger. + + diff --git a/docs/platforms/javascript/common/configuration/integrations/fastify.mdx b/docs/platforms/javascript/common/configuration/integrations/fastify.mdx index f4ba56683c2d8..cf140e80b1134 100644 --- a/docs/platforms/javascript/common/configuration/integrations/fastify.mdx +++ b/docs/platforms/javascript/common/configuration/integrations/fastify.mdx @@ -19,6 +19,47 @@ Sentry.init({ }); ``` +## Options + +### `shouldHandleError` + +A function that decides whether an error is captured. By default, errors with a 5xx status code (and errors with a 2xx status code or lower) are captured, and errors with a 3xx or 4xx status code aren't. + +```typescript +declare function shouldHandleError( + error: Error, + request: FastifyRequest, + reply: FastifyReply +): boolean; +``` + +```javascript +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [ + Sentry.fastifyIntegration({ + shouldHandleError(error, request, reply) { + return reply.statusCode >= 500; + }, + }), + ], +}); +``` + +If you use TypeScript, cast the request and reply to get full type safety: + +```typescript +import type { FastifyRequest, FastifyReply } from "fastify"; + +Sentry.fastifyIntegration({ + shouldHandleError(error, minimalRequest, minimalReply) { + const request = minimalRequest as FastifyRequest; + const reply = minimalReply as FastifyReply; + return reply.statusCode >= 500; + }, +}); +``` + ## Supported Versions - `fastify`: `^3.21.0 || ^4.0.0` diff --git a/docs/platforms/javascript/common/configuration/integrations/servetunnel.mdx b/docs/platforms/javascript/common/configuration/integrations/servetunnel.mdx new file mode 100644 index 0000000000000..b4ecd1f4a5cf0 --- /dev/null +++ b/docs/platforms/javascript/common/configuration/integrations/servetunnel.mdx @@ -0,0 +1,68 @@ +--- +title: ServeTunnel +description: "Serves a tunnel on your server so Sentry browser SDK events reach Sentry through your own origin, past ad blockers." +supportedCategories: + - server +--- + + + +_Import name: `Sentry.serveTunnelIntegration`_ + +This integration serves the tunnel that the browser SDK uses when you set `tunnel: true`. The tunnel forwards the browser's events to Sentry, so ad blockers don't drop them. To set it up, see Tunneling. + + + +## Options + +Most apps don't need any of these options. + +### `allowedDsns` + +_Type: `string[]`_ + +DSNs to forward besides the server's own. Use this when the browser uses a different DSN than the server. The server's own DSN is always allowed. + +```javascript +Sentry.serveTunnelIntegration({ + allowedDsns: ["___PUBLIC_DSN___"], +}); +``` + +### `path` + +_Type: `string`_ + +A fixed tunnel path instead of the one derived from the DSN. The SDK doesn't add the base path it reads from your framework config, so include it in the path, or set `basePath` too. Set the same path in the browser, as described in Using a Fixed Path. + +### `basePath` + +_Type: `string`_ + +The path prefix your app is served under, for example `/docs`. The SDK reads it from your framework config, so you only need this option when it can't. Set the same value in the browser `tunnel` option. + +### `intercept` + +_Type: `boolean`_ +_Default: `true`_ + +Whether the SDK answers tunnel requests before they reach your app. Set it to `false` to answer them from your own code with `handleTunnelRequestIfMatched`, for example behind your own middleware. Tunnel requests still don't show up in your traces: + +```javascript +import express from "express"; +import * as Sentry from "@sentry/node"; + +const app = express(); + +app.use( + (req, res, next) => Sentry.handleTunnelRequestIfMatched(req, res) ?? next() +); +``` + +Add it before any middleware that reads the request body. + + + +On Vercel, the route that `withSentryConfig` adds at build time still answers tunnel requests. + + diff --git a/docs/platforms/javascript/common/configuration/options.mdx b/docs/platforms/javascript/common/configuration/options.mdx index 7ddb2380fce5a..5cecafc726546 100644 --- a/docs/platforms/javascript/common/configuration/options.mdx +++ b/docs/platforms/javascript/common/configuration/options.mdx @@ -83,14 +83,41 @@ Environments are case-sensitive. The environment name can't contain newlines, sp + + -Sets the URL that will be used to transport captured events. This can be used to work around ad-blockers or to have more granular control over events sent to Sentry. Adding your DSN is still required when using this option so necessary attributes can be set on the generated Sentry data. This option **requires the implementation** of a custom server endpoint. Learn more and find examples in [Dealing with Ad-Blockers](/platforms/javascript/troubleshooting/#dealing-with-ad-blockers). +Sets the URL that will be used to transport captured events. This can be used to work around ad-blockers or to have more granular control over events sent to Sentry. Adding your DSN is still required when using this option so necessary attributes can be set on the generated Sentry data. This option **requires the implementation** of a custom server endpoint. Learn more and find examples in Tunneling. + +The endpoint must forward only the request body to Sentry and accept only your own DSNs. Learn more in Setting Up the Tunnel Manually. + + + + + + + + + +Where the browser SDK sends captured events instead of the Sentry ingest URL. Use it to work around ad blockers or to control which events reach Sentry. The DSN is still required, so the SDK can initialize correctly and forward the Sentry ingest URL to the tunnel. + +The `tunnel` option can be set to the following values: + +- A string, a URL or a path, sends events to that endpoint. You serve the endpoint yourself, as described in Setting Up the Tunnel Manually. +- `true` sends events to the managed tunnel, a path on your own origin derived from the DSN. Your server needs to serve it, as described in Setting Up the Tunnel. +- An object works like `true`, with these options: + - `path`: a fixed tunnel path instead of the one derived from the DSN. The SDK doesn't add the base path your framework uses, so include it in the path, or set `basePath` too. + - `basePath`: the path prefix your app is served under, for example `/docs`. Most framework SDKs set it for you. + - `trailingSlash`: appends a trailing slash to the tunnel path, for servers that redirect paths without one. -The endpoint must forward only the request body to Sentry and accept only your own DSNs. Learn more in [Using the `tunnel` Option](/platforms/javascript/troubleshooting/#using-the-tunnel-option). +`true` and the object are available since version `11.13.0`. + +On the server, `tunnel` only takes a URL. It's where the server SDK sends its own events, and it's independent from `serveTunnelIntegration`. + + @@ -108,7 +135,7 @@ Set to `false` to opt out, for example, when using a custom `tunnel` or when run Controls which categories of data the SDK collects automatically. All fields are optional. - By default the SDK collects rich debugging context (including user identity, request/response bodies, and generative AI content) and scrubs values whose keys match the built-in sensitive denylist (`auth`, `token`, `password`, and similar). +By default the SDK collects rich debugging context (including user identity, request/response bodies, and generative AI content) and scrubs values whose keys match the built-in sensitive denylist (`auth`, `token`, `password`, and similar). @@ -299,21 +326,35 @@ The callback gets a second argument (called a "hint") which contains the origina - The JavaScript SDK uses a transport to send events to Sentry. - Transports will drop an event if it fails to send due to a lack of connection. + The JavaScript SDK uses a transport to send events to Sentry. Transports will + drop an event if it fails to send due to a lack of connection. In the browser, a `fetch`-based transport is used by default. - - - On the server, a `https`-based transport is used by default. - + + + On the server, a `https`-based transport is used by default. + - + A `fetch`-based transport is used by default. @@ -551,7 +592,8 @@ The `samplingContext` object passed to the function has the following properties - `name`: The name of the span as it was started. - `attributes`: The initial attributes of the span. - - `location`: The current page or worker URL, if available. Provided by the BrowserTracing integration. + - `location`: The current page or worker URL, if available. Provided by the + BrowserTracing integration. - `normalizedRequest`: Request information of the currently active HTTP @@ -605,7 +647,7 @@ The SDK skips storage operation spans for Durable Object keys whose names start Controls which bindings on `env` receive tracing data over [RPC calls](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/) to Durable Objects and other Workers. RPC has no headers, so the SDK appends the trace context as a trailing argument that an instrumented receiver strips again before your method runs. -String entries must match a binding name exactly, so `"DB"` matches `"DB"` but not `"MY_DB"`. Use a regular expression for pattern matching. +String entries must match a binding name exactly, so `"DB"` matches `"DB"` but not `"MY_DB"`. Use a regular expression for pattern matching. This option controls outgoing RPC trace propagation, which is disabled by default. Add bindings to enable it for those receivers. Sentry-instrumented receivers automatically continue incoming traces without configuring this option. @@ -617,6 +659,28 @@ Propagation over `stub.fetch()` and service binding `fetch()` uses HTTP headers, + + +Overrides whether Sentry treats a `fetch` response as streaming. Use this if your application streams responses, such as HTML rendered with streaming SSR, that Sentry doesn't detect automatically. + +Return `true` to keep the request span open until streaming completes, `false` to end it when the handler returns, or `undefined` to use automatic detection. + +```typescript {filename:instrument.server.ts} +import { defineCloudflareOptions } from "@sentry/cloudflare"; + +export default defineCloudflareOptions((env) => ({ + dsn: env.SENTRY_DSN, + isStreamingResponse: (response) => + response.headers.get("content-type")?.startsWith("text/html") + ? true + : undefined, +})); +``` + +The callback receives the response and request. It must be synchronous and must not read the response body. + + + @@ -860,7 +924,8 @@ Controls whether the SDK installs runtime hooks that instrument supported depend - On SDK versions below `10.71.0`, logs are opt-in. Set `enableLogs: true` in your `Sentry.init` to send them. + On SDK versions below `10.71.0`, logs are opt-in. Set `enableLogs: true` in + your `Sentry.init` to send them. @@ -872,8 +937,8 @@ This function is called with a log object, and can return a modified log object, ## Metrics Options - **Note:** For Electron, metric options apply to the process where these options - are set. + **Note:** For Electron, metric options apply to the process where these + options are set. diff --git a/docs/platforms/javascript/common/configuration/tunneling.mdx b/docs/platforms/javascript/common/configuration/tunneling.mdx new file mode 100644 index 0000000000000..4187caa8f3fd4 --- /dev/null +++ b/docs/platforms/javascript/common/configuration/tunneling.mdx @@ -0,0 +1,365 @@ +--- +title: Tunneling +sidebar_order: 35 +description: "Send browser SDK events to Sentry through your own server, so ad blockers don't drop them." +supportedCategories: + - browser + - server +--- + +Ad blockers often block requests to Sentry, so your events never arrive. A tunnel is an endpoint on your own origin that forwards events to Sentry, and ad blockers let requests to your own origin through. + +![Without a tunnel, ad blockers block requests to Sentry. With a tunnel, the browser sends them to your own origin, which forwards them to Sentry.](/img/tunnel-flow.svg) + +## Setting Up the Tunnel + + + +The browser sends its events to a path on your own origin derived from the DSN, for example `/qpo967`, and your server forwards them to Sentry. + +If your server doesn't run a Sentry JavaScript SDK, or you want the tunnel as a route in your app, [set up the tunnel manually](#setting-up-the-tunnel-manually) instead. + + + The tunnel only works while the server SDK is enabled. Without a DSN, or with + `enabled: false`, the browser's events are lost. + + + + +### Turn On the Tunnel in the Browser + +Set `tunnel: true` in your browser `Sentry.init`: + + + + + +If you use the `tunnelRoute` option, remove it from `withSentryConfig`. + + + + + +If you use the `tunnelRoute` option, remove it from `sentryTanstackStart`. + + + +### Add the Integration to Your Server + +Add `serveTunnelIntegration` to your server `Sentry.init`: + + + + + +Use the server that serves your app. The tunnel is on the same origin as your page. If a separate dev server like Vite serves your page locally, use a [fixed path](#using-a-fixed-path) and proxy it to your server. + + + + + +No additional setup is needed. The server SDK answers tunnel requests before they reach your app, so your routes and middleware don't need any changes. + + + + + +On Vercel, `withSentryConfig` adds a route for the tunnel at build time instead, and your middleware (`proxy.ts` or `middleware.ts`) runs before that route. If your middleware blocks requests, for example ones without a session, use a [fixed path](#using-a-fixed-path) and exclude it in the `matcher`: + +```typescript {filename:proxy.ts} +export const config = { + matcher: ["/((?!monitoring|_next/static|_next/image|favicon.ico).*)"], +}; +``` + + + + + +The SDK answers tunnel requests when you load it with `NODE_OPTIONS`, as described in the [setup guide](/platforms/javascript/guides/aws-lambda/install/npm/), or wrap your handler with `Sentry.wrapHandler`. If you only call `Sentry.init` inside your handler module, tunnel requests reach your handler instead. + + + + + +Call `Sentry.init` before you create your server, for example by preloading your instrument file with `bun --preload`. A server created before `init` doesn't answer tunnel requests. + + + + + +Call `Sentry.init` before you create your server, by importing your instrument file before anything else. A server created before `init` doesn't answer tunnel requests. + + + + + +If your Worker serves static assets with a single-page app fallback, Cloudflare answers the tunnel request before your Worker runs. Run your Worker first: + +```jsonc {filename:wrangler.jsonc} +{ + "assets": { + "not_found_handling": "single-page-application", + "run_worker_first": true, + }, +} +``` + + + + + +The SDK can't answer tunnel requests on Azure Functions, because each function only gets the requests for its own route. Set `intercept: false`, and answer them with `handleTunnelRequestIfMatched` in a function with a catch-all route: + +```javascript +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration({ intercept: false })], +}); +``` + + + +To check the tunnel, trigger an event and look in your browser's Network tab for a `POST` to a path on your own origin that returns `200`. + + + +### Using a Different DSN in the Browser + +The server answers one path per DSN it allows. If your browser uses a different DSN than your server, add it to `allowedDsns`: + + + +```javascript +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [ + Sentry.serveTunnelIntegration({ + allowedDsns: [""], + }), + ], +}); +``` + + + + + +```javascript +export default Sentry.withSentry( + (env) => ({ + dsn: "___PUBLIC_DSN___", + integrations: [ + Sentry.serveTunnelIntegration({ + allowedDsns: [""], + }), + ], + }), + { + async fetch(request, env, ctx) { + // Your app + }, + } +); +``` + + + +### Using a Fixed Path + +To serve the tunnel at a path you choose, set it on both sides: + + + +```javascript {tabTitle:Browser} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + tunnel: "/monitoring", +}); +``` + +```javascript {tabTitle:Server} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration({ path: "/monitoring" })], +}); +``` + + + + + +```javascript {tabTitle:Browser} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + tunnel: "/monitoring", +}); +``` + +```javascript {tabTitle:Server} +export default Sentry.withSentry( + (env) => ({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration({ path: "/monitoring" })], + }), + { + async fetch(request, env, ctx) { + // Your app + }, + } +); +``` + + + +### What the Tunnel Forwards + +- Only events for your server's DSN and your `allowedDsns`, so the tunnel can't be used as an open proxy. +- The visitor's real IP address, without cookies or auth headers. + + + +See `serveTunnelIntegration` for all options. + + + +## Setting Up the Tunnel Manually + +The browser setup works the same as for the automatic tunnel, except that you point the browser SDK to the tunnel path you want to use, for example `/tunnel`: + +```javascript +Sentry.init({ + dsn: "___PUBLIC_DSN___", + tunnel: "/tunnel", +}); +``` + +How you serve that path depends on your server. If it runs a Sentry JavaScript SDK, you can use the tunnel helpers it comes with. Otherwise, write the endpoint yourself. + +### With a Sentry JavaScript SDK on Your Server + +Keep `serveTunnelIntegration` on your server. Set `intercept: false` so your route answers the requests instead of the SDK, and set `path` to your route so tunnel requests stay out of your traces: + + + +```javascript +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [ + Sentry.serveTunnelIntegration({ intercept: false, path: "/tunnel" }), + ], +}); +``` + + + +Answer the requests at your endpoint with `handleTunnelRequest`, which forwards them to Sentry: + + + +To forward a different browser DSN, add it to `allowedDsns` on the integration, as described in [Using a Different DSN in the Browser](#using-a-different-dsn-in-the-browser). `handleTunnelRequest` uses the same list. + +### On Other Servers + +Your endpoint must: + +- Forward the request body to Sentry, without cookies or auth headers. +- Accept only envelopes for your own DSNs, so it can't be used as an open proxy. +- Send the envelope only to the host of that DSN. + + + +```csharp {tabTitle:ASP.NET Core} +// This functionality is now built-in to the Sentry.AspNetCore package. +// See https://docs.sentry.io/platforms/dotnet/guides/aspnetcore/#tunnel +// docs for more information. + +// This example shows how you could implement it yourself: + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Text.Json; +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; + +// Change host appropriately if you run your own Sentry instance. +const string host = "sentry.io"; +// Set knownProjectIds to a list with your Sentry project IDs which you +// want to accept through this proxy. +var knownProjectIds = new HashSet() { }; + +var client = new HttpClient(); +WebHost.CreateDefaultBuilder(args).Configure(a => + a.Run(async context => + { + context.Request.EnableBuffering(); + using var reader = new StreamReader(context.Request.Body); + var header = await reader.ReadLineAsync(); + var headerJson = JsonSerializer.Deserialize>(header); + if (headerJson.TryGetValue("dsn", out var dsnString) + && Uri.TryCreate(dsnString.ToString(), UriKind.Absolute, out var dsn)) + { + var projectId = dsn.AbsolutePath.Trim('/'); + if (knownProjectIds.Contains(projectId) && string.Equals(dsn.Host, host, StringComparison.OrdinalIgnoreCase)) { + context.Request.Body.Position = 0; + await client.PostAsync($"https://{dsn.Host}/api/{projectId}/envelope/", + new StreamContent(context.Request.Body)); + } + } + })).Build().Run(); +``` + +```ruby {tabTitle:Rails} +require 'net/http' + +class HomeController < ApplicationController + + SENTRY_HOST = "oXXXXXX.ingest.sentry.io" + SENTRY_PROJECT_IDS = ["123456"] + + def tunnel + envelope = request.body.read + piece = envelope.split("\n").first + header = JSON.parse(piece) + dsn = URI.parse(header['dsn']) + project_id = dsn.path.tr('/', '') + + raise "Invalid sentry hostname: #{dsn.hostname}" if dsn.hostname != SENTRY_HOST + raise "Invalid sentry project id: #{project_id}" unless SENTRY_PROJECT_IDS.include?(project_id) + + upstream_sentry_url = "https://#{SENTRY_HOST}/api/#{project_id}/envelope/" + Net::HTTP.post(URI(upstream_sentry_url), envelope) + + head(:ok) + rescue => e + # handle exception in your preferred style, + # e.g. by logging or forwarding to server Sentry project + Rails.logger.error('error tunneling to sentry') + end + +end +``` + + + +#### Credentials on Tunnel Requests + +The browser sends cookies and HTTP authentication to an endpoint on the same origin as your app. If your endpoint forwards request headers, it sends them on to Sentry. + +Forward only the request body, or tell the browser to send no credentials: + +```javascript +Sentry.init({ + dsn: "___PUBLIC_DSN___", + tunnel: "/tunnel", + transportOptions: { + fetchOptions: { credentials: "omit" }, + }, +}); +``` + +If a layer in front of your tunnel requires credentials, like Vercel Deployment Protection or Cloudflare Access, keep sending them and forward only the request body. diff --git a/docs/platforms/javascript/common/data-management/sensitive-data/index.mdx b/docs/platforms/javascript/common/data-management/sensitive-data/index.mdx index b5c70dd09409f..dae753d55eacb 100644 --- a/docs/platforms/javascript/common/data-management/sensitive-data/index.mdx +++ b/docs/platforms/javascript/common/data-management/sensitive-data/index.mdx @@ -1,7 +1,7 @@ --- title: "Scrubbing Sensitive Data" description: "Learn about filtering or scrubbing sensitive data within the Sentry JavaScript SDK, so that data is not sent with the event. You can also configure server-side scrubbing to ensure the data is not stored." -customCanonicalTag: "/platforms/javascript/guides/koa/data-management/sensitive-data/" +customCanonicalTag: "/platforms/javascript/guides/node/data-management/sensitive-data/" sidebar_order: 100 keywords: - pii diff --git a/docs/platforms/javascript/common/index.mdx b/docs/platforms/javascript/common/index.mdx index f2e64835007ec..27e4d77056ae0 100644 --- a/docs/platforms/javascript/common/index.mdx +++ b/docs/platforms/javascript/common/index.mdx @@ -4,11 +4,9 @@ - +This guide focuses on plain JavaScript. If you're using a framework, select it to open its setup instructions: -This guide focuses on plain JavaScript. If you're working with React, Next.js, or any other framework, choose the fitting SDK from the left-hand dropdown. - - + diff --git a/docs/platforms/javascript/common/sourcemaps/uploading/rollup.mdx b/docs/platforms/javascript/common/sourcemaps/uploading/rollup.mdx index 1595ac6fcb59a..06aa5f958ffef 100644 --- a/docs/platforms/javascript/common/sourcemaps/uploading/rollup.mdx +++ b/docs/platforms/javascript/common/sourcemaps/uploading/rollup.mdx @@ -2,7 +2,7 @@ title: Rollup description: "Upload your source maps with the Sentry Rollup Plugin." sidebar_order: 5 -customCanonicalTag: "/platforms/javascript/guides/koa/sourcemaps/uploading/rollup/" +customCanonicalTag: "/platforms/javascript/guides/node/sourcemaps/uploading/rollup/" --- diff --git a/docs/platforms/javascript/common/troubleshooting/img/tunnel.png b/docs/platforms/javascript/common/troubleshooting/img/tunnel.png deleted file mode 100644 index e0417e91203bd..0000000000000 Binary files a/docs/platforms/javascript/common/troubleshooting/img/tunnel.png and /dev/null differ diff --git a/docs/platforms/javascript/common/troubleshooting/index.mdx b/docs/platforms/javascript/common/troubleshooting/index.mdx index 1fb9a9adef7e9..069439f628f5a 100644 --- a/docs/platforms/javascript/common/troubleshooting/index.mdx +++ b/docs/platforms/javascript/common/troubleshooting/index.mdx @@ -41,6 +41,7 @@ If you set up the Sentry SDK and it's not sending any data to Sentry: If you update your Sentry SDK to a new major version, you might encounter breaking changes that need some adaption on your end. + Check out our migration guide to learn everything you need @@ -126,7 +127,7 @@ Since Chrome 142, a page needs the user's permission before it can send requests | public | private network or localhost | Permission prompt | | private network | localhost | Permission prompt | -This affects a publicly hosted app reporting to a self-hosted Sentry that is only reachable on an internal address, and Spotlight enabled on a non-localhost page. To avoid the prompt, expose Sentry on a public hostname, or use the [`tunnel` option](#using-the-tunnel-option) to send events through your app's own origin. +This affects a publicly hosted app reporting to a self-hosted Sentry that is only reachable on an internal address, and Spotlight enabled on a non-localhost page. To avoid the prompt, expose Sentry on a public hostname, or use a tunnel to send events through your app's own origin. @@ -213,175 +214,10 @@ Chrome then ignores the SDK stack frames when debugging. -When you are using our CDN, ad-blocking or script-blocking extensions may prevent our SDK from being fetched and initialized properly. Because of this, any call to the SDKs API will fail and may cause your application to behave unexpectedly. - -Additionally, even when the SDK is downloaded and initialized correctly, Sentry endpoints that need to receive captured data may be blocked as well. This prevents any error reports, sessions health, or performance data from being delivered, making it effectively unavailable in [sentry.io](https://sentry.io). - -Furthermore, some browsers, like [Brave](https://brave.com/), have built-in ad-blockers that may block requests sent to our endpoint. Even if users deactivate your domain from blocking, Brave might continue to block [requests made from service workers](https://github.com/getsentry/sentry/issues/47912#issuecomment-1573714875). - -You can work around our CDN bundles being blocked by [using our NPM packages](#using-the-npm-package) and bundling our SDK with your app. However, the endpoint blockage can only be resolved by using a tunnel as explained below. - - - - - - - -The Sentry Next.js SDK has a separate option to make setting up tunnels very -straight-forward, allowing you to skip the setup below. See -`tunnelRoute` to learn how to set up tunneling on Next.js. - -If you do not want to configure `tunnelRoute`, you can follow the guide below. - - - -A tunnel is an HTTP endpoint that acts as a proxy between Sentry and your application. Because you control this server, there is no risk of any requests sent to it being blocked. When the endpoint lives under the same origin (although it does not have to in order for the tunnel to work), the browser will not treat any requests to the endpoint as a third-party request. As a result, these requests will have different security measures applied which, by default, don't trigger ad-blockers. A quick summary of the flow can be found below. - -![Tunnel Flow](./img/tunnel.png) - -Starting with version `6.7.0` of the JavaScript SDK, you can use the `tunnel` option to tell the SDK to deliver events to the configured URL, instead of using the DSN. This allows the SDK to remove `sentry_key` from the query parameters, which is one of the main reasons ad-blockers prevent sending events in the first place. This option also stops the SDK from sending preflight requests, which was one of the requirements that necessitated sending the `sentry_key` in the query parameters. - -To enable the `tunnel` option, provide either a relative or an absolute URL in your `Sentry.init` call. When you use a relative URL, it's relative to the current origin, and this is the form that we recommend. Using a relative URL will not trigger a preflight CORS request, so no events will be blocked, because the ad-blocker will not treat these events as third-party requests. When using tunneling with server-side SDKs like `@sentry/node` or `@sentry/bun` you must provide an absolute URL. - -```javascript -Sentry.init({ - dsn: "___PUBLIC_DSN___", - tunnel: "/tunnel", -}); -``` - -Once configured, all events will be sent to the `/tunnel` endpoint. This solution, however, requires an additional configuration on the server, as the events now need to be parsed and redirected to Sentry. - -Your tunnel endpoint must: - -- Forward only the request body to Sentry, without the request headers. -- Accept only envelopes whose DSN is on a list of allowed DSNs. Otherwise, anyone can use your endpoint to send requests to other servers. -- Send the envelope only to the host of that DSN. - -On a JavaScript server with Fetch API `Request` and `Response` objects, `handleTunnelRequest` from `@sentry/core` (SDK version `10.40.0` and later) does this for you. Starting with versions `10.77.1` (v10) and `11.9.0` (v11), it also rejects requests larger than 20 MiB. - -```javascript -import { handleTunnelRequest } from "@sentry/core"; - -export async function POST(request) { - return handleTunnelRequest({ - request, - allowedDsns: ["___PUBLIC_DSN___"], - }); -} -``` - -If you implement the endpoint yourself, here's an example for your server component: - -```csharp - -// This functionality is now built-in to the Sentry.AspNetCore package. -// See https://docs.sentry.io/platforms/dotnet/guides/aspnetcore/#tunnel -// docs for more information. - -// This example shows how you could implement it yourself: - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using System.Text.Json; -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; - -// Change host appropriately if you run your own Sentry instance. -const string host = "sentry.io"; -// Set knownProjectIds to a list with your Sentry project IDs which you -// want to accept through this proxy. -var knownProjectIds = new HashSet() { }; - -var client = new HttpClient(); -WebHost.CreateDefaultBuilder(args).Configure(a => - a.Run(async context => - { - context.Request.EnableBuffering(); - using var reader = new StreamReader(context.Request.Body); - var header = await reader.ReadLineAsync(); - var headerJson = JsonSerializer.Deserialize>(header); - if (headerJson.TryGetValue("dsn", out var dsnString) - && Uri.TryCreate(dsnString.ToString(), UriKind.Absolute, out var dsn)) - { - var projectId = dsn.AbsolutePath.Trim('/'); - if (knownProjectIds.Contains(projectId) && string.Equals(dsn.Host, host, StringComparison.OrdinalIgnoreCase)) { - context.Request.Body.Position = 0; - await client.PostAsync($"https://{dsn.Host}/api/{projectId}/envelope/", - new StreamContent(context.Request.Body)); - } - } - })).Build().Run(); -``` - -```ruby -require 'net/http' - -class HomeController < ApplicationController - - SENTRY_HOST = "oXXXXXX.ingest.sentry.io" - SENTRY_PROJECT_IDS = ["123456"] - - def tunnel - envelope = request.body.read - piece = envelope.split("\n").first - header = JSON.parse(piece) - dsn = URI.parse(header['dsn']) - project_id = dsn.path.tr('/', '') - - raise "Invalid sentry hostname: #{dsn.hostname}" if dsn.hostname != SENTRY_HOST - raise "Invalid sentry project id: #{project_id}" unless SENTRY_PROJECT_IDS.include?(project_id) - - upstream_sentry_url = "https://#{SENTRY_HOST}/api/#{project_id}/envelope/" - Net::HTTP.post(URI(upstream_sentry_url), envelope) - - head(:ok) - rescue => e - # handle exception in your preferred style, - # e.g. by logging or forwarding to server Sentry project - Rails.logger.error('error tunneling to sentry') - end - -end -``` - -```javascript -const SENTRY_HOST = "oXXXXXX.ingest.sentry.io"; -const SENTRY_PROJECT_IDS = ["123456"]; - -export const postAction = async ({ request }) => { - try { - const envelopeBytes = await request.arrayBuffer(); - const envelope = new TextDecoder().decode(envelopeBytes); - const piece = envelope.split("\n")[0]; - const header = JSON.parse(piece); - const dsn = new URL(header["dsn"]); - const project_id = dsn.pathname?.replace("/", ""); - - if (dsn.hostname !== SENTRY_HOST) { - throw new Error(`Invalid sentry hostname: ${dsn.hostname}`); - } - - if (!project_id || !SENTRY_PROJECT_IDS.includes(project_id)) { - throw new Error(`Invalid sentry project id: ${project_id}`); - } - - const upstream_sentry_url = `https://${SENTRY_HOST}/api/${project_id}/envelope/`; - await fetch(upstream_sentry_url, { method: "POST", body: envelopeBytes }); - - return json({}, { status: 200 }); - } catch (e) { - console.error("error tunneling to sentry", e); - return json({ error: "error tunneling to sentry" }, { status: 500 }); - } -}; -``` +Ad-blocking or script-blocking extensions may block Sentry in two ways: -If your use-case is related to the SDK package itself being blocked, any of the following solutions will help you resolve this issue. +- They block requests to Sentry's ingest endpoints, so captured data never reaches [sentry.io](https://sentry.io). Send events through your own server to avoid this, as described in Tunneling. +- When you load the SDK from our CDN, they may prevent it from being fetched and initialized. Any call to the SDK's API then fails and may cause your application to behave unexpectedly. Any of the following solutions resolves this. ### Using the NPM Package @@ -441,32 +277,6 @@ If you would like to copy and paste the snippet directly, here it is minified: - - -The browser SDK doesn't set the [`credentials`](https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials) option of `fetch`. With the default value `same-origin`, the browser sends credentials (cookies and HTTP authentication) to a tunnel on the same origin as your app. A tunnel that forwards request headers sends these credentials to Sentry. - - - -The Next.js `tunnelRoute` option handles this for you. See `tunnelRoute`. - - - -Forward only the request body, or tell the browser to send no credentials: - -```javascript -Sentry.init({ - dsn: "___PUBLIC_DSN___", - tunnel: "/tunnel", - transportOptions: { - fetchOptions: { credentials: "omit" }, - }, -}); -``` - -If a layer in front of your tunnel requires credentials (for example, Vercel Deployment Protection, Cloudflare Access, or HTTP Basic authentication), it rejects requests without credentials. Keep the default in this case, and make sure that your tunnel doesn't forward the request headers. - - - @@ -636,7 +446,7 @@ Learn more about fixing these caching issues in the - + diff --git a/docs/platforms/javascript/guides/astro/index.mdx b/docs/platforms/javascript/guides/astro/index.mdx index 85729298541b1..377dd37dd3990 100644 --- a/docs/platforms/javascript/guides/astro/index.mdx +++ b/docs/platforms/javascript/guides/astro/index.mdx @@ -5,6 +5,7 @@ sdk: sentry.javascript.astro categories: - browser - server +runtime: node --- ## Prerequisites @@ -18,7 +19,7 @@ You need: -This SDK currently only works on Node runtimes, such as Node adapter or Vercel with Lambda functions. If you use Cloudflare Workers or Cloudflare Pages, refer to our [Astro on Cloudflare guide](/platforms/javascript/guides/cloudflare/frameworks/astro/). Other non-Node runtimes, like Vercel's Edge runtime, are currently **not supported**. +This SDK currently only works on Node runtimes, such as Node adapter or Vercel with Lambda functions. If you use Cloudflare Workers or Cloudflare Pages, refer to our [Astro on Cloudflare guide](/platforms/javascript/guides/astro/cloudflare/). Other non-Node runtimes, like Vercel's Edge runtime, are currently **not supported**. @@ -204,7 +205,7 @@ At this point, you should have integrated Sentry into your Astro application. He - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup - Set up Agent Tracing to monitor your AI systems -- Set up tunneling to avoid ad blockers blocking Sentry events +- Set up tunneling to avoid ad blockers blocking Sentry events diff --git a/docs/platforms/javascript/guides/aws-lambda/configuration/lambda-wrapper.mdx b/docs/platforms/javascript/guides/aws-lambda/configuration/lambda-wrapper.mdx index 37f4d666de321..d45540daefe29 100644 --- a/docs/platforms/javascript/guides/aws-lambda/configuration/lambda-wrapper.mdx +++ b/docs/platforms/javascript/guides/aws-lambda/configuration/lambda-wrapper.mdx @@ -1,10 +1,10 @@ --- title: Lambda Handler Wrapper -description: "Configure Sentry's Lambda function wrapper" +description: "Configure Sentry's Lambda handler wrapper" sidebar_order: 2 --- -On this page you'll learn about the options to configure the `Sentry.wrapHandler` wrapper for your Lambda function. +On this page you'll learn about the options to configure the `Sentry.wrapHandler` wrapper for your Lambda Event Function. If you're using the AWS Lambda layer with environment variables (i.e. no Sentry code in your function), skip this guide or switch to the [initializing the SDK in code](../../install/layer/#alternative-initialize-the-sdk-in-code). diff --git a/docs/platforms/javascript/guides/aws-lambda/index.mdx b/docs/platforms/javascript/guides/aws-lambda/index.mdx index 7532fd6bab979..1fd998ae23dec 100644 --- a/docs/platforms/javascript/guides/aws-lambda/index.mdx +++ b/docs/platforms/javascript/guides/aws-lambda/index.mdx @@ -24,11 +24,11 @@ AWS Lambda offers two function types for Node.js, and each needs a different Sen -On this page you'll get an overview how to install, configure and use Sentry in your AWS Lambda functions. Once set up, our SDK will automatically report error and performance data from your Lambda Functions. Issues in Sentry will automatically include cloudwatch data, function details and execution time measurements. +On this page you'll get an overview how to install, configure and use Sentry in your AWS Lambda Event Functions (formerly called Lambda functions). Once set up, our SDK will automatically report error and performance data from your functions. Issues in Sentry will automatically include cloudwatch data, function details and execution time measurements. ## Installation -Depending on your preferences, you can install Sentry in your Lambda functions using the [Sentry AWS Lambda Layer](./install/layer/) (recommended) or the [Sentry AWS NPM package](./install/npm/). +Depending on your preferences, you can install Sentry in your Event Functions using the [Sentry AWS Lambda Layer](./install/layer/) (recommended) or the [Sentry AWS NPM package](./install/npm/). ### Should I use the Lambda Layer or the NPM package? @@ -36,12 +36,12 @@ We generally recommend using the Lambda layer as it doesn't require you to deplo With the layer, you can achieve the same level of customization as with the NPM package. There are two reasons why you still might want to use the NPM package instead: -1. You want to minimize lambda function size and tree-shake parts of the SDK code that you don't need. A related reason might be because you're transpiling your code and want to transpile your dependencies as well. +1. You want to minimize function size and tree-shake parts of the SDK code that you don't need. A related reason might be because you're transpiling your code and want to transpile your dependencies as well. 2. You already use NPM packages and deploy `node_modules` with your function and you don't want to add a (or another) Lambda layer to your functions. ## Configuration -After installing the SDK, you might want to configure some parameters. Besides the [common SDK configuration](./configuration/), you can also [configure Sentry's Lambda Function handler wrapper](./configuration/lambda-wrapper/) to optimize function runtime overhead and timeout warnings. +After installing the SDK, you might want to configure some parameters. Besides the [common SDK configuration](./configuration/), you can also [configure Sentry's Lambda handler wrapper](./configuration/lambda-wrapper/) to optimize function runtime overhead and timeout warnings. ## Verify diff --git a/docs/platforms/javascript/guides/aws-lambda/install/container-image.mdx b/docs/platforms/javascript/guides/aws-lambda/install/container-image.mdx index 3d901a0c50d11..0f34a9d199008 100644 --- a/docs/platforms/javascript/guides/aws-lambda/install/container-image.mdx +++ b/docs/platforms/javascript/guides/aws-lambda/install/container-image.mdx @@ -2,11 +2,11 @@ title: Container Image description: >- Learn how to install the Sentry Lambda extension to use Sentry in your - container image-based Lambda functions. + container image-based Lambda Event Functions. sidebar_order: 3 --- -When you deploy a Lambda function as a container image (for example, with the [Lambda Web Adapter](https://github.com/awslabs/aws-lambda-web-adapter) for SvelteKit, Next.js, or Remix), you can't attach a Lambda layer. That means you also lose the Sentry Lambda extension that ships with our [Lambda Layer](/platforms/javascript/guides/aws-lambda/install/layer/). +When you deploy a Lambda Event Function as a container image (for example, with the [Lambda Web Adapter](https://github.com/awslabs/aws-lambda-web-adapter) for SvelteKit, Next.js, or Remix), you can't attach a Lambda layer. That means you also lose the Sentry Lambda extension that ships with our [Lambda Layer](/platforms/javascript/guides/aws-lambda/install/layer/). Without the extension, events queued at the moment Lambda freezes the runtime can be lost. The extension runs as a sidecar process that receives events on a local port and forwards them to Sentry, so envelopes leave the function before the freeze. @@ -14,7 +14,7 @@ This guide shows how to install the extension into your Docker image and point a ## 1. Prerequisites -- Your Lambda function is deployed as a [container image](https://docs.aws.amazon.com/lambda/latest/dg/images-create.html). +- Your Lambda Event Function is deployed as a [container image](https://docs.aws.amazon.com/lambda/latest/dg/images-create.html). - You have a Sentry SDK in your application (`@sentry/aws-serverless`, `@sentry/sveltekit`, `@sentry/nextjs`, etc.). ## 2. Install `@sentry/aws-serverless` diff --git a/docs/platforms/javascript/guides/aws-lambda/install/index.mdx b/docs/platforms/javascript/guides/aws-lambda/install/index.mdx index 44d2f44538a76..f9e14dc98da3e 100644 --- a/docs/platforms/javascript/guides/aws-lambda/install/index.mdx +++ b/docs/platforms/javascript/guides/aws-lambda/install/index.mdx @@ -1,7 +1,7 @@ --- title: Installation Methods sidebar_order: 1 -description: "Review all installation methods for using Sentry in AWS Lambda functions" +description: "Review all installation methods for using Sentry in AWS Lambda Event Functions" --- @@ -12,9 +12,9 @@ We generally recommend using the Lambda layer as it doesn't require you to deplo With the layer, you can achieve the same level of customization as with the NPM package. There are two reasons why you still might want to use the NPM package instead: -1. You want to minimize lambda function size and tree-shake parts of the SDK code that you don't need. A related reason might be because you're transpiling your code and want to transpile your dependencies as well. +1. You want to minimize function size and tree-shake parts of the SDK code that you don't need. A related reason might be because you're transpiling your code and want to transpile your dependencies as well. 2. You already use NPM packages and deploy `node_modules` with your function and you don't want to add a (or another) Lambda layer to your functions. ### What if I'm deploying a container image? -Container image-based Lambda functions can't attach a layer. Follow the [Container Image guide](/platforms/javascript/guides/aws-lambda/install/container-image/) to install the Sentry Lambda extension into your Docker image so events queued during a Lambda freeze are still delivered. +Container image-based Event Functions can't attach a layer. Follow the [Container Image guide](/platforms/javascript/guides/aws-lambda/install/container-image/) to install the Sentry Lambda extension into your Docker image so events queued during a Lambda freeze are still delivered. diff --git a/docs/platforms/javascript/guides/aws-lambda/install/layer.mdx b/docs/platforms/javascript/guides/aws-lambda/install/layer.mdx index 30d47a8d30130..d060602a23091 100644 --- a/docs/platforms/javascript/guides/aws-lambda/install/layer.mdx +++ b/docs/platforms/javascript/guides/aws-lambda/install/layer.mdx @@ -2,7 +2,7 @@ title: Lambda Layer description: >- Learn how to add the Sentry Node Lambda Layer to use Sentry in your Lambda - functions + Event Functions sidebar_order: 1 og_image: /og-images/platforms-javascript-guides-aws-lambda-install-layer.png --- @@ -14,7 +14,7 @@ If you follow this guide, you don't have to worry about deploying Sentry depende Before you begin, make sure you have the following: -- You have a Lambda function deployed in AWS. +- You have a Lambda Event Function deployed in AWS. - You know the AWS region that your function is deployed to. ## 1. Add the Sentry Lambda Layer diff --git a/docs/platforms/javascript/guides/aws-lambda/install/npm.mdx b/docs/platforms/javascript/guides/aws-lambda/install/npm.mdx index 11a7c6b114264..a40001a8efce1 100644 --- a/docs/platforms/javascript/guides/aws-lambda/install/npm.mdx +++ b/docs/platforms/javascript/guides/aws-lambda/install/npm.mdx @@ -2,13 +2,13 @@ title: NPM Package description: >- Learn how to install the Sentry AWS NPM package to use Sentry in your Lambda - functions + Event Functions sidebar_order: 2 og_image: /og-images/platforms-javascript-guides-aws-lambda-install-npm.png --- -In this guide you will learn how to set up the `@sentry/aws-serverless` SDK for AWS Lambda functions using NPM. -We recommend starting the SDK automatically via environment variables so that you only have to make minimal code changes to your lambda function. +In this guide you will learn how to set up the `@sentry/aws-serverless` SDK for AWS Lambda Event Functions using NPM. +We recommend starting the SDK automatically via environment variables so that you only have to make minimal code changes to your function. If you need more control over the SDK setup, you can also [initialize the SDK in code](#option-b-manual-setup). However, you need to modify your code and deploy the Sentry dependencies alongside your function code. If you're looking for the most simple way to set up Sentry, use the [Lambda Layer](/platforms/javascript/guides/aws-lambda/install/layer/) instead. @@ -17,7 +17,7 @@ However, you need to modify your code and deploy the Sentry dependencies alongsi Before you begin, make sure you have the following: -- You have a Lambda function deployed in AWS. +- You have a Lambda Event Function deployed in AWS. - You're able to deploy dependencies (i.e. `node_modules`) alongside your function code to AWS Lambda. ## 2. Install diff --git a/docs/platforms/javascript/guides/bun/index.mdx b/docs/platforms/javascript/guides/bun/index.mdx index 953542c895b9e..4f18bafd063a0 100644 --- a/docs/platforms/javascript/guides/bun/index.mdx +++ b/docs/platforms/javascript/guides/bun/index.mdx @@ -7,6 +7,8 @@ categories: - server-only --- + + @@ -108,13 +110,7 @@ For Bun, `bunR Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. -Add an intentional error to your main application file: - -```javascript -setTimeout(() => { - throw new Error("Sentry Test Error"); -}, 0); -``` + ### View Captured Data in Sentry @@ -137,3 +133,5 @@ At this point, you should have integrated Sentry into your Bun application. Here + + diff --git a/docs/platforms/javascript/guides/cloudflare/frameworks/index.mdx b/docs/platforms/javascript/guides/cloudflare/frameworks/index.mdx deleted file mode 100644 index 91bb3bbe66db2..0000000000000 --- a/docs/platforms/javascript/guides/cloudflare/frameworks/index.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Frameworks on Cloudflare -description: "Learn how to set up the Cloudflare SDK with popular frameworks like Astro, SvelteKit, and Remix." ---- - -You can use the Sentry Cloudflare SDK in combination with Sentry meta-framework SDKs like SvelteKit or Remix to instrument your Cloudflare Pages applications that use these frameworks. - - diff --git a/docs/platforms/javascript/guides/cloudflare/frameworks/nextjs.mdx b/docs/platforms/javascript/guides/cloudflare/frameworks/nextjs.mdx deleted file mode 100644 index 6d4f78393a76a..0000000000000 --- a/docs/platforms/javascript/guides/cloudflare/frameworks/nextjs.mdx +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Next.js on Cloudflare -description: "Learn how to configure Sentry for your Next.js application deployed on Cloudflare Workers." ---- - -The Sentry Next.js SDK supports Next.js applications deployed on Cloudflare Workers, but requires additional configuration to run in this environment. - -## Prerequisites - -Before you begin, make sure you have: - -- A Sentry [account](https://sentry.io/signup/) and [project](/product/projects/) -- A [Cloudflare Workers project](https://dash.cloudflare.com/workers/overview) -- A Next.js application configured for Cloudflare Workers with [OpenNext](https://opennext.js.org/cloudflare) or [vinext](https://github.com/cloudflare/vinext) -- The Sentry SDK [installed and configured](/platforms/javascript/guides/nextjs/) in your Next.js application - - - If you haven't deployed a Next.js app to Cloudflare Workers before, follow - Cloudflare's [Next.js deployment - guide](https://developers.cloudflare.com/workers/framework-guides/web-apps/nextjs/) - to get started. - - -## Configure Wrangler - -Once you've set up Sentry in your Next.js application following the [installation guide](/platforms/javascript/guides/nextjs/), you'll need to configure [Wrangler](https://developers.cloudflare.com/workers/wrangler/) with the required compatibility settings. - -First, add the `nodejs_compat` [compatibility flag](https://developers.cloudflare.com/workers/runtime-apis/nodejs/) to configure the Cloudflare Workers runtime to provide the Node.js APIs required by the Sentry SDK. - -```json {tabTitle:wrangler.jsonc} -{ - "compatibility_flags": ["nodejs_compat"] -} -``` - -```toml {tabTitle:wrangler.toml} -compatibility_flags = ["nodejs_compat"] -``` - -Then, set the [compatibility date](https://developers.cloudflare.com/workers/configuration/compatibility-dates/) to `2025-08-16` or later. This is required to introduce `https.request` to the Cloudflare Workers runtime, which the Sentry SDK needs to send data. - -Your final configuration should look like this: - -```json {tabTitle:wrangler.jsonc} -{ - "compatibility_flags": ["nodejs_compat"], - "compatibility_date": "2025-08-16" -} -``` - -```toml {tabTitle:wrangler.toml} -compatibility_flags = ["nodejs_compat"] -compatibility_date = "2025-08-16" -``` - -## Wrap the Worker Entry - - - -If you build your app with vinext, skip to [Wrap the Worker Entry With vinext](#wrap-the-worker-entry-with-vinext). - -On Cloudflare Workers, your Next.js app runs inside the Worker entry that OpenNext generates (`.open-next/worker.js`). Wrap this entry with `withSentry` from `@sentry/nextjs/cloudflare` to get the same Next.js spans as on Node.js, plus Cloudflare data such as spans for D1 queries. Each request gets one `http.server` span with the name of the Next.js route, and the Next.js spans become its children. - -`@sentry/nextjs` depends on `@sentry/cloudflare`, so you don't need to install another package. - -First, create a [custom Worker](https://opennext.js.org/cloudflare/howtos/custom-worker) that imports the handler of OpenNext and wraps it with `withSentry`. Pass your Sentry options to `withSentry`: - -```typescript {filename:worker.ts} -import * as Sentry from "@sentry/nextjs/cloudflare"; -// @ts-ignore `.open-next/worker.js` is generated at build time -import handler from "./.open-next/worker.js"; - -// Re-export the Durable Objects your app uses, for example for the DO Queue and DO Tag Cache of OpenNext -// @ts-ignore `.open-next/worker.js` is generated at build time -export { DOQueueHandler, DOShardedTagCache } from "./.open-next/worker.js"; - -export default Sentry.withSentry( - () => ({ - dsn: "___PUBLIC_DSN___", - - // Set tracesSampleRate to 1.0 to capture 100% of spans for tracing. - // Learn more at - // https://docs.sentry.io/platforms/javascript/guides/cloudflare/configuration/options/#tracesSampleRate - tracesSampleRate: 1.0, - }), - handler -); -``` - -Then, point `main` in your Wrangler configuration to this file: - -```json {tabTitle:wrangler.jsonc} -{ - "main": "./worker.ts" -} -``` - -```toml {tabTitle:wrangler.toml} -main = "./worker.ts" -``` - -### Wrap the Worker Entry With vinext - - - -With [vinext](https://github.com/cloudflare/vinext), you don't need a custom Worker. Add the Sentry Vite plugin to your Vite config, and it wraps your Worker entry with `withSentry` from `@sentry/nextjs/cloudflare` automatically. - -### Server and Edge Configuration in the Worker - -In the Worker, `withSentry` creates the Sentry client. `Sentry.init()` in `sentry.server.config.ts` and `sentry.edge.config.ts` still runs, but it creates no client and only applies the `release` option. Set all other options in `withSentry`. - -On Workers, these two files are optional. Keep them if you use `next dev`, which runs on Node.js and doesn't use the Worker entry. They also pass on the release that `withSentryConfig` sets at build time. - -Keep `instrumentation.ts`, because Next.js reports server errors, for example from Server Components and route handlers, through its `onRequestError` hook. - -The SDK takes the release from the first of these sources that has a value: - -1. The `release` option of `withSentry` -2. The `SENTRY_RELEASE` environment variable -3. The ID of the `CF_VERSION_METADATA` binding -4. The `release` option of `Sentry.init()` in `sentry.server.config.ts` or `sentry.edge.config.ts`, or else the release that `withSentryConfig` sets at build time - -On Node.js, the build release comes before `SENTRY_RELEASE`. - -## Deploy - -Build and deploy your Next.js application to Cloudflare Workers. You should start seeing error events, traces, and logs appear in Sentry. diff --git a/docs/platforms/javascript/guides/cloudflare/frameworks/nuxt.mdx b/docs/platforms/javascript/guides/cloudflare/frameworks/nuxt.mdx deleted file mode 100644 index 3b3444b1cf8a7..0000000000000 --- a/docs/platforms/javascript/guides/cloudflare/frameworks/nuxt.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Nuxt on Cloudflare -description: "Learn how to instrument your Nuxt app on Cloudflare Workers and Pages and capture your first errors with Sentry." ---- - -This guide will show you how to set up the SDK with Nitro's `cloudflare_module` (or their deprecated `cloudflare-pages`) deployment preset. - - diff --git a/docs/platforms/javascript/guides/cloudflare/index.mdx b/docs/platforms/javascript/guides/cloudflare/index.mdx index 76049c2c54552..cd9bfc16f52ed 100644 --- a/docs/platforms/javascript/guides/cloudflare/index.mdx +++ b/docs/platforms/javascript/guides/cloudflare/index.mdx @@ -12,16 +12,9 @@ categories: This guide covers Cloudflare Workers. If you're deploying a Cloudflare Pages application, see Cloudflare Pages instead, which is set up with middleware rather than a wrapper. -If you're using any of the listed frameworks, follow their specific setup instructions: +If you're using a framework, select it to open its setup instructions: -- **[Astro](/platforms/javascript/guides/cloudflare/frameworks/astro/)** -- **[Hono](/platforms/javascript/guides/hono/)** (with @sentry/hono) -- **[Hydrogen](/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router/)** -- **[Next.js](/platforms/javascript/guides/cloudflare/frameworks/nextjs/)** -- **[Nuxt](/platforms/javascript/guides/cloudflare/frameworks/nuxt/)** -- **[Remix](/platforms/javascript/guides/cloudflare/frameworks/remix/)** -- **[SvelteKit](/platforms/javascript/guides/cloudflare/frameworks/sveltekit/)** -- **[TanStack Start](/platforms/javascript/guides/cloudflare/frameworks/tanstack-start/)** + The Cloudflare Workers runtime has some platform-specific limitations that @@ -178,7 +171,7 @@ At this point, you should have integrated Sentry into your Cloudflare Worker. He -- Check out setup instructions for popular [frameworks on Cloudflare](/platforms/javascript/guides/cloudflare/frameworks/) +- Using a framework? Select it in the [framework selector](#framework-selector) at the top of this page - Find various support topics in troubleshooting - [Get support](https://www.sentry.help/en/) diff --git a/docs/platforms/javascript/guides/cordova/configuration/options.mdx b/docs/platforms/javascript/guides/cordova/configuration/options.mdx index 6906a9235b502..49fcff6cc8323 100644 --- a/docs/platforms/javascript/guides/cordova/configuration/options.mdx +++ b/docs/platforms/javascript/guides/cordova/configuration/options.mdx @@ -49,9 +49,9 @@ Environments are case-sensitive. The environment name can't contain newlines, sp -Sets the URL that will be used to transport captured events. This can be used to work around ad-blockers or to have more granular control over events sent to Sentry. Adding your DSN is still required when using this option so necessary attributes can be set on the generated Sentry data. This option **requires the implementation** of a custom server endpoint. Learn more and find examples in [Dealing with Ad-Blockers](/platforms/javascript/troubleshooting/#dealing-with-ad-blockers). +Sets the URL that will be used to transport captured events. This can be used to work around ad-blockers or to have more granular control over events sent to Sentry. Adding your DSN is still required when using this option so necessary attributes can be set on the generated Sentry data. This option **requires the implementation** of a custom server endpoint. Learn more and find examples in [Tunneling](/platforms/javascript/configuration/tunneling/). -The endpoint must forward only the request body to Sentry and accept only your own DSNs. Learn more in [Using the `tunnel` Option](/platforms/javascript/troubleshooting/#using-the-tunnel-option). +The endpoint must forward only the request body to Sentry and accept only your own DSNs. Learn more in [Setting Up the Tunnel Manually](/platforms/javascript/configuration/tunneling/#setting-up-the-tunnel-manually). diff --git a/docs/platforms/javascript/guides/cordova/data-management/sensitive-data/index.mdx b/docs/platforms/javascript/guides/cordova/data-management/sensitive-data/index.mdx index 5045b48f990e1..5a280d3a5710c 100644 --- a/docs/platforms/javascript/guides/cordova/data-management/sensitive-data/index.mdx +++ b/docs/platforms/javascript/guides/cordova/data-management/sensitive-data/index.mdx @@ -1,7 +1,7 @@ --- title: "Scrubbing Sensitive Data" description: "Learn about filtering or scrubbing sensitive data within the Sentry JavaScript SDK, so that data is not sent with the event. You can also configure server-side scrubbing to ensure the data is not stored." -customCanonicalTag: "/platforms/javascript/guides/koa/data-management/sensitive-data/" +customCanonicalTag: "/platforms/javascript/guides/node/data-management/sensitive-data/" sidebar_order: 100 keywords: - pii diff --git a/docs/platforms/javascript/guides/cordova/sourcemaps/uploading/rollup.mdx b/docs/platforms/javascript/guides/cordova/sourcemaps/uploading/rollup.mdx index 066d1b6ba87f4..c2f8ffb6e6b6d 100644 --- a/docs/platforms/javascript/guides/cordova/sourcemaps/uploading/rollup.mdx +++ b/docs/platforms/javascript/guides/cordova/sourcemaps/uploading/rollup.mdx @@ -2,7 +2,7 @@ title: Rollup description: "Upload your source maps with the Sentry Rollup Plugin." sidebar_order: 5 -customCanonicalTag: "/platforms/javascript/guides/koa/sourcemaps/uploading/rollup/" +customCanonicalTag: "/platforms/javascript/guides/node/sourcemaps/uploading/rollup/" --- diff --git a/docs/platforms/javascript/guides/deno/index.mdx b/docs/platforms/javascript/guides/deno/index.mdx index 41329f9bb689a..87e356d892b3f 100644 --- a/docs/platforms/javascript/guides/deno/index.mdx +++ b/docs/platforms/javascript/guides/deno/index.mdx @@ -7,6 +7,8 @@ categories: - server-only --- + + This SDK is currently in **beta**. Beta features are still in progress and may have bugs. Please reach out on [GitHub](https://github.com/getsentry/sentry-javascript/issues/new/choose) if you have any feedback or concerns @@ -122,13 +124,7 @@ For Deno, `de Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. -Add an intentional error to your application: - -```javascript -setTimeout(() => { - throw new Error("Sentry Test Error"); -}, 0); -``` + ### View Captured Data in Sentry @@ -151,3 +147,5 @@ At this point, you should have integrated Sentry into your Deno application. Her + + diff --git a/docs/platforms/javascript/guides/ember/index.mdx b/docs/platforms/javascript/guides/ember/index.mdx index 4a12916733b9e..8b944aebf8d2f 100644 --- a/docs/platforms/javascript/guides/ember/index.mdx +++ b/docs/platforms/javascript/guides/ember/index.mdx @@ -154,7 +154,7 @@ Now, head over to your project on [Sentry.io](https://sentry.io) to view the col At this point, you should have integrated Sentry into your Ember application. Here's what to explore next: - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Set up tunneling to avoid ad blockers from blocking Sentry events +- Set up tunneling to avoid ad blockers from blocking Sentry events diff --git a/docs/platforms/javascript/guides/express/configuration/integrations/contextlines.mdx b/docs/platforms/javascript/guides/express/configuration/integrations/contextlines.mdx deleted file mode 100644 index 7b3af58727490..0000000000000 --- a/docs/platforms/javascript/guides/express/configuration/integrations/contextlines.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: ContextLines -description: "Adds source code to your stack frames. (default)" ---- - -_Import name: `Sentry.contextLinesIntegration`_ - -This integration is enabled by default. If you'd like to modify your default integrations, read [this](./../#modifying-default-integrations). - -This integration adds source code to your stack frames. It ensures that you can see the code that caused the error directly in the Sentry UI. - - - -## Options - -### `frameContextLines` - -_Type: `number`_ - -The number of lines to collect around each stack frame's line number. Defaults to 7. diff --git a/docs/platforms/javascript/guides/express/index.mdx b/docs/platforms/javascript/guides/express/index.mdx index 059dcbfb2b745..222756abf18f0 100644 --- a/docs/platforms/javascript/guides/express/index.mdx +++ b/docs/platforms/javascript/guides/express/index.mdx @@ -1,11 +1,51 @@ --- title: Express -description: "Learn how to manually set up Sentry in your Express app and capture your first events." +description: "Learn how to set up Sentry in your Express app on Node.js, Bun, or Deno." sdk: sentry.javascript.node fallbackGuide: javascript.node +inheritCommonContent: false categories: - server - server-only --- - +[Express](https://expressjs.com/) doesn't need its own Sentry SDK. Set up Sentry for the runtime your app runs on, and the SDK instruments Express automatically: `expressIntegration` captures errors from your routes and middleware, and creates spans for incoming requests when tracing is enabled. + +## Set Up Sentry for Your Runtime + +- +- +- + +## Customize Error Capturing + +Errors with a 3xx or 4xx status code are skipped, since they're usually expected redirects or client errors. To change which errors are captured, pass a `shouldHandleError` callback to `expressIntegration()`: + +```javascript +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [ + Sentry.expressIntegration({ + shouldHandleError(error) { + const status = Number(error.status ?? error.statusCode ?? 500); + // Capture 401/403 in addition to the default 5xx errors + return status === 401 || status === 403 || status >= 500; + }, + }), + ], +}); +``` + +If you capture errors yourself in your own error-handling middleware, set `shouldHandleError: false` to avoid duplicate events. diff --git a/docs/platforms/javascript/guides/express/index__v7.x.mdx b/docs/platforms/javascript/guides/express/index__v7.x.mdx deleted file mode 100644 index 76ef56f70dc76..0000000000000 --- a/docs/platforms/javascript/guides/express/index__v7.x.mdx +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Express -description: "Learn how to instrument the Sentry Express SDK." -sdk: sentry.javascript.node -fallbackGuide: javascript.node -categories: - - server ---- - - - -This guide explains how to set up Sentry in your Express application. - - diff --git a/docs/platforms/javascript/guides/express/tracing/instrumentation/automatic-instrumentation.mdx b/docs/platforms/javascript/guides/express/tracing/instrumentation/automatic-instrumentation.mdx deleted file mode 100644 index c7b42fb602ab9..0000000000000 --- a/docs/platforms/javascript/guides/express/tracing/instrumentation/automatic-instrumentation.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Automatic Instrumentation -description: "Learn what transactions are captured after tracing is enabled in the Sentry Express SDK." ---- - - diff --git a/docs/platforms/javascript/guides/fastify/features/error-handler.mdx b/docs/platforms/javascript/guides/fastify/features/error-handler.mdx deleted file mode 100644 index 43e3c0f8cf935..0000000000000 --- a/docs/platforms/javascript/guides/fastify/features/error-handler.mdx +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Fastify Error Handler -description: "Learn how Sentry's Fastify integration captures errors and how to configure it." ---- - -The `fastifyIntegration` captures errors in your Fastify application and sends them to Sentry. It's enabled by default, so you only need to add it to your `Sentry.init` call to configure it. - -By default, errors with status codes 5xx and above, as well as errors with status codes 2xx and below, are captured. Errors with 3xx and 4xx status codes aren't sent to Sentry. - -## Configuration - -To control which errors are captured, pass `shouldHandleError` to `Sentry.fastifyIntegration`: - -```javascript -import * as Sentry from "@sentry/node"; - -Sentry.init({ - dsn: "your-dsn", - integrations: [ - Sentry.fastifyIntegration({ - shouldHandleError(error, request, reply) { - return reply.statusCode >= 500; - }, - }), - ], -}); -``` - -## Options - -`Sentry.fastifyIntegration` accepts the following options: - -- `shouldHandleError` - -A function that determines whether an error should be captured. - -```typescript -declare function shouldHandleError( - error: Error, - request: FastifyRequest, - reply: FastifyReply -): boolean; -``` - -If using TypeScript, you can cast the request and reply to get full type safety. - -```typescript -import type { FastifyRequest, FastifyReply } from "fastify"; - -Sentry.fastifyIntegration({ - shouldHandleError(error, minimalRequest, minimalReply) { - const request = minimalRequest as FastifyRequest; - const reply = minimalReply as FastifyReply; - return reply.statusCode >= 500; - }, -}); -``` diff --git a/docs/platforms/javascript/guides/fastify/features/index.mdx b/docs/platforms/javascript/guides/fastify/features/index.mdx deleted file mode 100644 index b7fcfb338bb49..0000000000000 --- a/docs/platforms/javascript/guides/fastify/features/index.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Fastify Features -description: "Learn how Sentry's Node SDK exposes features for first class integration with Fastify." -excerpt: "" ---- - -The Sentry Node SDK offers Fastify-specific features for first class integration with the framework. - - diff --git a/docs/platforms/javascript/guides/fastify/index.mdx b/docs/platforms/javascript/guides/fastify/index.mdx index 8635ad6a08605..2e8735557adb6 100644 --- a/docs/platforms/javascript/guides/fastify/index.mdx +++ b/docs/platforms/javascript/guides/fastify/index.mdx @@ -1,13 +1,34 @@ --- title: Fastify -description: "Learn how to manually set up Sentry in your Fastify app and capture your first events." +description: "Learn how to set up Sentry in your Fastify app on Node.js, Bun, or Deno." sdk: sentry.javascript.node fallbackGuide: javascript.node +inheritCommonContent: false categories: - server - server-only --- - +[Fastify](https://fastify.dev/) doesn't need its own Sentry SDK. Set up Sentry for the runtime your app runs on, and the SDK instruments Fastify automatically: `fastifyIntegration` captures errors from your routes and hooks, and creates spans for incoming requests when tracing is enabled. - +## Set Up Sentry for Your Runtime + +- +- +- + +## Customize Error Capturing + +Errors with a 3xx or 4xx status code are skipped. To change which errors are captured, pass a `shouldHandleError` callback to `fastifyIntegration()`. See the [Fastify integration](/platforms/javascript/guides/node/configuration/integrations/fastify/#shouldhandleerror) for all options. diff --git a/docs/platforms/javascript/guides/fastify/tracing/instrumentation/automatic-instrumentation.mdx b/docs/platforms/javascript/guides/fastify/tracing/instrumentation/automatic-instrumentation.mdx deleted file mode 100644 index abc98b5bca4fd..0000000000000 --- a/docs/platforms/javascript/guides/fastify/tracing/instrumentation/automatic-instrumentation.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Automatic Instrumentation -description: "Learn what transactions are captured after tracing is enabled in the Sentry Fastify SDK." ---- - - diff --git a/docs/platforms/javascript/guides/flue/cloudflare.mdx b/docs/platforms/javascript/guides/flue/cloudflare.mdx index e5c274aa0189d..a9eba621da5b4 100644 --- a/docs/platforms/javascript/guides/flue/cloudflare.mdx +++ b/docs/platforms/javascript/guides/flue/cloudflare.mdx @@ -1,15 +1,15 @@ --- -title: Cloudflare Quick Start +title: Sentry for Flue (Cloudflare) +sidebar_title: Quick Start (Cloudflare) sidebar_order: 0.5 description: Learn how to send Flue agent traces, model calls, tool executions, and errors to Sentry from Cloudflare Workers. +runtime: cloudflare --- [Flue](https://flueframework.com/) is an open TypeScript framework for building AI agents, made by the Astro team. This guide sets up the Sentry SDK in a Flue app running on Cloudflare Workers so agent turns, model calls, tool executions, and errors flow into [Sentry Agent Tracing](/product/agents/). -Running Flue on Node.js? Follow the [Flue Quick Start](../) instead. - ## Prerequisites Before you begin, you need: diff --git a/docs/platforms/javascript/guides/flue/index.mdx b/docs/platforms/javascript/guides/flue/index.mdx index 5a87966bc49b9..430cf14d3ef05 100644 --- a/docs/platforms/javascript/guides/flue/index.mdx +++ b/docs/platforms/javascript/guides/flue/index.mdx @@ -4,6 +4,7 @@ description: Learn how to send Flue agent traces, model calls, tool executions, sdk: sentry.javascript.node fallbackGuide: javascript.node icon: flue +runtime: node categories: - server - server-only @@ -18,8 +19,6 @@ keywords: -Deploying Flue agents to Cloudflare Workers? Follow the [Cloudflare Quick Start](./cloudflare/) instead. - ## Prerequisites Before you begin, you need: diff --git a/docs/platforms/javascript/guides/gatsby/index.mdx b/docs/platforms/javascript/guides/gatsby/index.mdx index ec585fdbbe0d2..c6d51f50c2fa3 100644 --- a/docs/platforms/javascript/guides/gatsby/index.mdx +++ b/docs/platforms/javascript/guides/gatsby/index.mdx @@ -165,7 +165,7 @@ At this point, you should have integrated Sentry into your Gatsby application. H - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup - Set up Agent Tracing to monitor your AI systems -- Set up tunneling to avoid ad blockers from blocking Sentry events +- Set up tunneling to avoid ad blockers from blocking Sentry events diff --git a/docs/platforms/javascript/guides/hapi/configuration/integrations/contextlines.mdx b/docs/platforms/javascript/guides/hapi/configuration/integrations/contextlines.mdx deleted file mode 100644 index 7b3af58727490..0000000000000 --- a/docs/platforms/javascript/guides/hapi/configuration/integrations/contextlines.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: ContextLines -description: "Adds source code to your stack frames. (default)" ---- - -_Import name: `Sentry.contextLinesIntegration`_ - -This integration is enabled by default. If you'd like to modify your default integrations, read [this](./../#modifying-default-integrations). - -This integration adds source code to your stack frames. It ensures that you can see the code that caused the error directly in the Sentry UI. - - - -## Options - -### `frameContextLines` - -_Type: `number`_ - -The number of lines to collect around each stack frame's line number. Defaults to 7. diff --git a/docs/platforms/javascript/guides/hapi/index.mdx b/docs/platforms/javascript/guides/hapi/index.mdx index 9c3a092676880..147b858df193c 100644 --- a/docs/platforms/javascript/guides/hapi/index.mdx +++ b/docs/platforms/javascript/guides/hapi/index.mdx @@ -1,11 +1,32 @@ --- title: Hapi -description: "Learn how to manually set up Sentry in your Hapi app and capture your first events." +description: "Learn how to set up Sentry in your Hapi app on Node.js, Bun, or Deno." sdk: sentry.javascript.node fallbackGuide: javascript.node +inheritCommonContent: false categories: - server - server-only --- - +[Hapi](https://hapi.dev/) doesn't need its own Sentry SDK. Set up Sentry for the runtime your app runs on, and the SDK instruments Hapi automatically: `hapiIntegration` registers an error handler when your server starts, and creates spans for incoming requests when tracing is enabled. + +## Set Up Sentry for Your Runtime + +- +- +- + +To configure the integration, see the [Hapi integration](/platforms/javascript/guides/node/configuration/integrations/hapi/). diff --git a/docs/platforms/javascript/guides/hapi/tracing/instrumentation/automatic-instrumentation.mdx b/docs/platforms/javascript/guides/hapi/tracing/instrumentation/automatic-instrumentation.mdx deleted file mode 100644 index e749b53b702b1..0000000000000 --- a/docs/platforms/javascript/guides/hapi/tracing/instrumentation/automatic-instrumentation.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Automatic Instrumentation -description: "Learn what transactions are captured after tracing is enabled in the Sentry Hapi SDK." ---- - - diff --git a/docs/platforms/javascript/guides/cloudflare/frameworks/hono.mdx b/docs/platforms/javascript/guides/hono/cloudflare.mdx similarity index 96% rename from docs/platforms/javascript/guides/cloudflare/frameworks/hono.mdx rename to docs/platforms/javascript/guides/hono/cloudflare.mdx index 6a7df59814d50..a07aa937e23da 100644 --- a/docs/platforms/javascript/guides/cloudflare/frameworks/hono.mdx +++ b/docs/platforms/javascript/guides/hono/cloudflare.mdx @@ -1,6 +1,9 @@ --- title: Hono on Cloudflare description: "Learn how to instrument your Hono app on Cloudflare Workers with Sentry." +sidebar_title: Quick Start (Cloudflare) +sidebar_order: 0.5 +runtime: cloudflare --- Hono has its own dedicated SDK (`@sentry/hono`) with first-class support for Cloudflare Workers, Node.js, Bun, and Deno. It works as Hono middleware, so you can drop it into an existing app. diff --git a/docs/platforms/javascript/guides/koa/configuration/integrations/contextlines.mdx b/docs/platforms/javascript/guides/koa/configuration/integrations/contextlines.mdx deleted file mode 100644 index 7b3af58727490..0000000000000 --- a/docs/platforms/javascript/guides/koa/configuration/integrations/contextlines.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: ContextLines -description: "Adds source code to your stack frames. (default)" ---- - -_Import name: `Sentry.contextLinesIntegration`_ - -This integration is enabled by default. If you'd like to modify your default integrations, read [this](./../#modifying-default-integrations). - -This integration adds source code to your stack frames. It ensures that you can see the code that caused the error directly in the Sentry UI. - - - -## Options - -### `frameContextLines` - -_Type: `number`_ - -The number of lines to collect around each stack frame's line number. Defaults to 7. diff --git a/docs/platforms/javascript/guides/koa/index.mdx b/docs/platforms/javascript/guides/koa/index.mdx index 61f9b6d2450cb..33d7cff36ebad 100644 --- a/docs/platforms/javascript/guides/koa/index.mdx +++ b/docs/platforms/javascript/guides/koa/index.mdx @@ -1,11 +1,32 @@ --- title: Koa -description: "Learn how to manually set up Sentry in your Koa app and capture your first events." +description: "Learn how to set up Sentry in your Koa app on Node.js, Bun, or Deno." sdk: sentry.javascript.node fallbackGuide: javascript.node +inheritCommonContent: false categories: - server - server-only --- - +[Koa](https://koajs.com/) doesn't need its own Sentry SDK. Set up Sentry for the runtime your app runs on, and the SDK instruments Koa automatically: `koaIntegration` registers an error handler when your app starts, and creates spans for incoming requests and middleware when tracing is enabled. + +## Set Up Sentry for Your Runtime + +- +- +- + +To configure the integration, see the [Koa integration](/platforms/javascript/guides/node/configuration/integrations/koa/). diff --git a/docs/platforms/javascript/guides/koa/tracing/instrumentation/automatic-instrumentation.mdx b/docs/platforms/javascript/guides/koa/tracing/instrumentation/automatic-instrumentation.mdx deleted file mode 100644 index 4ad82b17e57af..0000000000000 --- a/docs/platforms/javascript/guides/koa/tracing/instrumentation/automatic-instrumentation.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Automatic Instrumentation -description: "Learn what transactions are captured after tracing is enabled in the Sentry Koa SDK." ---- - - diff --git a/docs/platforms/javascript/guides/mastra/cloudflare.mdx b/docs/platforms/javascript/guides/mastra/cloudflare.mdx index 2efb42fef0a73..59dfc102ee961 100644 --- a/docs/platforms/javascript/guides/mastra/cloudflare.mdx +++ b/docs/platforms/javascript/guides/mastra/cloudflare.mdx @@ -1,15 +1,15 @@ --- -title: Cloudflare Quick Start +title: Sentry for Mastra (Cloudflare) +sidebar_title: Quick Start (Cloudflare) sidebar_order: 0.5 description: Learn how to send Mastra agent traces, model calls, tool executions, and errors to Sentry from Cloudflare Workers. +runtime: cloudflare --- [Mastra](https://mastra.ai/) is a TypeScript framework for building AI applications and agents. This guide sets up the Sentry SDK in a Mastra app running on Cloudflare Workers so agent runs, model generations, tool calls, workflows, and errors flow into [Sentry Agent Tracing](/product/agents/). -Running Mastra on Node.js? Follow the [Mastra Quick Start](../) instead. - ## Prerequisites Before you begin, you need: diff --git a/docs/platforms/javascript/guides/mastra/index.mdx b/docs/platforms/javascript/guides/mastra/index.mdx index 43ecc77e79488..94b8b41e34bc6 100644 --- a/docs/platforms/javascript/guides/mastra/index.mdx +++ b/docs/platforms/javascript/guides/mastra/index.mdx @@ -4,6 +4,7 @@ description: Learn how to send Mastra agent traces, model calls, tool executions sdk: sentry.javascript.node fallbackGuide: javascript.node icon: mastra +runtime: node categories: - server - server-only @@ -18,8 +19,6 @@ keywords: -Running Mastra on Cloudflare Workers? Follow the [Cloudflare Quick Start](./cloudflare/) instead. - ## Prerequisites Before you begin, you need: diff --git a/docs/platforms/javascript/guides/nextjs/best-practices/deploying-on-cloudflare.mdx b/docs/platforms/javascript/guides/nextjs/best-practices/deploying-on-cloudflare.mdx deleted file mode 100644 index 2fc24a8629806..0000000000000 --- a/docs/platforms/javascript/guides/nextjs/best-practices/deploying-on-cloudflare.mdx +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: Deploying on Cloudflare Workers -description: "Learn how to configure Sentry for your Next.js application deployed on Cloudflare Workers." -sidebar_section: configuration ---- - -For instructions on deploying your Next.js application with Sentry on Cloudflare Workers, see the [Next.js on Cloudflare](/platforms/javascript/guides/cloudflare/frameworks/nextjs/) guide. diff --git a/docs/platforms/javascript/guides/nextjs/cloudflare.mdx b/docs/platforms/javascript/guides/nextjs/cloudflare.mdx new file mode 100644 index 0000000000000..c12cffdcce951 --- /dev/null +++ b/docs/platforms/javascript/guides/nextjs/cloudflare.mdx @@ -0,0 +1,9 @@ +--- +title: Next.js on Cloudflare +sidebar_title: Quick Start (Cloudflare) +sidebar_order: 0.5 +description: "Learn how to set up Sentry in your Next.js application deployed on Cloudflare Workers and capture your first errors." +runtime: cloudflare +--- + + diff --git a/docs/platforms/javascript/guides/nextjs/configuration/build/index.mdx b/docs/platforms/javascript/guides/nextjs/configuration/build/index.mdx index 65cc4f66e263a..26f1c59202ffa 100644 --- a/docs/platforms/javascript/guides/nextjs/configuration/build/index.mdx +++ b/docs/platforms/javascript/guides/nextjs/configuration/build/index.mdx @@ -204,85 +204,11 @@ Note: Enabling this option can lead to longer build times. - -This feature requires **Next.js version 11+**. Rewrite mode doesn't work with self-hosted Sentry instances. + +This option is deprecated and will be removed in v12. Set `tunnel: true` in the browser and add `serveTunnelIntegration` on the server instead, as described in Tunneling. -Tunnel Sentry requests through this route on your Next.js server to prevent ad-blockers from blocking Sentry events from being sent. - -This option can be set to: - -- `true` for auto-generated routes, which are unpredictable and change with each deployment. -- A custom static string path like `/error-monitoring`. - - - -Your middleware (`proxy.ts` or `middleware.ts`) also runs for tunnel requests. On v10, the SDK skips your middleware only in rewrite mode with Webpack. Exclude the tunnel route in its `matcher`. This needs a fixed string, because `true` creates a new path for each build: - -```typescript {filename:proxy.ts} -export const config = { - matcher: ["/((?!error-monitoring|_next/static|_next/image|favicon.ico).*)"], -}; -``` - - - -Learn more about tunneling in the troubleshooting section. - -The tunnel route works in one of two modes: - -- **Rewrite mode** (default): A Next.js rewrite proxies each request to Sentry with all its request headers. Works only with Sentry SaaS DSNs. -- **Handler mode**: A route handler in your app forwards only the request body to Sentry. Works with any DSN. - -Starting with versions `10.77.1` (v10) and `11.9.0` (v11), the browser sends tunnel requests in rewrite mode [with `credentials: "omit"`](https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials). -If a layer in front of your app requires credentials (for example, Vercel Deployment Protection or HTTP Basic authentication), it rejects these requests. Use handler mode in this case. -You can also set `credentials: "same-origin"`, but rewrite mode then forwards the credentials to Sentry: - -```javascript {filename:instrumentation-client.ts} -Sentry.init({ - dsn: "___PUBLIC_DSN___", - transportOptions: { - fetchOptions: { credentials: "same-origin" }, - }, -}); -``` - -**Handler mode** - - - -Keep `tunnelRoute` and add this file. If your app uses a `src` directory, add it at `src/app/sentry-tunnel/route.ts`: - -```typescript {filename:app/sentry-tunnel/route.ts} -export { POST } from "@sentry/nextjs/tunnel"; -``` - -This works with any `tunnelRoute` value, including `true`. When the SDK finds the file, the build prints this line: - -```bash -[@sentry/nextjs] The tunnel route sends events through app/sentry-tunnel/route.ts. Only the event payload goes to Sentry. -``` - -If the line is missing, the SDK uses rewrite mode. - -The handler accepts only the DSN of your server-side SDK. It rejects other DSNs with a `403` and requests larger than 20 MiB with a `413`. If your browser SDK uses a different DSN, list the allowed DSNs: - -```typescript {filename:app/sentry-tunnel/route.ts} -import { createSentryTunnelRoute } from "@sentry/nextjs/tunnel"; - -export const { POST } = createSentryTunnelRoute({ - allowedDsns: ["___PUBLIC_DSN___"], -}); -``` - - - -- Handler mode works only with the App Router. -- The SDK doesn't find the file in a route group, such as `app/(group)/sentry-tunnel/`. -- With `"moduleResolution": "node"` in `tsconfig.json`, the type check fails with `Cannot find module '@sentry/nextjs/tunnel'`. Set `moduleResolution` to `bundler`, `node16`, or `nodenext`. -- Each event request runs the route handler. On serverless hosts, this is one function invocation for each request. - - +Tunnels Sentry requests through a route on your Next.js server, so ad blockers don't drop them. Set it to `true` for a path derived from your DSN, or to a path like `/error-monitoring`. diff --git a/docs/platforms/javascript/guides/nextjs/index.mdx b/docs/platforms/javascript/guides/nextjs/index.mdx index 71fff4aae652d..3086deec71c81 100644 --- a/docs/platforms/javascript/guides/nextjs/index.mdx +++ b/docs/platforms/javascript/guides/nextjs/index.mdx @@ -5,256 +5,9 @@ sdk: sentry.javascript.nextjs categories: - browser - server +runtime: node --- - - - - -## Install - -### Run the Installation Wizard - -Run the Sentry wizard to automatically install the SDK and configure Sentry in your Next.js application: - -```bash -npx @sentry/wizard@latest -i nextjs -``` - -The wizard asks whether you want to enable **Tracing** and **Session Replay**, route browser requests through your server to avoid ad blockers, and create an example page. To match the configuration in this guide, answer **Yes** to each. - -Prefer to set things up yourself? Check out the [Manual Setup](/platforms/javascript/guides/nextjs/manual-setup/) guide. - -## Configure - -**Error Monitoring** starts working as soon as you call `Sentry.init()`. **Logs** and **Application Metrics** need no extra configuration, and you'll learn how to send them in steps [#3](#send-logs) and [#4](#send-application-metrics-). -This guide also enables **Tracing**, **Session Replay**, and **User Feedback**. - - - -### Initialize the SDK - -Next.js runs code in different environments, so the wizard creates a separate initialization file for each in your project's root directory (or `src` folder): - -- `instrumentation-client.ts`: runs in the browser -- `sentry.server.config.ts`: runs in the Node.js runtime -- `sentry.edge.config.ts`: runs in the Edge runtime - -Use the tabs in the code box below to view each file. - -The snippets also turn on: - -- Tracing: via `tracesSampleRate` in all three files -- Session Replay: via `replayIntegration()`, sampled with `replaysSessionSampleRate` and `replaysOnErrorSampleRate` -- User Feedback: via `feedbackIntegration()`. The wizard doesn't add this integration, so add it to `instrumentation-client.ts` yourself. - -Don't need a feature? Remove its integration and options from the snippets. - -```typescript {tabTitle:Client} {mdExpandTabs} {filename:instrumentation-client.ts} -import * as Sentry from "@sentry/nextjs"; - -Sentry.init({ - dsn: "___PUBLIC_DSN___", - integrations: [ - // enables Session Replay - Sentry.replayIntegration(), - // enables User Feedback - Sentry.feedbackIntegration({ - // Additional integration configuration goes in here - colorScheme: "system", - }), - ], - - // Enables Tracing. - // Set to 1.0 to capture 100% of spans for tracing. - // We recommend reducing this value in production. - tracesSampleRate: 1.0, - - // Capture replays for 10% of all sessions, - // plus for 100% of sessions with an error - // Requires Sentry.replayIntegration() - replaysSessionSampleRate: 0.1, - replaysOnErrorSampleRate: 1.0, -}); - -// Instruments client-side navigations -export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; -``` - -```typescript {tabTitle:Server} {filename:sentry.server.config.ts} -import * as Sentry from "@sentry/nextjs"; - -Sentry.init({ - dsn: "___PUBLIC_DSN___", - - // Enables Tracing. - // Set to 1.0 to capture 100% of spans for tracing. - // We recommend reducing this value in production. - tracesSampleRate: 1.0, -}); -``` - -```typescript {tabTitle:Edge} {filename:sentry.edge.config.ts} -import * as Sentry from "@sentry/nextjs"; - -Sentry.init({ - dsn: "___PUBLIC_DSN___", - - // Enables Tracing. - // Set to 1.0 to capture 100% of spans for tracing. - // We recommend reducing this value in production. - tracesSampleRate: 1.0, -}); -``` - -### Register the Server-Side Configuration - -The wizard creates a [Next.js instrumentation file](https://nextjs.org/docs/app/guides/instrumentation) named `instrumentation.ts`. It loads your server and edge configurations, and exports `onRequestError` to capture errors from Server Components, route handlers, and middleware. - -```typescript {filename:instrumentation.ts} -import * as Sentry from "@sentry/nextjs"; - -export async function register() { - if (process.env.NEXT_RUNTIME === "nodejs") { - await import("./sentry.server.config"); - } - - if (process.env.NEXT_RUNTIME === "edge") { - await import("./sentry.edge.config"); - } -} - -export const onRequestError = Sentry.captureRequestError; -``` - -### Capture React Render Errors - -If you use the App Router, the wizard adds Sentry to `app/global-error.tsx` to capture React rendering errors. If you use the Pages Router, it adds Sentry to `pages/_error.tsx` instead. - - - -### Apply Instrumentation to Your App - -The wizard wraps your Next.js configuration with `withSentryConfig`. This instruments your app at build time, uploads source maps, and, if you said yes in the wizard, routes browser requests to Sentry through your server to avoid ad blockers. - -To forward only the request body to Sentry, add a tunnel route handler (SDK version `10.77.1` and later on v10, `11.9.0` and later on v11). Use the handler if Vercel Deployment Protection or another login protects your app. -Learn more about the [`tunnelRoute` option](/platforms/javascript/guides/nextjs/configuration/build/#tunnelRoute). - -```typescript {filename:next.config.ts} -import type { NextConfig } from "next"; -import { withSentryConfig } from "@sentry/nextjs/config"; - -const nextConfig: NextConfig = { - // Your existing Next.js configuration -}; - -export default withSentryConfig(nextConfig, { - org: "___ORG_SLUG___", - project: "___PROJECT_SLUG___", - - // Only print logs for uploading source maps in CI - silent: !process.env.CI, - - // Upload a larger set of source maps for prettier stack traces (increases build time) - widenClientFileUpload: true, - - // Route browser requests to Sentry through a Next.js rewrite to avoid ad blockers. - // This can increase your server load as well as your hosting bill. - tunnelRoute: "/monitoring", -}); -``` - -### Add Readable Stack Traces With Source Maps - -The wizard stores your auth token in `.env.sentry-build-plugin` and adds the file to `.gitignore`. The Sentry build plugin uses this token to upload source maps when you build your app locally. - -For CI/CD builds, set the `SENTRY_AUTH_TOKEN` environment variable in your build system instead. - - - -```bash {filename:.env.sentry-build-plugin} -SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ -``` - -### Control the Data You Send to Sentry - - - -## Send Logs - - - -If you're already logging with another library, use an integration to capture those logs as Sentry Logs automatically: - -- `consoleLoggingIntegration` for `console` calls -- Consola -- Pino -- Winston - -## Send Application Metrics - - - -In the Node.js runtime, `nodeRuntimeMetricsIntegration` also collects runtime health metrics automatically. - -## Verify Your Setup - -Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. - -The wizard created an example page that sends a test error from both your frontend and your backend: - -1. Start your development server: - - ```bash - npm run dev - ``` - -2. Open [localhost:3000/sentry-example-page](http://localhost:3000/sentry-example-page) in your browser. -3. Click **Throw Sample Error**. - -If you skipped the example page, add a test button to one of your pages instead. Clicking it will trigger an error for Sentry to capture. - -```tsx {filename:app/page.tsx} -"use client"; - -export default function Page() { - return ( - - ); -} -``` - - - -### View Captured Data in Sentry - -Now, head over to your project on [Sentry.io](https://sentry.io/) to view the collected data (it takes a couple of moments for the data to appear). - - - -## Next Steps - -At this point, you should have integrated Sentry into your Next.js application. Here's what to explore next: - -- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Set up Agent Tracing to monitor agents built with the Vercel AI SDK, LangChain, and more -- Set up tunneling to avoid ad blockers blocking Sentry events, if you didn't enable it in the wizard - - - -- If you encountered issues with our installation wizard, try [setting up Sentry manually](/platforms/javascript/guides/nextjs/manual-setup/) -- Find various topics in Troubleshooting -- [Get support](https://www.sentry.help/en/) - - - - + diff --git a/docs/platforms/javascript/guides/nextjs/manual-setup/index.mdx b/docs/platforms/javascript/guides/nextjs/manual-setup/index.mdx index ddbc212f18dea..a741cb79ab385 100644 --- a/docs/platforms/javascript/guides/nextjs/manual-setup/index.mdx +++ b/docs/platforms/javascript/guides/nextjs/manual-setup/index.mdx @@ -254,32 +254,13 @@ Prevent ad blockers from blocking Sentry events by routing them through your Nex This increases server load. Consider the trade-off for your application. -To forward only the request body to Sentry, also add `app/sentry-tunnel/route.ts` (SDK version `10.77.1` and later on v10, `11.9.0` and later on v11). -Use this file if Vercel Deployment Protection or another login protects your app. Learn more in `tunnelRoute`. +Set `tunnel: true` in your browser `Sentry.init`, and add `serveTunnelIntegration` to your server `Sentry.init`: - + -If you're using Next.js proxy/middleware that intercepts requests, exclude the tunnel route. The file is called `proxy.ts` in Next.js 16+ and `middleware.ts` in Next.js 15: + -```typescript {filename:proxy.ts} -export const config = { - matcher: ["/((?!sentry-tunnel|_next/static|_next/image|favicon.ico).*)"], -}; -``` - - - -```typescript {filename:next.config.ts} -export default withSentryConfig(nextConfig, { - // Use a fixed route (recommended) - tunnelRoute: "/sentry-tunnel", -}); -``` - -```typescript {filename:app/sentry-tunnel/route.ts} -// Forward only the request body to Sentry -export { POST } from "@sentry/nextjs/tunnel"; -``` +Learn more in Tunneling. ### Control the Data You Send to Sentry (Optional) diff --git a/docs/platforms/javascript/guides/nextjs/manual-setup/webpack-setup.mdx b/docs/platforms/javascript/guides/nextjs/manual-setup/webpack-setup.mdx index 8e51afc5e733f..2827d4e663d03 100644 --- a/docs/platforms/javascript/guides/nextjs/manual-setup/webpack-setup.mdx +++ b/docs/platforms/javascript/guides/nextjs/manual-setup/webpack-setup.mdx @@ -218,31 +218,15 @@ export default withSentryConfig(nextConfig, { Tunneling works identically for both Webpack and Turbopack. Sentry automatically filters tunnel requests from middleware spans to prevent noise in your monitoring data. -### Configure Tunnel Route +### Configure the Tunnel -Enable tunneling to bypass ad-blockers. Use a fixed route so you can exclude it from middleware if needed. +Set `tunnel: true` in your browser `Sentry.init`, and add `serveTunnelIntegration` to your server `Sentry.init`: -To forward only the request body to Sentry, add a tunnel route handler (SDK version `10.77.1` and later on v10, `11.9.0` and later on v11). -Use the handler if Vercel Deployment Protection or another login protects your app. Learn more about the [`tunnelRoute` option](/platforms/javascript/guides/nextjs/configuration/build/#tunnelRoute). + - + -You can use `tunnelRoute: true` to auto-generate a random route. However, random routes cannot be excluded from middleware matchers since the route changes on each build. This may cause issues if you have middleware that intercepts all requests. - -```typescript -tunnelRoute: true, // Auto-generated random route -``` - - - -```typescript {filename:next.config.ts} -import { withSentryConfig } from "@sentry/nextjs/config"; - -export default withSentryConfig(nextConfig, { - // Use a fixed route (recommended) - tunnelRoute: "/sentry-tunnel", -}); -``` +Learn more in [Tunneling](/platforms/javascript/guides/nextjs/configuration/tunneling/). ## Migrating from Webpack to Turbopack @@ -258,13 +242,11 @@ export default withSentryConfig(nextConfig, { webpack: { excludeServerRoutes: ["/api/health"], }, - tunnelRoute: "/sentry-tunnel", }); // After (Turbopack) export default withSentryConfig(nextConfig, { // webpack.excludeServerRoutes is not supported with Turbopack - tunnelRoute: "/sentry-tunnel", }); ``` diff --git a/docs/platforms/javascript/guides/node/index.mdx b/docs/platforms/javascript/guides/node/index.mdx index 989e9c7935797..0955371bf4511 100644 --- a/docs/platforms/javascript/guides/node/index.mdx +++ b/docs/platforms/javascript/guides/node/index.mdx @@ -7,8 +7,12 @@ categories: - server-only --- + + + + diff --git a/docs/platforms/javascript/guides/nuxt/cloudflare.mdx b/docs/platforms/javascript/guides/nuxt/cloudflare.mdx new file mode 100644 index 0000000000000..312a366e6a20c --- /dev/null +++ b/docs/platforms/javascript/guides/nuxt/cloudflare.mdx @@ -0,0 +1,11 @@ +--- +title: Nuxt on Cloudflare +sidebar_title: Quick Start (Cloudflare) +sidebar_order: 0.5 +description: "Learn how to instrument your Nuxt app on Cloudflare Workers and Pages and capture your first errors with Sentry." +runtime: cloudflare +--- + +This guide shows how to set up the SDK with Nitro's `cloudflare_module` deployment preset, or with the deprecated `cloudflare-pages` preset. + + diff --git a/docs/platforms/javascript/guides/nuxt/features/nitro-deployment-presets.mdx b/docs/platforms/javascript/guides/nuxt/features/nitro-deployment-presets.mdx index 945f878d90816..ca23844d62a0d 100644 --- a/docs/platforms/javascript/guides/nuxt/features/nitro-deployment-presets.mdx +++ b/docs/platforms/javascript/guides/nuxt/features/nitro-deployment-presets.mdx @@ -8,4 +8,4 @@ The Sentry Nuxt SDK provides support for different Nitro deployment presets, mos ## Cloudflare Pages -Using the Cloudflare Nitro plugin of Sentry enables Sentry monitoring on Cloudflare Workers and Pages. Go and see the [Cloudflare Nitro plugin documentation](/platforms/javascript/guides/cloudflare/frameworks/nuxt/). +Using the Cloudflare Nitro plugin of Sentry enables Sentry monitoring on Cloudflare Workers and Pages. Go and see the [Cloudflare Nitro plugin documentation](/platforms/javascript/guides/nuxt/cloudflare/). diff --git a/docs/platforms/javascript/guides/nuxt/index.mdx b/docs/platforms/javascript/guides/nuxt/index.mdx index 0fd2306ca119c..939e36f930dc8 100644 --- a/docs/platforms/javascript/guides/nuxt/index.mdx +++ b/docs/platforms/javascript/guides/nuxt/index.mdx @@ -5,108 +5,7 @@ sdk: sentry.javascript.nuxt categories: - browser - server +runtime: node --- - - - - -## Install - - - - - - - - - -## Avoid Ad Blockers With Tunneling (Optional) - - - -## Control the Data You Send to Sentry (Optional) - - - -## Verify Your Setup - -The `sentry init` command checks the integration files it creates or modifies before it finishes. To confirm runtime events are reaching Sentry, start your Nuxt app, exercise the parts of your app that should send events, and then check your Sentry project. - -If you used the Nuxt installation wizard instead, you can also verify your setup with the example page or component it creates. - - -The wizard creates a `SentryErrorButton` component when it fails to add an example page to your project. This usually happens if you don't have a `app.vue` file or if that file does not contain the `NuxtPage` component. To verify your setup, follow these steps before continuing with the next section, "View Captured Data in Sentry": - -1. Add the `SentryErrorButton` component to a page and open it in your browser. For most Nuxt applications, this will be at localhost. -2. Click the "Throw Sample Error" button, which triggers an error and starts a performance trace on the client side. - -To test the server side as well, refer to the "Verify" section in the [Manual setup guide](/platforms/javascript/guides/nuxt/manual-setup/). - - - -To test Sentry, you can run your Nuxt application in either production or development mode. -We **recommend testing in production mode** as it most closely resembles your deployed application's environment. - -The SDK bundles `sentry.server.config.ts` into the Nitro server build and initializes Sentry when the server starts. To learn more, see Server-Side Installation. - -### Run in Production Mode (Recommended) - -Build your project with `nuxi build`, then start the server. - -```bash -# Start your app after building your project with `nuxi build` -node .output/server/index.mjs -``` - -### Run in Development Mode - -Sentry also monitors the server side during development. Start the dev server as usual. - -Spans from some libraries, such as database clients, can be missing in development mode. -Errors and request traces always work. To learn more, see Development Mode. - -```bash -nuxt dev -``` - -If you used the Nuxt installation wizard, after building and running your project: - -1. Open the example page `/sentry-example-page` in your browser. For most Nuxt applications, this will be at localhost. -2. Click the "Throw sample error" button. This triggers two errors: - - a frontend error - - an error within the API route - -Sentry captures both of these errors for you. Additionally, the button click starts a performance trace to measure the time it takes for the API request to complete. - - - -### View Captured Data in Sentry - -Now, head over to your project on [Sentry.io](https://sentry.io/) to view the collected data (it takes a couple of moments for the data to appear). - - - - - -## Next Steps - -At this point, you should have integrated Sentry into your Nuxt application and should already be sending error and performance data to your Sentry project. - -Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are: - -- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Learn how to [manually capture errors](/platforms/javascript/guides/nuxt/usage/) -- Continue to [customize your configuration](/platforms/javascript/guides/nuxt/configuration/) -- Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts -- Learn how to [track your Vue components or your Pinia store](/platforms/javascript/guides/nuxt/features/) -- Learn how to [add support for different Nitro deployment presets](/platforms/javascript/guides/nuxt/features/nitro-deployment-presets/) (like Cloudflare) - - - -- If you encountered issues with our installation wizard, try [setting up Sentry manually](/platforms/javascript/guides/nuxt/manual-setup/) -- [Get support](https://www.sentry.help/en/) - - - - + diff --git a/docs/platforms/javascript/guides/nuxt/install/index.mdx b/docs/platforms/javascript/guides/nuxt/install/index.mdx index 298c08d02db09..4f11e711aea48 100644 --- a/docs/platforms/javascript/guides/nuxt/install/index.mdx +++ b/docs/platforms/javascript/guides/nuxt/install/index.mdx @@ -38,7 +38,7 @@ The SDK doesn't initialize Sentry while Nitro prerenders your pages at build tim ### Cloudflare -With a Cloudflare Nitro preset, the SDK doesn't use `sentry.server.config.ts`. Set up the SDK with the [Cloudflare Nitro plugin](/platforms/javascript/guides/cloudflare/frameworks/nuxt/) instead. +With a Cloudflare Nitro preset, the SDK doesn't use `sentry.server.config.ts`. Set up the SDK with the [Cloudflare Nitro plugin](/platforms/javascript/guides/nuxt/cloudflare/) instead. ## Upgrade to SDK Version 11 diff --git a/docs/platforms/javascript/guides/pi-durable/bun.mdx b/docs/platforms/javascript/guides/pi-durable/bun.mdx new file mode 100644 index 0000000000000..8990f49d25a32 --- /dev/null +++ b/docs/platforms/javascript/guides/pi-durable/bun.mdx @@ -0,0 +1,120 @@ +--- +title: Sentry for Pi Durable (Bun) +sidebar_title: Quick Start (Bun) +sidebar_order: 0.7 +description: Learn how to send Pi Durable agent runs, model requests, tool calls, and errors to Sentry from a Bun app. +runtime: bun +--- + +[Pi Durable](https://earendil.com/posts/pi-durable/) is Earendil's durable agent harness, built on the same foundations as the Pi coding agent. This guide sets up the Sentry SDK in a Bun app that runs Pi Durable, so agent runs, model requests, tool calls, and errors flow into [Sentry Agent Tracing](/product/agents/). + + + +## Prerequisites + +Before you begin, you need: + +- A Sentry [account](https://sentry.io/signup/) and [project](/product/projects/). The project's DSN tells the SDK where to send data. +- A Bun application using `@earendil-works/pi-durable` version `1.0.0` or later. +- `@sentry/bun` version `11.6.0` or later. + + + +## Install + +Choose the features you want to configure, and this guide will show you how: + + + +Install the Sentry Bun SDK: + +```bash +bun add @sentry/bun@^11.6.0 +``` + +## Configure + +Create an `instrument.ts` file in the root of your project. The Pi Durable integration is enabled by default, so you don't add it to `integrations`: + +```typescript {filename:instrument.ts} +import * as Sentry from "@sentry/bun"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + // ___PRODUCT_OPTION_START___ performance + + // Set tracesSampleRate to 1.0 to capture 100% + // of spans for tracing. + // We recommend adjusting this value in production. + // Learn more at + // https://docs.sentry.io/platforms/javascript/guides/bun/configuration/options/#tracesSampleRate + tracesSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ performance +}); +``` + +Bun has no runtime hook that Sentry can use to instrument Pi Durable, so build your app with `sentryBunPlugin` from `@sentry/bun/plugin`. The plugin instruments `Harness.open()` while `Bun.build()` bundles `@earendil-works/pi-durable`: + +```typescript {filename:build.ts} +import { sentryBunPlugin } from "@sentry/bun/plugin"; + +await Bun.build({ + entrypoints: ["./app.ts"], + outdir: "./dist", + target: "bun", + plugins: [sentryBunPlugin()], +}); +``` + +Build your app, then run the output with the instrument file preloaded: + +```bash +bun build.ts +bun --preload ./instrument.ts dist/app.js +``` + +If you run your source directly, for example with `bun app.ts`, the plugin doesn't run, and Pi Durable isn't traced. + +Your Pi Durable code doesn't change. Every Harness your app opens is traced, whichever storage it uses. + + + +### Control the Data You Send to Sentry (Optional) + + + +To change recording for Pi Durable only, pass `recordInputs` and `recordOutputs` to the integration. They take precedence over `dataCollection`: + +```typescript {filename:instrument.ts} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [ + Sentry.piDurableIntegration({ + recordInputs: false, + recordOutputs: false, + }), + ], +}); +``` + + + + + + + +## Troubleshooting + +- **No AI spans at all.** Confirm that `sentryBunPlugin()` is in your `Bun.build()` call and that you run the built output, not your source files. + + + + + +## Supported Versions + +- `@sentry/bun`: `>=11.6.0` +- `@earendil-works/pi-durable`: `>=1.0.0 <2.0.0` diff --git a/docs/platforms/javascript/guides/pi-durable/cloudflare.mdx b/docs/platforms/javascript/guides/pi-durable/cloudflare.mdx index cfde28a4f313c..1a178064c9377 100644 --- a/docs/platforms/javascript/guides/pi-durable/cloudflare.mdx +++ b/docs/platforms/javascript/guides/pi-durable/cloudflare.mdx @@ -1,15 +1,15 @@ --- -title: Cloudflare Quick Start +title: Sentry for Pi Durable (Cloudflare) +sidebar_title: Quick Start (Cloudflare) sidebar_order: 0.5 description: Learn how to send Pi Durable agent runs, model requests, tool calls, and errors to Sentry from Cloudflare Durable Objects. +runtime: cloudflare --- [Pi Durable](https://earendil.com/posts/pi-durable/) is Earendil's durable agent harness, built on the same foundations as the Pi coding agent. This guide sets up the Sentry SDK in a Worker that runs Pi Durable in a Durable Object, for example through the Agents SDK `PiHarness`, so agent runs, model requests, tool calls, and errors flow into [Sentry Agent Tracing](/product/agents/). -Running Pi Durable on Node.js? Follow the [Pi Durable Quick Start](../) instead. - ## Prerequisites Before you begin, you need: diff --git a/docs/platforms/javascript/guides/pi-durable/deno.mdx b/docs/platforms/javascript/guides/pi-durable/deno.mdx new file mode 100644 index 0000000000000..24eecb22d96a1 --- /dev/null +++ b/docs/platforms/javascript/guides/pi-durable/deno.mdx @@ -0,0 +1,121 @@ +--- +title: Sentry for Pi Durable (Deno) +sidebar_title: Quick Start (Deno) +sidebar_order: 0.6 +description: Learn how to send Pi Durable agent runs, model requests, tool calls, and errors to Sentry from a Deno app. +runtime: deno +--- + +[Pi Durable](https://earendil.com/posts/pi-durable/) is Earendil's durable agent harness, built on the same foundations as the Pi coding agent. This guide sets up the Sentry SDK in a Deno app that runs Pi Durable, so agent runs, model requests, tool calls, and errors flow into [Sentry Agent Tracing](/product/agents/). + + + +## Prerequisites + +Before you begin, you need: + +- A Sentry [account](https://sentry.io/signup/) and [project](/product/projects/). The project's DSN tells the SDK where to send data. +- A Deno application using `@earendil-works/pi-durable` version `1.0.0` or later. Deno must be version `2.8.3` or later. +- `@sentry/deno` version `11.6.0` or later. + + + +## Install + +Choose the features you want to configure, and this guide will show you how: + + + +Deno loads the Sentry Deno SDK from npm through the `npm:` specifier. Add it to the imports in your `deno.json`, so Deno uses version `11.6.0` or later. + +The Sentry import hook, which you load when you start your app, reads `@earendil-works/pi-durable` from a local `node_modules` directory, not from Deno's global npm cache. Set `nodeModulesDir` in your `deno.json` too: + +```json {filename:deno.json} +{ + "imports": { + "@sentry/deno": "npm:@sentry/deno@^11.6.0" + }, + "nodeModulesDir": "auto" +} +``` + +## Configure + +Initialize the Sentry SDK at the top of your entry file. The Pi Durable integration is enabled by default, so you don't add it to `integrations`: + +```typescript {filename:main.ts} +import * as Sentry from "npm:@sentry/deno"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + // ___PRODUCT_OPTION_START___ performance + + // Set tracesSampleRate to 1.0 to capture 100% + // of spans for tracing. + // We recommend adjusting this value in production. + // Learn more at + // https://docs.sentry.io/platforms/javascript/guides/deno/configuration/options/#tracesSampleRate + tracesSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ performance +}); +``` + +Load the Sentry import hook with the `--preload` flag when you start your app. Deno blocks access to the network, the file system, and system information until you grant it. Add the hosts your agents call, such as your model provider, to `--allow-net`, separated by commas, and add any other access your app needs: + +```bash +deno run \ + --preload=npm:@sentry/deno/import \ + --allow-net=___ORG_INGEST_DOMAIN___,api.openai.com \ + --allow-env \ + --allow-read=. \ + --allow-sys=hostname,osRelease \ + main.ts +``` + +The import hook instruments `Harness.open()` while Deno loads `@earendil-works/pi-durable`. `Sentry.init()` in your entry file alone is too late, because Deno loads every module that your entry file imports before it runs any of them. + +Your Pi Durable code doesn't change. Every Harness your app opens is traced, whichever storage it uses. + + + +### Control the Data You Send to Sentry (Optional) + + + +To change recording for Pi Durable only, pass `recordInputs` and `recordOutputs` to the integration. They take precedence over `dataCollection`: + +```typescript {filename:main.ts} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [ + Sentry.piDurableIntegration({ + recordInputs: false, + recordOutputs: false, + }), + ], +}); +``` + + + + + + + +## Troubleshooting + +- **No AI spans at all.** Confirm that you start your app with `--preload=npm:@sentry/deno/import` and that `deno.json` sets `nodeModulesDir`. Without the import hook, `@earendil-works/pi-durable` is loaded before `Sentry.init()` runs, so the SDK can't instrument it. +- **Your app stops at start with `NotCapable`.** Deno names the missing permission in the error. The import hook needs `--allow-env` and `--allow-read`. If the error asks for read access to a file in Deno's npm cache, set `nodeModulesDir` in your `deno.json` instead of granting more access. + + + + + +## Supported Versions + +- `@sentry/deno`: `>=11.6.0` +- `@earendil-works/pi-durable`: `>=1.0.0 <2.0.0` +- Deno: `>=2.8.3` diff --git a/docs/platforms/javascript/guides/pi-durable/index.mdx b/docs/platforms/javascript/guides/pi-durable/index.mdx index 45cc4aefb9886..87cbc8b766e5d 100644 --- a/docs/platforms/javascript/guides/pi-durable/index.mdx +++ b/docs/platforms/javascript/guides/pi-durable/index.mdx @@ -4,6 +4,7 @@ description: Learn how to send Pi Durable agent runs, model requests, tool calls sdk: sentry.javascript.node fallbackGuide: javascript.node icon: pi-durable +runtime: node categories: - server - server-only @@ -20,15 +21,13 @@ keywords: -Running Pi Durable in a Cloudflare Durable Object? Follow the [Cloudflare Quick Start](./cloudflare/) instead. - ## Prerequisites Before you begin, you need: - A Sentry [account](https://sentry.io/signup/) and [project](/product/projects/). The project's DSN tells the SDK where to send data. - A Node.js application using `@earendil-works/pi-durable` version `1.0.0` or later. -- `@sentry/node` version `11.6.0` or later, or [`@sentry/cloudflare@^11.6.0` when running on Cloudflare](./cloudflare/). Browser runtimes are not supported. +- `@sentry/node` version `11.6.0` or later. Browser runtimes are not supported. @@ -185,4 +184,6 @@ Sentry.init({ - `@sentry/node`: `>=11.6.0` - `@sentry/cloudflare`: `>=11.6.0` +- `@sentry/deno`: `>=11.6.0` +- `@sentry/bun`: `>=11.6.0` - `@earendil-works/pi-durable`: `>=1.0.0 <2.0.0` diff --git a/docs/platforms/javascript/guides/react-router/bun.mdx b/docs/platforms/javascript/guides/react-router/bun.mdx new file mode 100644 index 0000000000000..3091c54e5c655 --- /dev/null +++ b/docs/platforms/javascript/guides/react-router/bun.mdx @@ -0,0 +1,99 @@ +--- +title: React Router Framework on Bun +sidebar_title: Quick Start (Bun) +sidebar_order: 0.7 +description: Learn how to set up Sentry in your React Router app (v7.15+) that runs on Bun and capture your first errors and traces. +runtime: bun +--- + +This guide sets up Sentry in a React Router app in framework mode that you build with Vite and serve with `react-router-serve` on Bun. At the end, your app sends errors, traces, logs, and session replays to Sentry. + +## Prerequisites + +You need: + +- A Sentry [account](https://sentry.io/signup/) and [project](/product/projects/) +- A React Router app in framework mode, version `7.15.0` or above +- [Bun](https://bun.sh/) + + + +## Install + +Add the Sentry React Router SDK for your app and the Sentry Bun SDK for your server: + +```bash +bun add @sentry/react-router @sentry/bun +``` + +## Configure + +**Error Monitoring** starts working as soon as you call `Sentry.init()`. **Logs** and **Application Metrics** need no extra configuration, and you'll learn how to send them in steps [#3](#send-logs) and [#4](#send-application-metrics-). +This guide also enables **Tracing**, **Session Replay**, and **User Feedback**. + + + + + +### Configure Server-Side Sentry + +Create a file called `instrument.server.mjs` in the root of your project, and initialize Sentry with the Bun SDK. Don't use `Sentry.init()` from `@sentry/react-router` on the server: it's made for Node.js. + +```javascript {filename: instrument.server.mjs} +import * as Sentry from "@sentry/bun"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + // Enables Tracing. + // Set to 1.0 to capture 100% of spans for tracing. + // We recommend reducing this value in production. + tracesSampleRate: 1.0, +}); +``` + + + +To use a Content Security Policy nonce or your own `handleRequest` or `handleError` logic, see the manual setup. + + + +Keep the plugin even if you don't upload source maps: on Bun, it's the only way to get spans for packages such as database clients. You don't need `sentryBunPlugin` from the [Bun guide](/platforms/javascript/guides/bun/). That plugin is for apps that you build with `Bun.build()`, and Vite builds your React Router app. + +### Start Your App + +Preload `instrument.server.mjs` and run the `react-router-serve` script with Bun. Update the `start` script in your `package.json`: + +```json {filename: package.json} +"scripts": { + "start": "bun --preload ./instrument.server.mjs ./node_modules/@react-router/serve/bin.cjs ./build/server/index.js" +} +``` + +Use the path of the script file, not the `react-router-serve` command. With the command, the preloaded file doesn't apply to the server, and Sentry receives no data. + +When the server starts, Bun shows the message `[Sentry] No diagnostics-channel injection detected`. You can ignore it: the Sentry Vite plugin instruments the packages in your server build. + +On Bun, you get no spans for the Express middleware of `react-router-serve`, because Express isn't part of your server build. Errors, request spans, spans for loaders and actions, and outgoing `fetch` requests work. + +### Control the Data You Send to Sentry + + + + + +## Next Steps + +At this point, you should have integrated Sentry into your React Router Framework application on Bun. Here's what to explore next: + +- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup +- Set up tunneling to avoid ad blockers blocking Sentry events +- Learn more about the [Sentry Bun SDK](/platforms/javascript/guides/bun/) + + + +- Find various topics in Troubleshooting +- [Get support](https://www.sentry.help/en/) + + + + diff --git a/docs/platforms/javascript/guides/react-router/cloudflare.mdx b/docs/platforms/javascript/guides/react-router/cloudflare.mdx new file mode 100644 index 0000000000000..4538702ddbb34 --- /dev/null +++ b/docs/platforms/javascript/guides/react-router/cloudflare.mdx @@ -0,0 +1,176 @@ +--- +title: React Router Framework on Cloudflare +sidebar_title: Quick Start (Cloudflare) +sidebar_order: 0.5 +description: Learn how to set up Sentry in your React Router app (v7.15+) deployed on Cloudflare Workers and capture your first errors and traces. +runtime: cloudflare +--- + + + +Using Shopify Hydrogen? Follow the [Hydrogen with React Router](/platforms/javascript/guides/react-router/hydrogen/) guide. + + + +This guide sets up Sentry in a React Router app in framework mode that runs on Cloudflare Workers. At the end, your app sends errors, traces, logs, and session replays to Sentry. The guide is for apps that you build with Vite and `@cloudflare/vite-plugin`, for example an app made with [Cloudflare's React Router guide](https://developers.cloudflare.com/workers/framework-guides/web-apps/react-router/). + +## Prerequisites + +You need: + +- A Sentry [account](https://sentry.io/signup/) and [project](/product/projects/) +- A React Router app in framework mode, version `7.15.0` or above, that uses `@cloudflare/vite-plugin` +- `@sentry/react-router` and `@sentry/cloudflare` version `11.8.0` or above + + + +## Install + +Add the Sentry React Router SDK for your app and the Sentry Cloudflare SDK for your Worker: + +```bash {tabTitle:npm} +npm install @sentry/react-router @sentry/cloudflare --save +``` + +```bash {tabTitle:yarn} +yarn add @sentry/react-router @sentry/cloudflare +``` + +```bash {tabTitle:pnpm} +pnpm add @sentry/react-router @sentry/cloudflare +``` + +## Configure + +**Error Monitoring** starts working as soon as you configure the SDK. **Logs** and **Application Metrics** need no extra configuration, and you'll learn how to send them in steps [#3](#send-logs) and [#4](#send-application-metrics-). +This guide also enables **Tracing**, **Session Replay**, and **User Feedback**. + + + + + +### Configure Server-Side Sentry + +Add `sentryCloudflareVitePlugin` to your `vite.config.ts`, after your other plugins: + +```typescript {filename: vite.config.ts} {diff} +import { cloudflare } from "@cloudflare/vite-plugin"; +import { reactRouter } from "@react-router/dev/vite"; ++import { sentryCloudflareVitePlugin } from "@sentry/cloudflare/vite"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [ + cloudflare({ viteEnvironment: { name: "ssr" } }), + reactRouter(), ++ sentryCloudflareVitePlugin(), + ], +}); +``` + +When Vite builds your app, the plugin wraps the default export of your Worker entry with Sentry. The Worker entry is the file in `main` of your Wrangler configuration, for example `workers/app.ts`, and you don't change it. The plugin also instruments supported packages, such as database clients. + +Create an `instrument.server.ts` file next to your Worker entry, for example `workers/instrument.server.ts`. The plugin uses its default export as the Sentry options: + +```typescript {filename: workers/instrument.server.ts} +import { defineCloudflareOptions } from "@sentry/cloudflare"; + +export default defineCloudflareOptions((env: Env) => ({ + dsn: "___PUBLIC_DSN___", + // Enables Tracing. + // Set to 1.0 to capture 100% of spans for tracing. + // We recommend reducing this value in production. + tracesSampleRate: 1.0, +})); +``` + + + +### Update Your Server Entry + +Replace the content of your `entry.server.tsx` file. Import from `@sentry/react-router/cloudflare`: its `createSentryHandleRequest` renders with `renderToReadableStream`, which works on Workers. + +`handleError` sends server errors to Sentry. `instrumentations` uses React Router's [instrumentation API](https://reactrouter.com/how-to/instrumentation) to create spans for all loaders, actions, middleware, and request handlers, and names each request after its route, for example `GET /users/:id`. + +```tsx {filename: entry.server.tsx} +import * as Sentry from "@sentry/react-router/cloudflare"; +import { renderToReadableStream } from "react-dom/server"; +import { ServerRouter, type HandleErrorFunction } from "react-router"; + +export default Sentry.createSentryHandleRequest({ + ServerRouter, + renderToReadableStream, +}); + +export const handleError: HandleErrorFunction = (error, { request }) => { + // React Router aborts some requests, for example when the user navigates away + if (!request.signal.aborted) { + Sentry.captureException(error); + } +}; + +export const instrumentations = [Sentry.createSentryServerInstrumentation()]; +``` + +### Add Readable Stack Traces With Source Maps + +The `sentryReactRouter` Vite plugin uploads your source maps, so stack traces in Sentry show your original code. Add it after `sentryCloudflareVitePlugin`, and pass both the Sentry options and the Vite configuration to it: + +```typescript {filename: vite.config.ts} {diff} +import { cloudflare } from "@cloudflare/vite-plugin"; +import { reactRouter } from "@react-router/dev/vite"; +import { sentryCloudflareVitePlugin } from "@sentry/cloudflare/vite"; ++import { ++ sentryReactRouter, ++ type SentryReactRouterBuildOptions, ++} from "@sentry/react-router/vite"; +import { defineConfig } from "vite"; + ++const sentryConfig: SentryReactRouterBuildOptions = { ++ org: "___ORG_SLUG___", ++ project: "___PROJECT_SLUG___", ++ ++ // An auth token is required for uploading source maps; ++ // store it in an environment variable to keep it secure. ++ authToken: process.env.SENTRY_AUTH_TOKEN, ++}; + +-export default defineConfig({ ++export default defineConfig((config) => ({ + plugins: [ + cloudflare({ viteEnvironment: { name: "ssr" } }), + reactRouter(), + sentryCloudflareVitePlugin(), ++ sentryReactRouter(sentryConfig, config), + ], +-}); ++})); +``` + + + +### Control the Data You Send to Sentry + + + + + +## Next Steps + +At this point, you should have integrated Sentry into your React Router Framework application on Cloudflare. Here's what to explore next: + +- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup +- Set up tunneling to avoid ad blockers blocking Sentry events +- Learn what the [Sentry Cloudflare Vite plugin](/platforms/javascript/guides/cloudflare/install/vite-plugin/) instruments and how to configure it + + + +- Find various topics in [Cloudflare troubleshooting](/platforms/javascript/guides/cloudflare/troubleshooting/) and React Router troubleshooting +- [Get support](https://www.sentry.help/en/) + + + + diff --git a/docs/platforms/javascript/guides/react-router/deno.mdx b/docs/platforms/javascript/guides/react-router/deno.mdx new file mode 100644 index 0000000000000..59631670f9872 --- /dev/null +++ b/docs/platforms/javascript/guides/react-router/deno.mdx @@ -0,0 +1,109 @@ +--- +title: React Router Framework on Deno +sidebar_title: Quick Start (Deno) +sidebar_order: 0.6 +description: Learn how to set up Sentry in your React Router app (v7.15+) that runs on Deno and capture your first errors and traces. +runtime: deno +--- + +This guide sets up Sentry in a React Router app in framework mode that you build with Vite and serve with `react-router-serve` on Deno. At the end, your app sends errors, traces, logs, and session replays to Sentry. + +## Prerequisites + +You need: + +- A Sentry [account](https://sentry.io/signup/) and [project](/product/projects/) +- A React Router app in framework mode, version `7.15.0` or above, with its dependencies in a `node_modules` folder +- [Deno](https://deno.com/) version `2.9.0` or above + + + +## Install + +Add the Sentry React Router SDK for your app and the Sentry Deno SDK for your server: + +```bash {tabTitle:npm} +npm install @sentry/react-router @sentry/deno --save +``` + +```bash {tabTitle:yarn} +yarn add @sentry/react-router @sentry/deno +``` + +```bash {tabTitle:pnpm} +pnpm add @sentry/react-router @sentry/deno +``` + +## Configure + +**Error Monitoring** starts working as soon as you call `Sentry.init()`. **Logs** and **Application Metrics** need no extra configuration, and you'll learn how to send them in steps [#3](#send-logs) and [#4](#send-application-metrics-). +This guide also enables **Tracing**, **Session Replay**, and **User Feedback**. + + + + + +### Configure Server-Side Sentry + +Create a file called `instrument.server.mjs` in the root of your project, and initialize Sentry with the Deno SDK. Don't use `Sentry.init()` from `@sentry/react-router` on the server: it's made for Node.js. + +```javascript {filename: instrument.server.mjs} +import * as Sentry from "@sentry/deno"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + // Enables Tracing. + // Set to 1.0 to capture 100% of spans for tracing. + // We recommend reducing this value in production. + tracesSampleRate: 1.0, +}); +``` + + + +To use a Content Security Policy nonce or your own `handleRequest` or `handleError` logic, see the manual setup. + + + +### Start Your App + +Run the `react-router-serve` script with Deno, and preload two files: the Sentry import hook (`npm:@sentry/deno/import`), which instruments the packages that Deno loads from `node_modules`, such as Express, and then `instrument.server.mjs`. Update the `start` script in your `package.json`: + +```json {filename: package.json} +"scripts": { + "start": "deno run --preload=npm:@sentry/deno/import --preload=./instrument.server.mjs --allow-net --allow-env --allow-read=. --allow-sys=hostname,osRelease,networkInterfaces ./node_modules/@react-router/serve/bin.cjs ./build/server/index.js" +} +``` + +Deno blocks access to the network, the file system, and system information until you grant it: + +| Flag | What it gives you | +| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `--allow-net` | The server port, and the delivery of events to Sentry. | +| `--allow-env` | The import hook and `react-router-serve`, which read environment variables. | +| `--allow-read=.` | The import hook, your server build, and the packages in `node_modules`. | +| `--allow-sys=hostname,osRelease,networkInterfaces` | The server name and the operating system version on events. `react-router-serve` needs `networkInterfaces` to start. | + +### Control the Data You Send to Sentry + + + + + +## Next Steps + +At this point, you should have integrated Sentry into your React Router Framework application on Deno. Here's what to explore next: + +- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup +- Set up tunneling to avoid ad blockers blocking Sentry events +- Learn more about the [Sentry Deno SDK](/platforms/javascript/guides/deno/) + + + +- If your app stops at start with `NotCapable`, Deno names the missing permission in the error. Add it to the `start` script. +- Find various topics in Troubleshooting +- [Get support](https://www.sentry.help/en/) + + + + diff --git a/docs/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router.mdx b/docs/platforms/javascript/guides/react-router/hydrogen.mdx similarity index 97% rename from docs/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router.mdx rename to docs/platforms/javascript/guides/react-router/hydrogen.mdx index 1c8207e0757e1..3bba22f1b5596 100644 --- a/docs/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router.mdx +++ b/docs/platforms/javascript/guides/react-router/hydrogen.mdx @@ -1,11 +1,14 @@ --- title: Hydrogen with React Router +h1_title: Hydrogen with React Router +sidebar_title: Quick Start (Hydrogen) +sidebar_order: 0.5 description: Learn how to instrument your Hydrogen app on Shopify Oxygen and capture your first errors and traces. --- -This guide applies to Hydrogen versions **2025.5.0 and later** that use React Router 7 (framework mode). For older versions of Hydrogen that use Remix v2, see our [Remix on Cloudflare guide](/platforms/javascript/guides/cloudflare/frameworks/hydrogen-remix/). +This guide applies to Hydrogen versions **2025.5.0 and later** that use React Router 7 (framework mode). For older versions of Hydrogen that use Remix v2, see the [Hydrogen with Remix guide](/platforms/javascript/guides/remix/hydrogen/). @@ -367,7 +370,7 @@ Now, head over to your project on [Sentry.io](https://sentry.io) to view the col ## Next Steps -At this point, you should have integrated Sentry into your React Router Framework application and should already be sending data to your Sentry project. +At this point, you should have integrated Sentry into your Hydrogen application and should already be sending data to your Sentry project. Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are: diff --git a/docs/platforms/javascript/guides/react-router/index.mdx b/docs/platforms/javascript/guides/react-router/index.mdx index 27fcb45648a80..ea3afcb8641f6 100644 --- a/docs/platforms/javascript/guides/react-router/index.mdx +++ b/docs/platforms/javascript/guides/react-router/index.mdx @@ -5,6 +5,7 @@ sdk: sentry.javascript.react-router categories: - browser - server +runtime: node --- Set up tunneling to avoid ad blockers blocking Sentry events +- Set up tunneling to avoid ad blockers blocking Sentry events - Read the manual setup guide for advanced configuration diff --git a/docs/platforms/javascript/guides/react-router/manual-setup.mdx b/docs/platforms/javascript/guides/react-router/manual-setup.mdx index aec0eda1e8064..04515d4afacca 100644 --- a/docs/platforms/javascript/guides/react-router/manual-setup.mdx +++ b/docs/platforms/javascript/guides/react-router/manual-setup.mdx @@ -34,76 +34,7 @@ This guide also enables **Tracing**, **Profiling**, **Session Replay**, and **Us -### Expose Entry Point Files - -Before configuring Sentry, you need to make React Router's entry files (`entry.client.tsx` and `entry.server.tsx`) visible in your project. Run this command to expose them: - -```bash -npx react-router reveal -``` - -### Configure Client-Side Sentry - -Initialize Sentry in your `entry.client.tsx` file. - -The snippet also turns on: - -- Tracing: via `tracesSampleRate` and `reactRouterTracingIntegration()` -- Session Replay: via `replayIntegration()`, sampled with `replaysSessionSampleRate` and `replaysOnErrorSampleRate` -- User Feedback: via `feedbackIntegration()` - -Don't need a feature? Remove its integration and options from the snippet. - -The `sentryOnError` handler integrates with React Router's [`onError` hook](https://reactrouter.com/how-to/error-reporting) to automatically capture and report client-side errors to Sentry. - -```tsx {filename: entry.client.tsx} -import * as Sentry from "@sentry/react-router"; -import { startTransition, StrictMode } from "react"; -import { hydrateRoot } from "react-dom/client"; -import { HydratedRouter } from "react-router/dom"; - -Sentry.init({ - dsn: "___PUBLIC_DSN___", - - integrations: [ - // Registers and configures the Tracing integration, - // which automatically instruments your application to monitor its - // performance, including custom React Router routing instrumentation - Sentry.reactRouterTracingIntegration(), - // Registers the Replay integration, - // which automatically captures Session Replays - Sentry.replayIntegration(), - // Registers the User Feedback integration - Sentry.feedbackIntegration({ - // Additional SDK configuration goes in here, for example: - colorScheme: "system", - }), - ], - - // Enables Tracing. - // Set to 1.0 to capture 100% of spans for tracing. - // We recommend reducing this value in production. - tracesSampleRate: 1.0, - - // Set `tracePropagationTargets` to declare which URL(s) should have trace propagation enabled - tracePropagationTargets: [/^\//, /^https:\/\/yourserver\.io\/api/], - - // Capture replays for 10% of all sessions, - // plus for 100% of sessions with an error - // Requires Sentry.replayIntegration() - replaysSessionSampleRate: 0.1, - replaysOnErrorSampleRate: 1.0, -}); - -startTransition(() => { - hydrateRoot( - document, - - - - ); -}); -``` + ### Configure Server-Side Sentry @@ -147,35 +78,7 @@ Sentry.init({ }); ``` -Next, replace the default `handleRequest` and `handleError` functions in your `entry.server.tsx` file with Sentry's wrapped versions, and export `instrumentations` to enable automatic tracing. - -Exporting `instrumentations` uses React Router's [instrumentation API](https://reactrouter.com/how-to/instrumentation) to automatically create spans for all loaders, actions, middleware, and request handlers — no need to wrap them individually. - -```tsx {diff} {filename: entry.server.tsx} -+import * as Sentry from '@sentry/react-router'; - import { createReadableStreamFromReadable } from '@react-router/node'; - import { renderToPipeableStream } from 'react-dom/server'; - import { ServerRouter } from 'react-router'; - import { type HandleErrorFunction } from 'react-router'; - -+const handleRequest = Sentry.createSentryHandleRequest({ -+ ServerRouter, -+ renderToPipeableStream, -+ createReadableStreamFromReadable, -+}); - - export default handleRequest; - -+export const handleError = Sentry.createSentryHandleError({ -+ logErrors: false -+}); - -+// Automatically instruments all server loaders, actions, middleware, -+// and request handlers. -+export const instrumentations = [Sentry.createSentryServerInstrumentation()]; - -// ... rest of your server entry -``` + @@ -357,59 +260,7 @@ When you import the instrumentation file directly instead of using the `--import -### Add Readable Stack Traces With Source Maps - -The stack traces in your Sentry errors probably won't look like your actual code without unminifying them. To fix this, upload your source maps to Sentry. - -First, update `vite.config.ts` to include the `sentryReactRouter` plugin, making sure to pass both the Vite and Sentry configurations to it: - -```typescript {filename: vite.config.ts} {diff} -import { reactRouter } from '@react-router/dev/vite'; -import { sentryReactRouter, type SentryReactRouterBuildOptions } from '@sentry/react-router/vite'; -import { defineConfig } from 'vite'; - -const sentryConfig: SentryReactRouterBuildOptions = { - org: "___ORG_SLUG___", - project: "___PROJECT_SLUG___", - - // An auth token is required for uploading source maps; - // store it in an environment variable to keep it secure. - authToken: process.env.SENTRY_AUTH_TOKEN, - // ... -}; - -export default defineConfig(config => { - return { -+ plugins: [reactRouter(),sentryReactRouter(sentryConfig, config)], - }; -}); -``` - -To keep your auth token secure, always store it in an environment variable instead of directly in your files: - - - -```bash {filename:.env} -SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ -``` - - - -Next, include the `sentryOnBuildEnd` hook in `react-router.config.ts`: - -```typescript {filename: react-router.config.ts} {diff} -import type { Config } from "@react-router/dev/config"; -import { sentryOnBuildEnd } from "@sentry/react-router/vite"; - -export default { - ssr: true, - buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { - // ... - // Call this at the end of the hook -+ await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); - }, -} satisfies Config; -``` + ### Control the Data You Send to Sentry @@ -458,7 +309,7 @@ Now, head over to your project on [Sentry.io](https://sentry.io) to view the col At this point, you should have integrated Sentry into your React Router Framework application. Here's what to explore next: - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Set up tunneling to avoid ad blockers blocking Sentry events +- Set up tunneling to avoid ad blockers blocking Sentry events - Set up Agent Tracing to monitor your AI systems diff --git a/docs/platforms/javascript/guides/react/index.mdx b/docs/platforms/javascript/guides/react/index.mdx index f44073a9ba55a..4b2bc7300c0a9 100644 --- a/docs/platforms/javascript/guides/react/index.mdx +++ b/docs/platforms/javascript/guides/react/index.mdx @@ -276,7 +276,7 @@ Now, head over to your project on [Sentry.io](https://sentry.io) to view the col At this point, you should have integrated Sentry into your React application. Here's what to explore next: - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Set up tunneling to avoid ad blockers from blocking Sentry events +- Set up tunneling to avoid ad blockers from blocking Sentry events - Explore React-specific features diff --git a/docs/platforms/javascript/guides/cloudflare/frameworks/remix.mdx b/docs/platforms/javascript/guides/remix/cloudflare.mdx similarity index 68% rename from docs/platforms/javascript/guides/cloudflare/frameworks/remix.mdx rename to docs/platforms/javascript/guides/remix/cloudflare.mdx index dc987930018ab..af5ff202c54c0 100644 --- a/docs/platforms/javascript/guides/cloudflare/frameworks/remix.mdx +++ b/docs/platforms/javascript/guides/remix/cloudflare.mdx @@ -1,12 +1,18 @@ --- title: Remix on Cloudflare +sidebar_title: Quick Start (Cloudflare) +sidebar_order: 0.5 description: "Learn how to instrument your Remix app on Cloudflare Workers and Pages and capture your first errors with Sentry." +runtime: cloudflare --- - + + +Using Shopify Hydrogen? Follow the [Hydrogen with React Router](/platforms/javascript/guides/react-router/hydrogen/) guide for Hydrogen 2025.5.0 and later, or the [Hydrogen with Remix](/platforms/javascript/guides/remix/hydrogen/) guide for older versions. + + + + @@ -43,9 +49,6 @@ yarn add @sentry/remix @sentry/cloudflare pnpm add @sentry/remix @sentry/cloudflare ``` - + diff --git a/docs/platforms/javascript/guides/remix/frameworks/index.mdx b/docs/platforms/javascript/guides/remix/frameworks/index.mdx deleted file mode 100644 index a72e5adcc00f7..0000000000000 --- a/docs/platforms/javascript/guides/remix/frameworks/index.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Cloudflare SDK Guide -description: "Learn how to set up the Remix SDK or Hydrogen with Cloudflare." ---- - -You can use the Sentry Remix SDK to set up Sentry with frameworks like Shopify's Hydrogen. The following guides will help you get started with the Sentry Remix SDK on Cloudflare: - -- **[Remix on Cloudflare](/platforms/javascript/guides/cloudflare/frameworks/remix/)** -- **[Hydrogen on Cloudflare](/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router/)** diff --git a/docs/platforms/javascript/guides/cloudflare/frameworks/hydrogen-remix.mdx b/docs/platforms/javascript/guides/remix/hydrogen.mdx similarity index 96% rename from docs/platforms/javascript/guides/cloudflare/frameworks/hydrogen-remix.mdx rename to docs/platforms/javascript/guides/remix/hydrogen.mdx index 1a8dcd0432c7d..b9be1f785653b 100644 --- a/docs/platforms/javascript/guides/cloudflare/frameworks/hydrogen-remix.mdx +++ b/docs/platforms/javascript/guides/remix/hydrogen.mdx @@ -1,11 +1,13 @@ --- title: Hydrogen with Remix (Legacy) +sidebar_title: Hydrogen (Legacy) +sidebar_order: 1.5 description: Learn how to use the Sentry Remix SDK to instrument your Hydrogen app (versions before 2025.5.0). --- -This guide applies to Hydrogen versions **before 2025.5.0** that use Remix v2. For newer versions of Hydrogen (2025.5.0+) that use React Router 7, see the [React Router guide](/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router/). +This guide applies to Hydrogen versions **before 2025.5.0** that use Remix v2. For newer versions of Hydrogen (2025.5.0+) that use React Router 7, see the [Hydrogen with React Router guide](/platforms/javascript/guides/react-router/hydrogen/). @@ -39,7 +41,7 @@ On Shopify Oxygen, never import anything directly from `@sentry/cloudflare`. Onl -`wrapRequestHandler` doesn't isolate requests from each other. Scope data you set during a request, for example with `setTag` or `setUser`, can show up on events from other concurrent or later requests in the same isolate. Use `wrapRequestHandler` only on runtimes that can't enable `nodejs_compat`, such as Shopify Oxygen. For Remix on Cloudflare Workers, follow the [Remix on Cloudflare guide](/platforms/javascript/guides/cloudflare/frameworks/remix/) instead. +`wrapRequestHandler` doesn't isolate requests from each other. Scope data you set during a request, for example with `setTag` or `setUser`, can show up on events from other concurrent or later requests in the same isolate. Use `wrapRequestHandler` only on runtimes that can't enable `nodejs_compat`, such as Shopify Oxygen. For Remix on Cloudflare Workers, follow the [Remix on Cloudflare guide](/platforms/javascript/guides/remix/cloudflare/) instead. diff --git a/docs/platforms/javascript/guides/remix/index.mdx b/docs/platforms/javascript/guides/remix/index.mdx index cd0ddc7968c5e..57df3cf6f3d06 100644 --- a/docs/platforms/javascript/guides/remix/index.mdx +++ b/docs/platforms/javascript/guides/remix/index.mdx @@ -5,6 +5,7 @@ sdk: sentry.javascript.remix categories: - browser - server +runtime: node --- diff --git a/docs/platforms/javascript/guides/solid/index.mdx b/docs/platforms/javascript/guides/solid/index.mdx index 4cfd9c1810a37..3f68538c33adc 100644 --- a/docs/platforms/javascript/guides/solid/index.mdx +++ b/docs/platforms/javascript/guides/solid/index.mdx @@ -152,7 +152,7 @@ Now, head over to your project on [Sentry.io](https://sentry.io/) to view the co At this point, you should have integrated Sentry into your Solid application. Here's what to explore next: - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Set up tunneling to avoid ad blockers from blocking Sentry events +- Set up tunneling to avoid ad blockers from blocking Sentry events - Explore Solid-specific features diff --git a/docs/platforms/javascript/guides/solidstart/index.mdx b/docs/platforms/javascript/guides/solidstart/index.mdx index f7c7a9f1baade..bb69e18cc532d 100644 --- a/docs/platforms/javascript/guides/solidstart/index.mdx +++ b/docs/platforms/javascript/guides/solidstart/index.mdx @@ -369,7 +369,7 @@ At this point, you should have integrated Sentry into your SolidStart applicatio - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup - Set up Agent Tracing to monitor your AI systems -- Set up tunneling to avoid ad blockers blocking Sentry events +- Set up tunneling to avoid ad blockers blocking Sentry events diff --git a/docs/platforms/javascript/guides/svelte/index.mdx b/docs/platforms/javascript/guides/svelte/index.mdx index 1931db3436219..3a50e8b42a42e 100644 --- a/docs/platforms/javascript/guides/svelte/index.mdx +++ b/docs/platforms/javascript/guides/svelte/index.mdx @@ -192,7 +192,7 @@ Now, head over to your project on [Sentry.io](https://sentry.io/) to view the co At this point, you should have integrated Sentry into your Svelte application. Here's what to explore next: - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Set up tunneling to avoid ad blockers from blocking Sentry events +- Set up tunneling to avoid ad blockers from blocking Sentry events - Explore Svelte-specific features diff --git a/docs/platforms/javascript/guides/cloudflare/frameworks/sveltekit.mdx b/docs/platforms/javascript/guides/sveltekit/cloudflare.mdx similarity index 55% rename from docs/platforms/javascript/guides/cloudflare/frameworks/sveltekit.mdx rename to docs/platforms/javascript/guides/sveltekit/cloudflare.mdx index 340bf50fa9f29..884a4c005303f 100644 --- a/docs/platforms/javascript/guides/cloudflare/frameworks/sveltekit.mdx +++ b/docs/platforms/javascript/guides/sveltekit/cloudflare.mdx @@ -1,9 +1,9 @@ --- title: SvelteKit on Cloudflare +sidebar_title: Quick Start (Cloudflare) +sidebar_order: 0.5 description: "Learn how to instrument your SvelteKit app on Cloudflare Workers and Pages and capture your first errors with Sentry." +runtime: cloudflare --- - + diff --git a/docs/platforms/javascript/guides/sveltekit/index.mdx b/docs/platforms/javascript/guides/sveltekit/index.mdx index 02bb0201d9913..67b2a730cd6f1 100644 --- a/docs/platforms/javascript/guides/sveltekit/index.mdx +++ b/docs/platforms/javascript/guides/sveltekit/index.mdx @@ -5,6 +5,7 @@ sdk: sentry.javascript.sveltekit categories: - browser - server +runtime: node --- @@ -70,7 +71,7 @@ Our next recommended steps for you are: - Learn how to [manually capture errors](/platforms/javascript/guides/sveltekit/usage/) - Continue to [customize your configuration](/platforms/javascript/guides/sveltekit/configuration/) - Learn how to [manually instrument](/platforms/javascript/guides/sveltekit/apis/#load-function-instrumentation) SvelteKit-specific features -- Learn more about [deploying SvelteKit apps to Cloudflare Pages](/platforms/javascript/guides/cloudflare/frameworks/sveltekit/) +- Learn more about [deploying SvelteKit apps to Cloudflare Pages](/platforms/javascript/guides/sveltekit/cloudflare/) - Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts diff --git a/docs/platforms/javascript/guides/sveltekit/manual-setup__v10.7.0.mdx b/docs/platforms/javascript/guides/sveltekit/manual-setup__v10.7.0.mdx index 11ff9ddc7ae5f..f83502f74828c 100644 --- a/docs/platforms/javascript/guides/sveltekit/manual-setup__v10.7.0.mdx +++ b/docs/platforms/javascript/guides/sveltekit/manual-setup__v10.7.0.mdx @@ -27,7 +27,7 @@ Here's an overview of the current support: - [Adapter-vercel](https://kit.svelte.dev/docs/adapter-vercel) when used with Vercel's Node.js Lambda runtime - [Adapter-node](https://kit.svelte.dev/docs/adapter-node) - **Supported non-Node.js runtimes** - - [Adapter-cloudflare](https://kit.svelte.dev/docs/adapter-cloudflare) requires [additional setup](/platforms/javascript/guides/cloudflare/frameworks/sveltekit/) + - [Adapter-cloudflare](https://kit.svelte.dev/docs/adapter-cloudflare) requires [additional setup](/platforms/javascript/guides/sveltekit/cloudflare/) - **Currently not supported** - Non-Node.js server runtimes, such as Vercel's edge runtime, are not yet supported. - **Other adapters** @@ -326,7 +326,7 @@ Our next recommended steps for you are: - Learn how to [manually capture errors](/platforms/javascript/guides/sveltekit/usage/) - Continue to [customize your configuration](/platforms/javascript/guides/sveltekit/configuration/) - Learn how to [manually instrument](/platforms/javascript/guides/sveltekit/apis/#load-function-instrumentation) SvelteKit-specific features -- Learn more about [deploying SvelteKit apps to Cloudflare Pages](/platforms/javascript/guides/cloudflare/frameworks/sveltekit/) +- Learn more about [deploying SvelteKit apps to Cloudflare Pages](/platforms/javascript/guides/sveltekit/cloudflare/) - Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts diff --git a/docs/platforms/javascript/guides/cloudflare/frameworks/tanstack-start.mdx b/docs/platforms/javascript/guides/tanstackstart-react/cloudflare.mdx similarity index 89% rename from docs/platforms/javascript/guides/cloudflare/frameworks/tanstack-start.mdx rename to docs/platforms/javascript/guides/tanstackstart-react/cloudflare.mdx index 11fb6d6d40330..fa90ff7c0bb6e 100644 --- a/docs/platforms/javascript/guides/cloudflare/frameworks/tanstack-start.mdx +++ b/docs/platforms/javascript/guides/tanstackstart-react/cloudflare.mdx @@ -1,13 +1,16 @@ --- -title: TanStack Start on Cloudflare +title: TanStack Start React on Cloudflare +sidebar_title: Quick Start (Cloudflare) +sidebar_order: 0.5 description: "Learn how to instrument your TanStack Start app on Cloudflare Workers and capture your first errors with Sentry." +runtime: cloudflare --- -This guide is for TanStack Start deployed to **Cloudflare Workers** using the `@cloudflare/vite-plugin`. For Node.js-based deployments, see our [TanStack Start guide](/platforms/javascript/guides/tanstackstart-react/). +This guide is for TanStack Start deployed to **Cloudflare Workers** using the `@cloudflare/vite-plugin`. @@ -30,9 +33,19 @@ Choose the features you want to configure, and this guide will show you how: ### Install the Sentry SDK -Run the command for your preferred package manager to add the Sentry SDK to your application: +Run the command for your preferred package manager to add the Sentry TanStack Start and Cloudflare SDKs to your application: - +```bash {tabTitle:npm} +npm install @sentry/tanstackstart-react @sentry/cloudflare --save +``` + +```bash {tabTitle:yarn} +yarn add @sentry/tanstackstart-react @sentry/cloudflare +``` + +```bash {tabTitle:pnpm} +pnpm add @sentry/tanstackstart-react @sentry/cloudflare +``` ## Configure @@ -42,7 +55,7 @@ When deploying TanStack Start to Cloudflare Workers, you need to wrap the server ### Create a Custom Server Entry @@ -166,8 +179,8 @@ export const startInstance = createStart(() => { ### Add Readable Stack Traces With Source Maps (Optional) ### Control the Data You Send to Sentry (Optional) @@ -223,8 +236,8 @@ Now's a good time to customize your setup and look into more advanced topics. Ou -- Check out setup instructions for other popular [frameworks on Cloudflare](/platforms/javascript/guides/cloudflare/frameworks/) -- Find various support topics in troubleshooting +- Check out setup instructions for other popular [frameworks on Cloudflare](/platforms/javascript/guides/cloudflare/#framework-selector) +- Find various support topics in [Cloudflare troubleshooting](/platforms/javascript/guides/cloudflare/troubleshooting/) - [Get support](https://www.sentry.help/en/) diff --git a/docs/platforms/javascript/guides/tanstackstart-react/features/createSentryTunnelRoute.mdx b/docs/platforms/javascript/guides/tanstackstart-react/features/createSentryTunnelRoute.mdx index d3244d9717c84..6b4709fc0937f 100644 --- a/docs/platforms/javascript/guides/tanstackstart-react/features/createSentryTunnelRoute.mdx +++ b/docs/platforms/javascript/guides/tanstackstart-react/features/createSentryTunnelRoute.mdx @@ -6,14 +6,13 @@ description: "Learn how to manually define a Sentry tunnel route in your TanStac - If you can use the `sentryTanstackStart` Vite plugin, prefer its - [`tunnelRoute`](/platforms/javascript/guides/tanstackstart-react/features/sentryTanstackStart/#tunnel-route) - option. It registers the route for you and automatically wires up the client - `tunnel` option. Use `createSentryTunnelRoute` only when you need full control over - the route file, the DSN allowlist, or can't use the Vite plugin. + For most apps, set up the tunnel as described in{" "} + Tunneling, which + needs no route file. Use `createSentryTunnelRoute` only when you want the + tunnel as a route in your app. -The `createSentryTunnelRoute` helper returns a TanStack Start server-route configuration with a `POST` handler that forwards Sentry envelopes to Sentry's ingest servers. Use it inside a file route to expose a same-origin tunnel endpoint. It forwards only the request body to Sentry. +The `createSentryTunnelRoute` helper returns a TanStack Start server-route configuration with a `POST` handler that forwards Sentry envelopes to Sentry's ingest servers. Use it inside a file route to expose a same-origin tunnel endpoint. ## Usage @@ -46,7 +45,7 @@ Sentry.init({ A list of DSN strings that the route is allowed to forward to. The route validates each incoming envelope against this list and rejects any DSN that isn't allowed. -If `allowedDsns` is omitted or empty, the route falls back to the DSN of the active server-side Sentry SDK at runtime. If neither is available, requests to the route return a 500 response. +The DSN of the active server-side Sentry SDK is always allowed too. If `allowedDsns` is omitted or empty, the route uses only that DSN. If neither is available, requests to the route return a 500 response. ```typescript {filename:src/routes/monitor.ts} Sentry.createSentryTunnelRoute({ diff --git a/docs/platforms/javascript/guides/tanstackstart-react/features/sentryTanstackStart.mdx b/docs/platforms/javascript/guides/tanstackstart-react/features/sentryTanstackStart.mdx index 5663884faf889..3d7519f76951f 100644 --- a/docs/platforms/javascript/guides/tanstackstart-react/features/sentryTanstackStart.mdx +++ b/docs/platforms/javascript/guides/tanstackstart-react/features/sentryTanstackStart.mdx @@ -97,56 +97,11 @@ sentryTanstackStart({ -The `tunnelRoute` option registers a same-origin TanStack Start server route that forwards Sentry envelopes to Sentry's ingest servers. It also automatically sets the client `tunnel` option in `Sentry.init()` so browser events go through that route. This helps avoid ad blockers and corporate firewalls that block requests to `*.sentry.io`. It forwards only the request body to Sentry. - -`tunnelRoute` accepts three shapes: - -#### `tunnelRoute: true` (recommended) - -Generates an opaque, unguessable route path for each dev session and production build. Because the path changes between builds, ad blockers can't reliably target it. - -```typescript {filename:vite.config.ts} -sentryTanstackStart({ - tunnelRoute: true, -}), -``` - -#### Static path - -Pass a string to use a fixed route path. This is easier to reason about, but a known path is easier for ad blockers to add to a list. - -```typescript {filename:vite.config.ts} -sentryTanstackStart({ - tunnelRoute: "/monitor", -}), -``` - -#### Object form - -Use the object form to control the DSN allowlist or set a static path explicitly: - -```typescript {filename:vite.config.ts} -sentryTanstackStart({ - tunnelRoute: { - allowedDsns: ["___PUBLIC_DSN___"], - path: "/monitor", - }, -}), -``` - -- **`allowedDsns`** — only envelopes targeting one of these DSNs are forwarded. If omitted or empty, the route falls back to the DSN of the active server-side Sentry SDK at runtime. -- **`path`** — the public route path. If omitted, an opaque path is generated (same behavior as `tunnelRoute: true`). - - - If you also pass `tunnel` to `Sentry.init()`, the runtime option wins and the - managed tunnel route is bypassed. The SDK logs a warning when this happens. + + This option is deprecated and will be removed in v12. Set `tunnel: true` in + the browser and add `serveTunnelIntegration` on the server instead, as + described in{" "} + Tunneling. - - When using `tunnelRoute: true` (or the object form without `path`), the - generated path changes for each dev session and each production build. Don't - hard-code it elsewhere in your app or infrastructure. - +The `tunnelRoute` option serves a tunnel on your own origin that forwards browser events to Sentry, so ad blockers don't drop them. It also sets the browser `tunnel` option for you. diff --git a/docs/platforms/javascript/guides/tanstackstart-react/index.mdx b/docs/platforms/javascript/guides/tanstackstart-react/index.mdx index 88566aa84c18e..8258b94d3ac1e 100644 --- a/docs/platforms/javascript/guides/tanstackstart-react/index.mdx +++ b/docs/platforms/javascript/guides/tanstackstart-react/index.mdx @@ -5,6 +5,7 @@ sdk: sentry.javascript.tanstackstart-react categories: - server - browser +runtime: node --- diff --git a/docs/platforms/javascript/guides/tanstackstart-react/manual-setup/index.mdx b/docs/platforms/javascript/guides/tanstackstart-react/manual-setup/index.mdx index a9c893db8c249..5ca2e5dc204cd 100644 --- a/docs/platforms/javascript/guides/tanstackstart-react/manual-setup/index.mdx +++ b/docs/platforms/javascript/guides/tanstackstart-react/manual-setup/index.mdx @@ -366,28 +366,15 @@ If you need more control over the upload process, see our [source maps guide](/p ### Avoid Ad Blockers With Tunneling (Optional) -Ad blockers and corporate firewalls often block requests to `*.sentry.io`, which can cause events to be dropped before they reach Sentry. To work around this, you can tunnel events through a same-origin route in your TanStack Start app. +Ad blockers and corporate firewalls often block requests to `*.sentry.io`, which can cause events to be dropped before they reach Sentry. To work around this, send them through a tunnel on your own origin. -The `sentryTanstackStart` Vite plugin can register a tunnel route for you and automatically wire up the client `tunnel` option. +Set `tunnel: true` in your browser `Sentry.init`, and add `serveTunnelIntegration` to your server `Sentry.init`: -Setting `tunnelRoute: true` generates an opaque route for each dev session and production build, making it harder for ad blockers to target. See the [`sentryTanstackStart`](/platforms/javascript/guides/tanstackstart-react/features/sentryTanstackStart/#tunnel-route) feature page for static paths and the full set of options. + -If you can't use the Vite plugin, or need full control over the route file and DSN allowlist, use [`createSentryTunnelRoute`](/platforms/javascript/guides/tanstackstart-react/features/createSentryTunnelRoute/) to define the route yourself. + -```typescript {filename:vite.config.ts} {9} -import { defineConfig } from "vite"; -import { tanstackStart } from "@tanstack/react-start/plugin/vite"; -import { sentryTanstackStart } from "@sentry/tanstackstart-react/vite"; - -export default defineConfig({ - plugins: [ - tanstackStart(), - sentryTanstackStart({ - tunnelRoute: true, - }), - ], -}); -``` +Learn more in Tunneling. ### Control the Data You Send to Sentry (Optional) diff --git a/docs/platforms/javascript/guides/vue/index.mdx b/docs/platforms/javascript/guides/vue/index.mdx index fe85f766b3816..7d1102360a9e6 100644 --- a/docs/platforms/javascript/guides/vue/index.mdx +++ b/docs/platforms/javascript/guides/vue/index.mdx @@ -232,7 +232,7 @@ Now, head over to your project on [Sentry.io](https://sentry.io/) to view the co At this point, you should have integrated Sentry into your Vue application. Here's what to explore next: - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Set up tunneling to avoid ad blockers from blocking Sentry events +- Set up tunneling to avoid ad blockers from blocking Sentry events - Explore Vue-specific features diff --git a/docs/platforms/python/agent-tracing/anthropic/index.mdx b/docs/platforms/python/agent-tracing/anthropic/index.mdx index 6055f79c34d59..cee1a9520dbe8 100644 --- a/docs/platforms/python/agent-tracing/anthropic/index.mdx +++ b/docs/platforms/python/agent-tracing/anthropic/index.mdx @@ -43,8 +43,8 @@ sentry_sdk.init(...) # same as above client = Anthropic(api_key="(your Anthropic key)") def my_llm_stuff(): - # or sentry_sdk.traces.start_span(name="The result of the AI inference", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="The result of the AI inference"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="The result of the AI inference") instead + with sentry_sdk.start_span(name="The result of the AI inference"): print( client.messages.create( model="claude-3-5-sonnet-20240620", @@ -68,7 +68,7 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se - The supported function is currently `messages.create` (both sync and async). -- Sentry considers LLM inputs/outputs as PII (Personally identifiable information) and doesn't include prompts, messages, or responses by default. Tool definitions are still attached by default; setting `inputs` to `False` in the `gen_ai` key described below removes them. To include prompts, messages, and responses, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately. When you pass a `data_collection` dictionary, both are collected by default and `include_prompts` is ignored: +- By default, the SDK records LLM inputs and outputs, such as prompts, messages, responses, and tool definitions. To control this, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately: ```python sentry_sdk.init( @@ -80,10 +80,16 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se ) ``` - Alternatively, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False` as shown in the [Options section](#options) below. `send_default_pii` will be removed in version 3.0 of the SDK. + In SDK versions prior to `3.0`, Sentry considers LLM inputs and outputs as PII and doesn't include prompts, messages, or responses unless you pass a `data_collection` dictionary or set `send_default_pii=True`. With `send_default_pii=True`, you can exclude them with the integration's `include_prompts=False` option, as shown in the [Options section](#options) below. ## Options + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, `AnthropicIntegration` doesn't accept any options. Use the `gen_ai` key of the `data_collection` option instead. + + + By adding `AnthropicIntegration` to your `sentry_sdk.init()` call explicitly, you can set options for `AnthropicIntegration` to change its behavior: ```python @@ -109,7 +115,7 @@ You can pass the following keyword arguments to `AnthropicIntegration()`: Whether LLM inputs and outputs should be sent to Sentry. If you use the `data_collection` option, this option is ignored. Use the `gen_ai` key instead. - Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. `send_default_pii` will be removed in version 3.0 of the SDK. + Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. The default is `True`. diff --git a/docs/platforms/python/agent-tracing/bedrock/index.mdx b/docs/platforms/python/agent-tracing/bedrock/index.mdx new file mode 100644 index 0000000000000..20cfca5159ad2 --- /dev/null +++ b/docs/platforms/python/agent-tracing/bedrock/index.mdx @@ -0,0 +1,101 @@ +--- +title: Amazon Bedrock +description: "Learn about using Sentry for Amazon Bedrock." +sidebar_order: 31 +--- + +This integration connects Sentry with [Amazon Bedrock](https://aws.amazon.com/bedrock/) calls made through the [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) `bedrock-runtime` client. + +Once you've installed this SDK, you can use the Sentry Agents Tracing, a Sentry dashboard that helps you understand what's going on with your AI requests. + +Sentry AI Observability will automatically collect information about prompts, tools, tokens, and models. Learn more about the [Agents Dashboard](/product/agents/dashboards/). + + + +## Install + +Install `sentry-sdk` from PyPI: + +```bash {tabTitle:pip} +pip install sentry-sdk +``` + +```bash {tabTitle:uv} +uv add sentry-sdk +``` + +## Configure + +Add `Boto3Integration()` to your `integrations` list: + +```python +import sentry_sdk +from sentry_sdk.integrations.boto3 import Boto3Integration + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + # Set traces_sample_rate to 1.0 to capture 100% + # of transactions for tracing. + traces_sample_rate=1.0, + # Check https://docs.sentry.io/platforms/python/data-management/data-collected/ to configure what data is collected + data_collection={ + "gen_ai": {"inputs": True, "outputs": True}, + }, + integrations=[ + Boto3Integration(), + ], +) +``` + +## Verify + +Verify that the integration works by making a chat request to Bedrock. + +```python +import boto3 +import sentry_sdk + +sentry_sdk.init(...) # same as above + +client = boto3.client("bedrock-runtime", region_name="us-east-1") + +def my_llm_stuff(): + # In SDK 2.x, use sentry_sdk.start_transaction(name="The result of the AI inference") instead + with sentry_sdk.start_span(name="The result of the AI inference"): + response = client.converse( + modelId="us.anthropic.claude-haiku-4-5-20251001-v1:0", + messages=[ + { + "role": "user", + "content": [{"text": "Tell me a short story about a robot."}], + } + ], + ) + print(response["output"]["message"]["content"][0]["text"]) +``` + +After running this script, the resulting data should show up in the `AI Spans` tab on the `Explore > Traces > Trace` page on Sentry.io. + +If you manually created an Invoke Agent Span (not done in the example above) the data will also show up in the [Agents Dashboard](/product/agents/dashboards/). + +It may take a couple of moments for the data to appear in [sentry.io](https://sentry.io). + +## Behavior + +- The Boto3 integration will connect Sentry with the supported Bedrock methods automatically. + +- The supported methods are currently `converse` and `converse_stream` on the `bedrock-runtime` client. + +- By default, the SDK records LLM inputs and outputs, such as prompts, messages, and responses. Tool definitions are recorded too; setting `inputs` to `False` in the `gen_ai` key removes them. To control this, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately: + + ```python + sentry_sdk.init( + # ... + data_collection={ + # Record LLM inputs, but not outputs + "gen_ai": {"inputs": True, "outputs": False}, + }, + ) + ``` + + In SDK versions prior to `3.0`, Sentry considers LLM inputs and outputs as PII and doesn't include prompts, messages, or responses unless you pass a `data_collection` dictionary or set `send_default_pii=True`. diff --git a/docs/platforms/python/agent-tracing/google-genai/index.mdx b/docs/platforms/python/agent-tracing/google-genai/index.mdx index 583db380806c6..41af60cd3d849 100644 --- a/docs/platforms/python/agent-tracing/google-genai/index.mdx +++ b/docs/platforms/python/agent-tracing/google-genai/index.mdx @@ -61,8 +61,8 @@ sentry_sdk.init(...) # same as above client = Client(api_key="(your Google API key)") def my_llm_stuff(): - # or sentry_sdk.traces.start_span(name="The result of the AI inference", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="The result of the AI inference"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="The result of the AI inference") instead + with sentry_sdk.start_span(name="The result of the AI inference"): response = client.models.generate_content( model="gemini-2.0-flash-exp", contents="say hello" @@ -82,7 +82,7 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se - The supported function is currently `models.generate_content` (both sync and async). -- Sentry considers LLM inputs/outputs as PII (Personally identifiable information) and doesn't include prompts, messages, or responses by default. Tool definitions and the tool calls returned by the model, including their arguments, are still attached by default; setting `inputs` and `outputs` to `False` in the `gen_ai` key described below removes them. The arguments and return values of Python functions you pass as tools are currently always attached to tool execution spans, regardless of these options. To include prompts, messages, and responses, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately. When you pass a `data_collection` dictionary, both are collected by default and `include_prompts` is ignored: +- By default, the SDK records LLM inputs and outputs, such as prompts, messages, and responses. Tool definitions and the tool calls returned by the model, including their arguments, are recorded too; setting `inputs` and `outputs` to `False` in the `gen_ai` key removes them. The arguments and return values of Python functions you pass as tools are currently always attached to tool execution spans, regardless of these options. To control this, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately: ```python sentry_sdk.init( @@ -94,10 +94,16 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se ) ``` - Alternatively, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False` as shown in the [Options section](#options) below. `send_default_pii` will be removed in version 3.0 of the SDK. + In SDK versions prior to `3.0`, Sentry considers LLM inputs and outputs as PII and doesn't include prompts, messages, or responses unless you pass a `data_collection` dictionary or set `send_default_pii=True`. With `send_default_pii=True`, you can exclude them with the integration's `include_prompts=False` option, as shown in the [Options section](#options) below. ## Options + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, `GoogleGenAIIntegration` doesn't accept any options. Use the `gen_ai` key of the `data_collection` option instead. + + + You can set options for `GoogleGenAIIntegration` to change its behavior: ```python @@ -123,7 +129,7 @@ You can pass the following keyword arguments to `GoogleGenAIIntegration()`: Whether LLM inputs and outputs should be sent to Sentry. If you use the `data_collection` option, this option is ignored. Use the `gen_ai` key instead. - Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. `send_default_pii` will be removed in version 3.0 of the SDK. + Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. The default is `True`. diff --git a/docs/platforms/python/agent-tracing/huggingface_hub/index.mdx b/docs/platforms/python/agent-tracing/huggingface_hub/index.mdx index f48ab12ff4295..87e4dc840c519 100644 --- a/docs/platforms/python/agent-tracing/huggingface_hub/index.mdx +++ b/docs/platforms/python/agent-tracing/huggingface_hub/index.mdx @@ -42,7 +42,7 @@ sentry_sdk.init( ## Verify -Verify that the integration works by initializing a transaction and invoking an agent. In these examples, we're providing a function tool to roll a die. +Verify that the integration works by starting a span and invoking an agent. In these examples, we're providing a function tool to roll a die. ```python import random @@ -77,8 +77,8 @@ def main(): client = InferenceClient(token=HF_TOKEN) - # or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): response = client.chat_completion( model="Qwen/Qwen2.5-72B-Instruct", messages=[{ @@ -103,7 +103,7 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se - All exceptions are reported. -- Sentry considers LLM and tokenizer inputs/outputs as PII (Personally identifiable information) and doesn't include prompts, messages, or responses by default. Tool definitions are still attached by default; setting `inputs` to `False` in the `gen_ai` key described below removes them. To include prompts, messages, and responses, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately. When you pass a `data_collection` dictionary, both are collected by default and `include_prompts` is ignored: +- By default, the SDK records LLM and tokenizer inputs and outputs, such as prompts, messages, and responses. Tool definitions are recorded too; setting `inputs` to `False` in the `gen_ai` key removes them. To control this, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately: ```python sentry_sdk.init( @@ -115,10 +115,16 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se ) ``` - Alternatively, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False` as shown in the [Options section](#options) below. `send_default_pii` will be removed in version 3.0 of the SDK. + In SDK versions prior to `3.0`, Sentry considers LLM and tokenizer inputs and outputs as PII and doesn't include prompts, messages, or responses unless you pass a `data_collection` dictionary or set `send_default_pii=True`. With `send_default_pii=True`, you can exclude them with the integration's `include_prompts=False` option, as shown in the [Options section](#options) below. ## Options + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, `HuggingfaceHubIntegration` doesn't accept any options. Use the `gen_ai` key of the `data_collection` option instead. + + + By adding `HuggingfaceHubIntegration` to your `sentry_sdk.init()` call explicitly, you can set options for `HuggingfaceHubIntegration` to change its behavior: ```python @@ -144,7 +150,7 @@ You can pass the following keyword arguments to `HuggingfaceHubIntegration()`: Whether LLM and tokenizer inputs and outputs should be sent to Sentry. If you use the `data_collection` option, this option is ignored. Use the `gen_ai` key instead. - Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. `send_default_pii` will be removed in version 3.0 of the SDK. + Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. The default is `True`. diff --git a/docs/platforms/python/agent-tracing/index.mdx b/docs/platforms/python/agent-tracing/index.mdx index 11dd15f3d3679..b3de6612ad34f 100644 --- a/docs/platforms/python/agent-tracing/index.mdx +++ b/docs/platforms/python/agent-tracing/index.mdx @@ -13,7 +13,7 @@ With Sentry Agent Tracing, you can ## Getting Started -Enable tracing. Supported AI libraries are instrumented automatically when their packages are installed. Prompt and response content is off by default — use the `gen_ai` key of the `data_collection` option to capture it. Alternatively, set `send_default_pii=True` (and configure `include_prompts` per integration). `send_default_pii` will be removed in version 3.0 of the SDK. +Enable tracing. Supported AI libraries are instrumented automatically when their packages are installed. Prompt and response content is captured by default — use the `gen_ai` key of the `data_collection` option to turn it off. In SDK versions prior to `3.0`, it's off by default unless you use `data_collection` or set `send_default_pii=True`. ```python import sentry_sdk @@ -34,6 +34,7 @@ Pick your AI stack. Each page has install and verify details. `data_collection` option, which lets you control inputs and outputs separately. When you pass a `data_collection` dictionary, both are collected by default and `include_prompts` is ignored: +LLM inputs and outputs, such as prompts, messages, responses, and tool definitions, are recorded by default. See each integration page for details. To control this, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately: ```python import sentry_sdk @@ -90,12 +91,13 @@ sentry_sdk.init( ) ``` -Alternatively, set `send_default_pii=True` to capture them. To keep other PII on but turn AI content off, set `include_prompts=False` on the integration. `send_default_pii` will be removed in version 3.0 of the SDK. +In SDK versions prior to `3.0`, LLM inputs and outputs are treated as PII and are **off** by default unless you pass a `data_collection` dictionary or set `send_default_pii=True`. To keep other PII on but turn AI content off with `send_default_pii=True`, set `include_prompts=False` on the integration: ```python import sentry_sdk from sentry_sdk.integrations.openai import OpenAIIntegration +# SDK 2.x only sentry_sdk.init( dsn="___PUBLIC_DSN___", send_default_pii=True, @@ -109,6 +111,12 @@ See each integration page for the options that apply to your stack. ### Streaming Gen AI Spans + + +Only available in SDK versions prior to `3.0`. Starting with `3.0`, all spans, including `gen_ai` spans, are streamed, and the `stream_gen_ai_spans` option was removed. + + + From SDK `2.64.0`, `gen_ai` spans are sent as standalone envelope items (avoids large-payload drops; required for Conversations). Self-hosted Sentry users should set `stream_gen_ai_spans=False` if standalone `gen_ai` spans may not be ingested. diff --git a/docs/platforms/python/agent-tracing/langchain/index.mdx b/docs/platforms/python/agent-tracing/langchain/index.mdx index 2f3cf2a4d99ee..ee087a4e6e5de 100644 --- a/docs/platforms/python/agent-tracing/langchain/index.mdx +++ b/docs/platforms/python/agent-tracing/langchain/index.mdx @@ -69,7 +69,7 @@ sentry_sdk.init( ## Verify -Verify that the integration works by initializing a transaction and invoking an agent. In these examples, we're providing a function tool to roll a die. +Verify that the integration works by starting a span and invoking an agent. In these examples, we're providing a function tool to roll a die. ```python {tabTitle:OpenAI} import random @@ -85,8 +85,8 @@ def roll_die(sides: int = 6) -> str: """Roll a die with a given number of sides""" return f"Rolled a {random.randint(1, sides)} on a {sides}-sided die." -# or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode -with sentry_sdk.start_transaction(name="langchain-openai"): +# In SDK 2.x, use sentry_sdk.start_transaction(name="langchain-openai") instead +with sentry_sdk.start_span(name="langchain-openai"): model = init_chat_model( "gpt-4o-mini", model_provider="openai", @@ -129,8 +129,8 @@ def roll_die(sides: int = 6) -> str: """Roll a die with a given number of sides""" return f"Rolled a {random.randint(1, sides)} on a {sides}-sided die." -# or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode -with sentry_sdk.start_transaction(name="langchain-anthropic"): +# In SDK 2.x, use sentry_sdk.start_transaction(name="langchain-anthropic") instead +with sentry_sdk.start_span(name="langchain-anthropic"): model = init_chat_model( "claude-3-5-sonnet-20241022", model_provider="anthropic", @@ -168,7 +168,7 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se - All exceptions are reported. -- Sentry considers LLM and tokenizer inputs/outputs as PII (Personally identifiable information) and doesn't include prompts, messages, or responses by default. Tool definitions, as well as tool calls passed in the model's invocation parameters, are still attached by default; setting `inputs` to `False` in the `gen_ai` key described below removes them. To include prompts, messages, and responses, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately. When you pass a `data_collection` dictionary, both are collected by default and `include_prompts` is ignored: +- By default, the SDK records LLM and tokenizer inputs and outputs, such as prompts, messages, and responses. Tool definitions, as well as tool calls passed in the model's invocation parameters, are recorded too; setting `inputs` to `False` in the `gen_ai` key removes them. To control this, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately: ```python sentry_sdk.init( @@ -180,10 +180,16 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se ) ``` - Alternatively, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False` as shown in the [Options section](#options) below. `send_default_pii` will be removed in version 3.0 of the SDK. + In SDK versions prior to `3.0`, Sentry considers LLM and tokenizer inputs and outputs as PII and doesn't include prompts, messages, or responses unless you pass a `data_collection` dictionary or set `send_default_pii=True`. With `send_default_pii=True`, you can exclude them with the integration's `include_prompts=False` option, as shown in the [Options section](#options) below. ## Options + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, `LangchainIntegration` doesn't accept any options. Use the `gen_ai` key of the `data_collection` option instead. + + + By adding `LangchainIntegration` to your `sentry_sdk.init()` call explicitly, you can set options for `LangchainIntegration` to change its behavior: ```python @@ -209,7 +215,7 @@ You can pass the following keyword arguments to `LangchainIntegration()`: Whether LLM and tokenizer inputs and outputs should be sent to Sentry. If you use the `data_collection` option, this option is ignored. Use the `gen_ai` key instead. - Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. `send_default_pii` will be removed in version 3.0 of the SDK. + Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. The default is `True`. diff --git a/docs/platforms/python/agent-tracing/langgraph/index.mdx b/docs/platforms/python/agent-tracing/langgraph/index.mdx index cbb16faaf5f0d..a20003f349e0d 100644 --- a/docs/platforms/python/agent-tracing/langgraph/index.mdx +++ b/docs/platforms/python/agent-tracing/langgraph/index.mdx @@ -73,8 +73,8 @@ def should_continue(state: State) -> Literal["tools", END]: last_message = state["messages"][-1] return "tools" if getattr(last_message, "tool_calls", None) else END -# or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode -with sentry_sdk.start_transaction(name="langgraph-openai"): +# In SDK 2.x, use sentry_sdk.start_transaction(name="langgraph-openai") instead +with sentry_sdk.start_span(name="langgraph-openai"): graph_builder = StateGraph(State) graph_builder.add_node("chatbot", chatbot) graph_builder.add_node("tools", ToolNode([roll_die])) @@ -102,6 +102,12 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se ## Options + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, `LanggraphIntegration` doesn't accept any options. Use the `gen_ai` key of the `data_collection` option instead. + + + By adding `LanggraphIntegration` to your `sentry_sdk.init()` call explicitly, you can set options for `LanggraphIntegration` to change its behavior: ```python @@ -127,7 +133,7 @@ You can pass the following keyword arguments to `LanggraphIntegration()`: Controls whether LLM inputs and outputs should be sent to Sentry. If you use the `data_collection` option, this option is ignored. Use the `gen_ai` key instead. - Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. `send_default_pii` will be removed in version 3.0 of the SDK. + Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. The default is `True`. diff --git a/docs/platforms/python/agent-tracing/litellm/index.mdx b/docs/platforms/python/agent-tracing/litellm/index.mdx index dde53bdd00c20..638b7b3332a62 100644 --- a/docs/platforms/python/agent-tracing/litellm/index.mdx +++ b/docs/platforms/python/agent-tracing/litellm/index.mdx @@ -86,7 +86,7 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se - The supported functions are currently `completion` and `embedding` (both sync and async). -- Sentry considers LLM inputs/outputs as PII (Personally identifiable information) and doesn't include PII data by default. To include the data, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately. When you pass a `data_collection` dictionary, both are collected by default and `include_prompts` is ignored: +- By default, the SDK records LLM inputs and outputs, such as prompts, messages, and responses. To control this, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately: ```python sentry_sdk.init( @@ -98,10 +98,16 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se ) ``` - Alternatively, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False` as shown in the [Options section](#options) below. `send_default_pii` will be removed in version 3.0 of the SDK. + In SDK versions prior to `3.0`, Sentry considers LLM inputs and outputs as PII and doesn't include prompts, messages, or responses unless you pass a `data_collection` dictionary or set `send_default_pii=True`. With `send_default_pii=True`, you can exclude them with the integration's `include_prompts=False` option, as shown in the [Options section](#options) below. ## Options + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, `LiteLLMIntegration` doesn't accept any options. Use the `gen_ai` key of the `data_collection` option instead. + + + By adding `LiteLLMIntegration` to your `sentry_sdk.init()` call explicitly, you can set options for `LiteLLMIntegration` to change its behavior: ```python @@ -127,7 +133,7 @@ You can pass the following keyword arguments to `LiteLLMIntegration()`: Whether LLM inputs and outputs should be sent to Sentry. If you use the `data_collection` option, this option is ignored. Use the `gen_ai` key instead. - Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. `send_default_pii` will be removed in version 3.0 of the SDK. + Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. The default is `True`. diff --git a/docs/platforms/python/agent-tracing/manual-instrumentation.mdx b/docs/platforms/python/agent-tracing/manual-instrumentation.mdx index 1b146af41d7b0..db31f96e8ec7e 100644 --- a/docs/platforms/python/agent-tracing/manual-instrumentation.mdx +++ b/docs/platforms/python/agent-tracing/manual-instrumentation.mdx @@ -46,7 +46,7 @@ To group turns into a [Conversation](/product/agents/conversations/), call `set_ Complex values (messages, tool definitions, arrays) must be **JSON strings** — span attributes only accept primitives. -Prompt, response, and tool content can contain PII. The SDK doesn't filter attributes you set manually, so the `data_collection` and `send_default_pii` options don't affect them. Decide what to record before you set these attributes. To learn how automatic integrations handle this data, see Privacy Controls. +Prompt, response, and tool content can contain PII. The SDK doesn't filter attributes you set manually, so the `data_collection` option (and `send_default_pii` in SDK versions prior to `3.0`) doesn't affect them. Decide what to record before you set these attributes. To learn how automatic integrations handle this data, see Privacy Controls. ## AI Request Span diff --git a/docs/platforms/python/agent-tracing/mistral/index.mdx b/docs/platforms/python/agent-tracing/mistral/index.mdx index 29fee9feb9132..05c005e7fba69 100644 --- a/docs/platforms/python/agent-tracing/mistral/index.mdx +++ b/docs/platforms/python/agent-tracing/mistral/index.mdx @@ -91,7 +91,7 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se - The supported functions are currently `Chat.complete` and `Chat.complete_async` (sync and async). Streaming completions (`stream=True`) are not instrumented. -- Sentry considers LLM inputs/outputs as PII (Personally identifiable information) and doesn't include PII data by default. To include the data, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately. When you pass a `data_collection` dictionary, both are collected by default: +- By default, the SDK records LLM inputs and outputs, such as prompts, messages, and responses. To control this, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately: ```python sentry_sdk.init( @@ -103,7 +103,7 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se ) ``` - Alternatively, set `send_default_pii=True` in the `sentry_sdk.init()` call. `send_default_pii` will be removed in version 3.0 of the SDK. + In SDK versions prior to `3.0`, Sentry considers LLM inputs and outputs as PII and doesn't include prompts, messages, or responses unless you pass a `data_collection` dictionary or set `send_default_pii=True`. ## Supported Versions diff --git a/docs/platforms/python/agent-tracing/openai-agents/index.mdx b/docs/platforms/python/agent-tracing/openai-agents/index.mdx index 4d3520779ae8e..5d4bb81759464 100644 --- a/docs/platforms/python/agent-tracing/openai-agents/index.mdx +++ b/docs/platforms/python/agent-tracing/openai-agents/index.mdx @@ -94,7 +94,7 @@ Data on the following will be collected: - number of input and output tokens used - LLM models usage -Sentry considers LLM and tool inputs/outputs as PII and doesn't include prompts, messages, or responses by default. Tool definitions are still attached by default; setting `inputs` to `False` in the `gen_ai` key described below removes them. To include prompts, messages, and responses, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately. When you pass a `data_collection` dictionary, both are collected by default and `include_prompts` is ignored: +By default, the SDK records LLM and tool inputs and outputs, such as prompts, messages, and responses. Tool definitions are recorded too; setting `inputs` to `False` in the `gen_ai` key removes them. To control this, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately: ```python sentry_sdk.init( @@ -106,10 +106,16 @@ sentry_sdk.init( ) ``` -Alternatively, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False` as shown in the [Options section](#options) below. `send_default_pii` will be removed in version 3.0 of the SDK. +In SDK versions prior to `3.0`, Sentry considers LLM and tool inputs and outputs as PII and doesn't include prompts, messages, or responses unless you pass a `data_collection` dictionary or set `send_default_pii=True`. With `send_default_pii=True`, you can exclude them with the integration's `include_prompts=False` option, as shown in the [Options section](#options) below. ## Options + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, `OpenAIAgentsIntegration` doesn't accept any options. Use the `gen_ai` key of the `data_collection` option instead. + + + By adding `OpenAIAgentsIntegration` to your `sentry_sdk.init()` call explicitly, you can set options for `OpenAIAgentsIntegration` to change its behavior: ```python @@ -135,7 +141,7 @@ You can pass the following keyword arguments to `OpenAIAgentsIntegration()`: Whether LLM and tool inputs and outputs should be sent to Sentry. If you use the `data_collection` option, this option is ignored. Use the `gen_ai` key instead. - Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. `send_default_pii` will be removed in version 3.0 of the SDK. + Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. The default is `True`. diff --git a/docs/platforms/python/agent-tracing/openai/index.mdx b/docs/platforms/python/agent-tracing/openai/index.mdx index 503ee0d30f9e0..fab2dbdb5a87f 100644 --- a/docs/platforms/python/agent-tracing/openai/index.mdx +++ b/docs/platforms/python/agent-tracing/openai/index.mdx @@ -51,10 +51,10 @@ sentry_sdk.init(...) # same as above client = OpenAI(api_key="(your OpenAI key)") def my_llm_stuff(): - # or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode - with sentry_sdk.start_transaction( + # In SDK 2.x, use sentry_sdk.start_transaction(name=..., op="ai-inference") instead + with sentry_sdk.start_span( name="The result of the AI inference", - op="ai-inference", + attributes={"sentry.op": "ai-inference"}, ): print( client.chat.completions.create( @@ -79,7 +79,7 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se - The supported modules are currently `responses.create`, `chat.completions.create`, and `embeddings.create`. -- Sentry considers LLM and tokenizer inputs/outputs as PII (Personally identifiable information) and doesn't include prompts, messages, or responses by default. Tool definitions are still attached by default; setting `inputs` to `False` in the `gen_ai` key described below removes them. To include prompts, messages, and responses, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately. When you pass a `data_collection` dictionary, both are collected by default and `include_prompts` is ignored: +- By default, the SDK records LLM and tokenizer inputs and outputs, such as prompts, messages, responses, and tool definitions. To control this, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately: ```python sentry_sdk.init( @@ -91,7 +91,7 @@ It may take a couple of moments for the data to appear in [sentry.io](https://se ) ``` - Alternatively, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False` as shown in the [Options section](#options) below. `send_default_pii` will be removed in version 3.0 of the SDK. + In SDK versions prior to `3.0`, Sentry considers LLM and tokenizer inputs and outputs as PII and doesn't include prompts, messages, or responses unless you pass a `data_collection` dictionary or set `send_default_pii=True`. With `send_default_pii=True`, you can exclude them with the integration's `include_prompts=False` option, as described in the [Options section](#options) below. ## Options @@ -103,12 +103,8 @@ from sentry_sdk.integrations.openai import OpenAIIntegration sentry_sdk.init( # ... - # Add data like inputs and responses; - # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info - send_default_pii=True, integrations=[ OpenAIIntegration( - include_prompts=False, # LLM/tokenizer inputs/outputs will be not sent to Sentry, despite send_default_pii=True tiktoken_encoding_name="cl100k_base", ), ], @@ -119,9 +115,11 @@ You can pass the following keyword arguments to `OpenAIIntegration()`: - `include_prompts`: + Only available in SDK versions prior to `3.0`. In SDK `3.x`, use the `gen_ai` key of the `data_collection` option instead. + Whether LLM and tokenizer inputs and outputs should be sent to Sentry. If you use the `data_collection` option, this option is ignored. Use the `gen_ai` key instead. - Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. `send_default_pii` will be removed in version 3.0 of the SDK. + Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. The default is `True`. diff --git a/docs/platforms/python/agent-tracing/pydantic-ai/index.mdx b/docs/platforms/python/agent-tracing/pydantic-ai/index.mdx index 4e71bc19d5bdc..1bc32a71b71f5 100644 --- a/docs/platforms/python/agent-tracing/pydantic-ai/index.mdx +++ b/docs/platforms/python/agent-tracing/pydantic-ai/index.mdx @@ -215,7 +215,7 @@ Data on the following will be collected: - LLM models usage - model settings (temperature, max_tokens, etc.) -Sentry considers LLM and tool inputs/outputs as PII and doesn't include prompts, messages, or responses by default. Tool definitions are still attached by default; setting `inputs` to `False` in the `gen_ai` key described below removes them. To include prompts, messages, and responses, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately. When you pass a `data_collection` dictionary, both are collected by default and `include_prompts` is ignored: +By default, the SDK records LLM and tool inputs and outputs, such as prompts, messages, and responses. Tool definitions are recorded too; setting `inputs` to `False` in the `gen_ai` key removes them. To control this, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately: ```python sentry_sdk.init( @@ -227,7 +227,7 @@ sentry_sdk.init( ) ``` -Alternatively, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False` as shown in the Options section below. `send_default_pii` will be removed in version 3.0 of the SDK. +In SDK versions prior to `3.0`, Sentry considers LLM and tool inputs and outputs as PII and doesn't include prompts, messages, or responses unless you pass a `data_collection` dictionary or set `send_default_pii=True`. With `send_default_pii=True`, you can exclude them with the integration's `include_prompts=False` option, as shown in the [Options section](#options) below. ## Options @@ -239,12 +239,9 @@ from sentry_sdk.integrations.pydantic_ai import PydanticAIIntegration sentry_sdk.init( # ... - # Add data like inputs and responses; - # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info - send_default_pii=True, integrations=[ PydanticAIIntegration( - include_prompts=False, # LLM and tool inputs/outputs will be not sent to Sentry, despite send_default_pii=True + handled_tool_call_exceptions=False, ), ], ) @@ -254,16 +251,18 @@ You can pass the following keyword arguments to `PydanticAIIntegration()`: - `include_prompts`: + Only available in SDK versions prior to `3.0`. In SDK `3.x`, use the `gen_ai` key of the `data_collection` option instead. + Whether LLM and tool inputs and outputs should be sent to Sentry. If you use the `data_collection` option, this option is ignored. Use the `gen_ai` key instead. - Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. `send_default_pii` will be removed in version 3.0 of the SDK. + Sentry considers this data personal identifiable data (PII) by default. If you want to include the data, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude prompts and outputs despite `send_default_pii=True`, configure the integration with `include_prompts=False`. The default is `True`. - `handled_tool_call_exceptions`: Option to capture tool call exceptions that Pydantic AI prevents from bubbling up. These include validation errors when an agent is configured to - retry tool calls. All additional tool call exceptions reported when this option is `True` are handled errors in Sentry. This option has no effect on exceptions that are not handled by Pydantic AI. + retry tool calls. All additional tool call exceptions reported when this option is `True` are handled errors in Sentry. This option has no effect on exceptions that are not handled by Pydantic AI. Starting with SDK `3.0`, an error is reported for every failed tool argument validation attempt, including retries. The default is `True`. diff --git a/docs/platforms/python/configuration/options.mdx b/docs/platforms/python/configuration/options.mdx index 776a980fa12ca..1e72bba5c2d33 100644 --- a/docs/platforms/python/configuration/options.mdx +++ b/docs/platforms/python/configuration/options.mdx @@ -87,32 +87,35 @@ This variable controls the total amount of breadcrumbs that should be captured. - + When enabled, stack traces are automatically attached to all messages logged. Stack traces are always attached to exceptions; however, when this option is set, stack traces are also sent with messages. This option, for instance, means that stack traces appear next to all log messages. Grouping in Sentry is different for events with stack traces and without. As a result, you will get new groups as you enable or disable this flag for certain events. +In SDK versions prior to `3.0`, the default was `False`. + -If this flag is enabled, [certain personally identifiable information (PII)](/platforms/python/data-management/data-collected/) is added by active integrations. - -If you enable this option, be sure to manually remove what you don't want to send using our features for managing [_Sensitive Data_](../../data-management/sensitive-data/). - - `send_default_pii` will be removed in version 3.0 of the SDK. Use the [`data_collection`](#data_collection) option instead. -If you set both, `send_default_pii` is ignored entirely and the SDK emits a `DeprecationWarning`. +Only available in SDK versions prior to `3.0`. Use the [`data_collection`](#data_collection) option instead. See the migration guide for how to keep your previous data collection behavior. +If this flag is enabled, [certain personally identifiable information (PII)](/platforms/python/data-management/data-collected/) is added by active integrations. + +If you enable this option, be sure to manually remove what you don't want to send using our features for managing [_Sensitive Data_](../../data-management/sensitive-data/). + +If you set both `send_default_pii` and `data_collection`, `send_default_pii` is ignored entirely and the SDK emits a `DeprecationWarning`. + -Controls which categories of data the SDK collects automatically, replacing the single `send_default_pii` boolean with a per-category configuration. All keys are optional. +Controls which categories of data the SDK collects automatically, with a per-category configuration. All keys are optional. ```python import sentry_sdk @@ -126,9 +129,9 @@ sentry_sdk.init( ) ``` -Passing a `data_collection` dictionary opts you into its defaults, which are more permissive than `send_default_pii=False`. Any key you don't set falls back to its default, so the SDK collects rich debugging context (user identity, request bodies, generative AI content) and scrubs values whose keys match the built-in sensitive denylist (`auth`, `token`, `password`, and similar). +Any key you don't set falls back to its default, so the SDK collects rich debugging context (user identity, request bodies, generative AI content) and scrubs values whose keys match the built-in sensitive denylist (`auth`, `token`, `password`, and similar). -If you set both `data_collection` and `send_default_pii`, `send_default_pii` is ignored entirely and the SDK emits a `DeprecationWarning`. +In SDK versions prior to `3.0`, the defaults only apply once you pass a `data_collection` dictionary, and they're more permissive than `send_default_pii=False`. If you set both `data_collection` and `send_default_pii`, `send_default_pii` is ignored entirely and the SDK emits a `DeprecationWarning`. For the full reference of available keys and their defaults, see Data Collected. @@ -136,6 +139,12 @@ For the full reference of available keys and their defaults, see + + +Only available in SDK versions prior to `3.0`. Use [`data_collection`](#data_collection) to control what data the SDK collects, and [`before_send`](#before_send) for custom scrubbing. + + + Scrubs the event payload for sensitive information such as cookies, sessions, and passwords from a `denylist`. It can additionally be used to scrub from another `pii_denylist` if `send_default_pii` is disabled. See how to [configure the scrubber here](../../data-management/sensitive-data/#event-scrubber). Only runs if `data_collection` is not defined. See Data Collected. @@ -144,12 +153,24 @@ Only runs if `data_collection` is not defined. See + + +Only available in SDK versions prior to `3.0`. Use the `frame_context_lines` setting of [`data_collection`](#data_collection) instead. Set it to `0` to disable source context. + + + When enabled, source context will be included in events sent to Sentry. This source context includes the five lines of code above and below the line of code where an error happened. + + +Only available in SDK versions prior to `3.0`. Use the `stack_frame_variables` setting of [`data_collection`](#data_collection) instead. + + + When enabled, the SDK will capture a snapshot of local variables to send with the event to help with debugging. @@ -281,25 +302,27 @@ By the time `before_send` is executed, all scope data has already been applied t -This function is called with a transaction event object, and can return a modified transaction event object, or `None` to skip reporting the event. One way this might be used is for manual PII stripping before sending. + - +Only available in SDK versions prior to `3.0`. Use [`before_send_span`](#before_send_span) to modify spans and [`ignore_spans`](#ignore_spans) to drop them. - + - +This function is called with a transaction event object, and can return a modified transaction event object, or `None` to skip reporting the event. One way this might be used is for manual PII stripping before sending. -Only available in stream mode. + - + This function is called with a span event object and can return a modified span object. Use it, for example, to manually strip PII from spans or filter data from spans before they're sent to Sentry. Note that `before_send_span` can only modify span data, meaning you cannot use it to drop spans. Use [`ignore_spans`](#ignore_spans) to drop spans. +In SDK versions prior to `3.0`, this option is only available in stream mode. + -```python {tabTitle:Stream Mode} +```python import sentry_sdk def before_send_span(span, hint): @@ -313,7 +336,6 @@ def before_send_span(span, hint): sentry_sdk.init( # ... - trace_lifecycle="stream", before_send_span=before_send_span, ) ``` @@ -339,7 +361,27 @@ New in SDK version `2.35.0`. Prior to `2.35.0`, this option was experimental. - + + +This function is called with a cron check-in object and a hint, and can return a modified check-in, or `None` to skip sending it. + +Check-ins don't go through `before_send`. In SDK versions prior to `3.0`, check-ins are passed to `before_send` instead. + +```python +import sentry_sdk + +def before_send_check_in(check_in, hint): + if check_in.get("monitor_slug") == "noisy-job": + return None + return check_in + +sentry_sdk.init( + # ... + before_send_check_in=before_send_check_in, +) +``` + + ## Transport Options @@ -426,9 +468,9 @@ sentry_sdk.init( -A number between `0` and `1`, controlling the percentage chance a given transaction (or service span in stream mode) will be sent to Sentry. (`0` represents 0% while `1` represents 100%.) Applies equally to all transactions and spans created in the app. Either this or `traces_sampler` must be defined to enable tracing. +A number between `0` and `1`, controlling the percentage chance a given trace will be sent to Sentry. (`0` represents 0% while `1` represents 100%.) Applies equally to all traces started in the app. Either this or `traces_sampler` must be defined to enable tracing. -If `traces_sample_rate` is `0`, this means that no new traces will be created. However, if you have another service (for example a JS frontend) that makes requests to your service that include trace information, those traces will be continued and thus transactions will be sent to Sentry. +If `traces_sample_rate` is `0`, this means that no new traces will be created. However, if you have another service (for example a JS frontend) that makes requests to your service that include trace information, those traces will be continued and thus spans will be sent to Sentry. If you want to disable all tracing you need to set `traces_sample_rate=None`. In this case, no new traces will be started and no incoming traces will be continued. @@ -438,6 +480,12 @@ If you want to disable all tracing you need to set `traces_sample_rate=None`. In + + +Only available in SDK versions prior to `3.0`. Starting with `3.0`, spans are always streamed. The SDK still accepts this option, but ignores any value other than `"stream"` and logs a warning. + + + Controls how spans are sent to Sentry: - In transaction mode (`"static"`, the default), all spans are collected in memory and sent to Sentry as a single transaction once the root span ends. @@ -447,12 +495,6 @@ Controls how spans are sent to Sentry: - - -Only available in stream mode. - - - A list of strings, compiled regular expressions, or dictionaries describing spans that shouldn't be sent to Sentry. When using strings, a span name containing the string will be filtered out. For exact or more complex pattern matching, use compiled regular expressions instead. You can also provide a dictionary with `name` and/or `attributes` keys to match on multiple conditions. At least one key must be provided. If the dropped span is a service span, its children are dropped too. If it's a child span, only that span is dropped and its children are reparented to the nearest ancestor. @@ -460,6 +502,8 @@ By default, no spans are ignored. `ignore_spans` is evaluated at span start, so only the span name and attributes available at that point are taken into account. Any name updates or additional attributes added while the span is active won't influence whether the span is dropped. +In SDK versions prior to `3.0`, this option is only available in stream mode. + ```python @@ -467,7 +511,6 @@ import re import sentry_sdk sentry_sdk.init( - trace_lifecycle="stream", ignore_spans=[ # String match against span name "/health", @@ -579,6 +622,12 @@ The threshold in milliseconds for adding the source location to an outgoing HTTP + + +Only available in SDK versions prior to `3.0`. + + + An optional property that disables tracing for HTTP requests with certain status codes. Requests are not traced if the status code is contained in the provided set. @@ -619,12 +668,18 @@ In `trace` mode, the profiler starts and stops automatically based on active spa -Determines which scheduler the profiler uses to record profiles. Can be `"thread"`, `"gevent"`, `"unknown"`, or `"sleep"` (deprecated, only for backwards compatibility). If not set, the SDK will determine the best scheduler to use. Only change this option if you know what you are doing. +Determines which scheduler the profiler uses to record profiles. Can be `"thread"`, `"gevent"`, or `"unknown"`. In SDK versions prior to `3.0`, `"sleep"` is also accepted (deprecated, only for backwards compatibility). If not set, the SDK will determine the best scheduler to use. Only change this option if you know what you are doing. + + +Only available in SDK versions prior to `3.0`. Transaction-based profiling was removed in `3.0`. Use [`profile_session_sample_rate`](#profile_session_sample_rate) with [`profile_lifecycle`](#profile_lifecycle) instead. + + + A number between `0` and `1`, controlling the percentage chance a given profile will be sent to Sentry. (`0` represents 0% while `1` represents 100%.) Applies equally to all profiles created in the app. The `profiles_sample_rate` setting is relative to the `traces_sample_rate` setting. Either this or `profiles_sampler` must be defined to enable profiling. @@ -633,6 +688,12 @@ Either this or `profiles_sampler` must be defined to enable profiling. + + +Only available in SDK versions prior to `3.0`. Transaction-based profiling was removed in `3.0`. Use [`profile_session_sample_rate`](#profile_session_sample_rate) with [`profile_lifecycle`](#profile_lifecycle) instead. + + + A function responsible for determining the percentage chance a recorded profile will be sent to Sentry. The function takes one parameter (the `sampling_context`). The given `sampling_context` contains information about the transaction linked to the profile and the context in which it's being created. The function must return a number between `0` (0% chance of being sent) and `1` (100% chance of being sent). Can also be used for filtering profiles, by returning `0` for those that are unwanted. Either this or `profiles_sample_rate` must be defined to enable profiling. Additionally, tracing must be enabled for profiling to work. @@ -647,6 +708,12 @@ A number between `0` and `1`, controlling the percentage chance a given session + + +Only available in SDK versions prior to `3.0`. Starting with `3.0`, all spans, including `gen_ai` spans, are streamed. + + + When enabled, `gen_ai` spans are sent as standalone envelope items instead of being bundled in the transaction payload. This prevents AI spans with large inputs and outputs from being dropped due to transaction payload size limits. This is enabled by default starting with SDK version `2.64.0` (before that, it defaulted to `False`). Set it to `False` to send `gen_ai` spans as part of the transaction instead. @@ -659,7 +726,13 @@ Self-hosted Sentry users should set this option to `False`, as standalone `gen_a -**Deprecated:** This option will be removed in the next major version. Use the `capture_sentry_logs` option on the [`logging`](/platforms/python/integrations/logging/#options) and [Loguru](/platforms/python/integrations/loguru/#options) integrations instead. + + +Only available in SDK versions prior to `3.0`. Starting with `3.0`, the `sentry_sdk.logger` API works without any configuration, and the [`logging`](/platforms/python/integrations/logging/) and [Loguru](/platforms/python/integrations/loguru/) integrations send Sentry logs once you add them to `integrations`. + + + +In SDK `2.x`, use the `capture_sentry_logs` option on the logging and Loguru integrations instead. The `sentry_sdk.logger` API works standalone and is not affected by this option. @@ -677,4 +750,3 @@ In SDK versions prior to `2.68.0`, this option had to be set to `True` to use th Deprecated in version `2.68.1`. New in SDK version `2.35.0`. Prior to `2.35.0`, this option was experimental. - diff --git a/docs/platforms/python/data-management/data-collected.mdx b/docs/platforms/python/data-management/data-collected.mdx index 08c5b4c716f89..a43a2d94d63be 100644 --- a/docs/platforms/python/data-management/data-collected.mdx +++ b/docs/platforms/python/data-management/data-collected.mdx @@ -8,17 +8,11 @@ Sentry takes data privacy very seriously and has default settings in place that The category types and amount of data collected vary, depending on the integrations you've enabled in the Sentry SDK. This page lists data categories that the Sentry Python SDK collects. - - -You can control many of the categories listed here with the `data_collection` option, which lets you opt in or out of each data category individually. - -The `send_default_pii` option is still supported, but `send_default_pii` will be removed in version 3.0 of the SDK. - -How much data the SDK collects by default depends on which option you use. Without `data_collection` (and with `send_default_pii` unset or `False`), the SDK collects conservatively, and the defaults described on this page apply. +This page describes the data collected by version `3.x` of the Python SDK. For `2.x`, switch to `2.x` in the version selector. -As soon as you pass a `data_collection` dictionary, the categories you don't set explicitly fall back to their `data_collection` defaults, which are more permissive. For example, cookies, query parameters (with sensitive values scrubbed), and AI message content are then collected unless you opt out. Setting `send_default_pii=True` is roughly equivalent to enabling all `data_collection` categories. + -If you set both, `send_default_pii` is ignored entirely and the SDK emits a `DeprecationWarning`. +You can control many of the categories listed here with the `data_collection` option, which lets you opt in or out of each data category individually. Any category you don't set falls back to its default, described on this page. Regardless of these options, you can always scrub any data before it's sent to Sentry. See Scrubbing Sensitive Data for details. @@ -26,9 +20,9 @@ Regardless of these options, you can always scrub any data before it's sent to S ## HTTP Headers -By default, the Sentry SDK sends HTTP request headers to Sentry but filters out any headers that contain sensitive data. (See the [list of headers](https://github.com/getsentry/sentry-python/blob/master/sentry_sdk/integrations/_wsgi_common.py#L28-L35) that are filtered). The Python SDK doesn't capture response headers. +By default, the Sentry SDK sends HTTP request headers to Sentry, with the values of sensitive headers scrubbed. The Python SDK doesn't capture response headers. -When using `data_collection`, request headers are collected with sensitive values scrubbed. Use `http_headers` to control this: +Use `http_headers` to control this: ```python import sentry_sdk @@ -48,15 +42,9 @@ sentry_sdk.init( Values whose keys match Sentry's built-in sensitive denylist (such as `auth`, `token`, or `password`) are always scrubbed, while the keys are kept. See [Key-Value Collection Behavior](#key-value-collection-behavior) below for details on `mode` and `terms`. -If you use `send_default_pii` instead, set it to `True` in the `sentry_sdk.init()` call to send all HTTP headers. - -Additionally a [data scrubber](/platforms/python/data-management/sensitive-data/) removes sensitive data from headers (and a lot of other fields) right before sending data to Sentry. - ## Cookies -By default, the Sentry SDK doesn't send cookies. Sentry tries to remove any cookies that contain sensitive information, such as the Session ID and CSRF Token cookies in Django. - -When using `data_collection`, cookies are collected by default with sensitive values scrubbed. Opt out with `{"mode": "off"}`, or restrict which values are sent using `"allowlist"` or `"denylist"` mode: +By default, the Sentry SDK sends cookies, with the values of sensitive cookies (such as the Session ID and CSRF Token cookies in Django) scrubbed. Opt out with `{"mode": "off"}`, or restrict which values are sent using `"allowlist"` or `"denylist"` mode: ```python import sentry_sdk @@ -69,15 +57,11 @@ sentry_sdk.init( ) ``` -If you use `send_default_pii` instead, set it to `True` in the `sentry_sdk.init()` call to send cookies. - -Additionally a [data scrubber](/platforms/python/data-management/sensitive-data/) removes sensitive data from cookies (and a lot of other fields) right before sending data to Sentry. - ## Information About Logged-in User -By default, the Sentry SDK doesn't send any information about the logged-in user, such as email address, user ID, or username. Even if enabled, the type of logged-in user information you'll be able to send depends on the integrations you enable in Sentry's SDK. Most integrations won't send any user information. Some will only set the user ID, but there are a few that will set the user ID, username, and email address. +By default, the Sentry SDK populates user identity fields (`user.id`, `user.email`, `user.username`) from instrumentation. The type of logged-in user information you'll be able to send depends on the integrations you enable in Sentry's SDK. Most integrations won't send any user information. Some will only set the user ID, but there are a few that will set the user ID, username, and email address. -When using `data_collection`, the SDK populates user identity fields (`user.id`, `user.email`, `user.username`) from instrumentation by default. To disable this, set `user_info` to `False`: +To disable this, set `user_info` to `False`: ```python import sentry_sdk @@ -90,15 +74,11 @@ sentry_sdk.init( ) ``` -If you use `send_default_pii` instead, set it to `True` in the `sentry_sdk.init()` call to start sending logged-in user information. - ## Users' IP Address -By default, the Sentry SDK doesn't send the user's IP address. Even if enabled, whether you're able to send the user's IP address or not, will depend on the integrations you enable in Sentry's SDK. Most integrations won't set the user's IP address at all. - -When using `data_collection`, the user's IP address is sent by default. Disable it by setting `user_info` to `False`. +By default, the Sentry SDK sends the user's IP address. Whether it's sent depends on the integrations you enable in Sentry's SDK. Most integrations won't set the user's IP address at all. Disable it by setting `user_info` to `False`. -Even when this is disabled, IP addresses can still reach Sentry through collected HTTP headers, cookies, or query parameters (for example, the `X-Forwarded-For` header). If you use `data_collection`, add these terms to the deny lists for those categories so their values are filtered: +Even when this is disabled, IP addresses can still reach Sentry through collected HTTP headers, cookies, or query parameters (for example, the `X-Forwarded-For` header). Add these terms to the deny lists for those categories so their values are filtered: ```python import sentry_sdk @@ -124,8 +104,6 @@ sentry_sdk.init( ) ``` -If you use `send_default_pii` instead, set it to `True` in the `sentry_sdk.init()` call to send the user's IP address. - ## Request URL The full request URL of outgoing and incoming HTTP requests is **always sent to Sentry**. Depending on your application, this could contain PII data. @@ -134,7 +112,7 @@ The full request URL of outgoing and incoming HTTP requests is **always sent to By default, the full request query string of outgoing and incoming HTTP requests is sent to Sentry. Depending on your application, this could contain PII data. For example, a query string like `?user_id=1234`, where `1234` is a user id (which may be considered PII). -When using `data_collection`, use `url_query_params` to control this. Set it to `{"mode": "off"}` to disable collection entirely, or use `"allowlist"` / `"denylist"` mode to filter which values are sent. Values whose keys match the built-in sensitive denylist (terms like `auth`, `token`, `password`, and `secret`) are scrubbed automatically. +Use `url_query_params` to control this. Set it to `{"mode": "off"}` to disable collection entirely, or use `"allowlist"` / `"denylist"` mode to filter which values are sent. Values whose keys match the built-in sensitive denylist (terms like `auth`, `token`, `password`, and `secret`) are scrubbed automatically. ```python import sentry_sdk @@ -161,7 +139,7 @@ The request body of incoming HTTP requests can be sent to Sentry. Whether it's s If you want to prevent bodies from being sent to Sentry altogether, set `max_request_body_size` to `"never"`. -When using `data_collection`, incoming and outgoing request bodies, as well as outgoing response bodies, are collected by default. To disable body collection, set `http_bodies` to an empty list, or provide only the body types you want: +By default, incoming and outgoing request bodies, as well as outgoing response bodies, are collected. To disable body collection, set `http_bodies` to an empty list, or provide only the body types you want: ```python import sentry_sdk @@ -183,9 +161,7 @@ The valid body types are `"incoming_request"`, `"outgoing_request"`, and `"outgo When an unhandled exception is sent to Sentry, a snapshot of the source code surrounding the line where the error originates is sent with it. -To opt out of sending this source context to Sentry, set `include_source_context` to `False`. - -When using `data_collection`, use `frame_context_lines` to control how many lines above and below each stack frame are captured. It defaults to `5`. Set it to `0` (or `False`) to opt out: +Use `frame_context_lines` to control how many lines above and below each stack frame are captured. It defaults to `5`. Set it to `0` (or `False`) to opt out: ```python import sentry_sdk @@ -202,11 +178,20 @@ sentry_sdk.init( When unhandled errors and exceptions are sent to Sentry, the names and values of local variables that were set when the errors occurred are sent at the same time. -You can stop sending local variables to Sentry by setting `include_local_variables=False` in the `sentry_sdk.init()` call. +`stack_frame_variables` controls this and defaults to `True`. Local variable values aren't scrubbed by default. To filter out sensitive variables (such as `password` or `token`), use `"denylist"` mode, optionally with your own `terms`: -When using `data_collection`, `stack_frame_variables` controls this and defaults to `True`. +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "stack_frame_variables": {"mode": "denylist"}, + }, +) +``` -To opt out explicitly, set `stack_frame_variables` to `False`: +To opt out entirely, set `stack_frame_variables` to `False`: ```python import sentry_sdk @@ -223,7 +208,7 @@ sentry_sdk.init( While SQL queries are sent to Sentry, neither the full SQL query (`UPDATE app_user SET password='supersecret' WHERE id=1;`), nor the values of its parameters will ever be sent. A parameterized version of the query (`UPDATE app_user SET password='%s' WHERE id=%s;`) is sent instead. -When using `data_collection`, set `database_query_data` to `False` to stop collecting database query data: +Set `database_query_data` to `False` to stop collecting database query data: ```python import sentry_sdk @@ -238,7 +223,7 @@ sentry_sdk.init( ## GraphQL Documents And Variables -When using `data_collection`, the GraphQL query document and its variables are collected by default. Both can be disabled independently: +By default, the GraphQL query document and its variables are collected. Both can be disabled independently: ```python import sentry_sdk @@ -251,11 +236,9 @@ sentry_sdk.init( ) ``` -Without `data_collection` (and with `send_default_pii` unset or `False`), GraphQL documents and variables aren't collected. - ## Queue And Task Message Data -When using `data_collection`, message body data for queue and task-queue integrations is collected by default. Set `queues` to `False` to opt out: +By default, message body data for queue and task-queue integrations is collected. Set `queues` to `False` to opt out: ```python import sentry_sdk @@ -268,13 +251,9 @@ sentry_sdk.init( ) ``` -Without `data_collection` (and with `send_default_pii` unset or `False`), this data isn't collected. - ## LLM Inputs And Responses -When using Sentry in your AI apps, the SDK by default won't add LLM prompts, messages, or responses to spans. Some integrations still attach tool data by default, such as tool definitions and MCP tool arguments. See the documentation for the specific AI framework for details on what's attached and how to remove it. - -When using `data_collection`, the `gen_ai` category records both inputs and outputs unless you opt out. Metadata like the model ID and token counts is always collected. +By default, the `gen_ai` category records both the inputs and outputs of your AI integrations, such as LLM prompts, messages, and responses. Metadata like the model ID and token counts is always collected. See the documentation for the specific AI framework for details on what's attached. ```python import sentry_sdk @@ -287,27 +266,26 @@ sentry_sdk.init( ) ``` -`gen_ai` supersedes the per-integration `include_prompts` parameter. When `data_collection` is set, `gen_ai` determines whether prompt content is recorded, regardless of what an individual integration's `include_prompts` is set to. - -If you use `send_default_pii` instead, add `send_default_pii=True` to your `sentry_sdk.init()` call to start recording LLM inputs and responses. Most AI integrations have an additional parameter to control whether prompts should be included called `include_prompts`. See the documentation for the specific AI framework for more information. +Tool arguments, tool results, and prompt content of the MCP integration are controlled separately by the `mcp` category, which works the same way. ## `data_collection` Reference ### Keys -| Key | Type | Default | Description | -| ----------------------- | --------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `user_info` | `bool` | `True` | Populate `user.*` fields (`id`, `email`, `username`, `ip_address`) from instrumentation. | -| `cookies` | key-value behavior | `{"mode": "denylist"}` | Collect cookies. | -| `http_headers` | `{"request": key-value behavior}` | `{"request": {"mode": "denylist"}}` | Collect HTTP request headers. The Python SDK currently doesn't capture response headers. | -| `http_bodies` | `list[str]` | `["incoming_request", "outgoing_request", "outgoing_response"]` | Body types to collect. Set to `[]` to disable. The Python SDK currently doesn't capture incoming response bodies. | -| `url_query_params` | key-value behavior | `{"mode": "denylist"}` | Collect URL query parameters. | -| `graphql` | `{"document": bool, "variables": bool}` | both `True` | Collect the GraphQL query document and its variables. | -| `gen_ai` | `{"inputs": bool, "outputs": bool}` | both `True` | Collect generative AI input and output content. Metadata such as the model ID and token counts is always collected. | -| `database_query_data` | `bool` | `True` | Collect database query data. Query parameter values are never sent; queries are parameterized first. | -| `queues` | `bool` | `True` | Collect message body data for queue and task-queue integrations. | -| `stack_frame_variables` | `bool` or key-value behavior | `True` | Include local variable values captured within stack frames. Accepts a boolean (`True` collects all variables, `False` collects none) or a key-value behavior to filter which variables are sent by name (see [Filtering Stack Frame Variables](https://develop.sentry.dev/sdk/foundations/client/data-collection/#filtering-stack-frame-variables)). | -| `frame_context_lines` | `int` or `bool` | `5` | Source code lines captured above and below each stack frame. `True` means the default of `5`, `False` means `0`. | +| Key | Type | Default | Description | +| ----------------------- | --------------------------------------- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `user_info` | `bool` | `True` | Populate `user.*` fields (`id`, `email`, `username`, `ip_address`) from instrumentation. | +| `cookies` | key-value behavior | `{"mode": "denylist"}` | Collect cookies. | +| `http_headers` | `{"request": key-value behavior}` | `{"request": {"mode": "denylist"}}` | Collect HTTP request headers. The Python SDK currently doesn't capture response headers. | +| `http_bodies` | `list[str]` | `["incoming_request", "outgoing_request", "outgoing_response"]` | Body types to collect. Set to `[]` to disable. The Python SDK currently doesn't capture incoming response bodies. | +| `url_query_params` | key-value behavior | `{"mode": "denylist"}` | Collect URL query parameters. | +| `graphql` | `{"document": bool, "variables": bool}` | both `True` | Collect the GraphQL query document and its variables. | +| `gen_ai` | `{"inputs": bool, "outputs": bool}` | both `True` | Collect generative AI input and output content. Metadata such as the model ID and token counts is always collected. | +| `mcp` | `{"inputs": bool, "outputs": bool}` | both `True` | Collect MCP tool arguments, tool results, and prompt content. | +| `database_query_data` | `bool` | `True` | Collect database query data. Query parameter values are never sent; queries are parameterized first. | +| `queues` | `bool` | `True` | Collect message body data for queue and task-queue integrations. | +| `stack_frame_variables` | `bool` or key-value behavior | `True` | Include local variable values captured within stack frames. Accepts a boolean (`True` collects all variables, `False` collects none) or a key-value behavior to filter which variables are sent by name (see [Filtering Stack Frame Variables](https://develop.sentry.dev/sdk/foundations/client/data-collection/#filtering-stack-frame-variables)). | +| `frame_context_lines` | `int` or `bool` | `5` | Source code lines captured above and below each stack frame. `True` means the default of `5`, `False` means `0`. | ### Key-Value Collection Behavior @@ -324,37 +302,3 @@ The `cookies`, `http_headers["request"]`, and `url_query_params` categories take | `"off"` | Collect nothing in this category. | `terms` match partially and case-insensitively, so `"-ip"` matches `X-Real-IP`. Filtered values are replaced with `[Filtered]`; the key itself is always preserved. The built-in sensitive denylist (`auth`, `token`, `secret`, `password`, `key`, `session`, and similar) always applies, even in `"allowlist"` mode. - -### Preserving `send_default_pii=False` Behavior - -To keep the conservative collection you get from `send_default_pii=False` while using `data_collection`, opt out of each category explicitly: - -```python -import sentry_sdk - -sentry_sdk.init( - dsn="___PUBLIC_DSN___", - data_collection={ - "user_info": False, - "gen_ai": {"inputs": False, "outputs": False}, - "graphql": {"document": False, "variables": False}, - "database_query_data": False, - "queues": False, - "http_bodies": [], - "cookies": { - "mode": "denylist", - "terms": ["forwarded", "-ip", "remote-", "via", "-user"], - }, - "http_headers": { - "request": { - "mode": "denylist", - "terms": ["forwarded", "-ip", "remote-", "via", "-user"], - }, - }, - "url_query_params": { - "mode": "denylist", - "terms": ["forwarded", "-ip", "remote-", "via", "-user"], - }, - }, -) -``` diff --git a/docs/platforms/python/data-management/data-collected__v2.x.mdx b/docs/platforms/python/data-management/data-collected__v2.x.mdx new file mode 100644 index 0000000000000..f5575dc3330db --- /dev/null +++ b/docs/platforms/python/data-management/data-collected__v2.x.mdx @@ -0,0 +1,362 @@ +--- +title: Data Collected +description: "See what data is collected by the Sentry Python SDK." +sidebar_order: 1 +--- + +This page describes the data collected by version `2.x` of the Python SDK. Version `3.x` collects more data by default and removed the `send_default_pii` option. To see the `3.x` docs, switch to `latest` in the version selector. + +Sentry takes data privacy very seriously and has default settings in place that prioritize data safety, especially when it comes to personally identifiable information (PII) data. When you add the Sentry SDK to your application, you allow it to collect data and send it to Sentry during the runtime of your application. + +The category types and amount of data collected vary, depending on the integrations you've enabled in the Sentry SDK. This page lists data categories that the Sentry Python SDK collects. + + + +You can control many of the categories listed here with the `data_collection` option, which lets you opt in or out of each data category individually. + +The `send_default_pii` option is still supported, but `send_default_pii` will be removed in version 3.0 of the SDK. + +How much data the SDK collects by default depends on which option you use. Without `data_collection` (and with `send_default_pii` unset or `False`), the SDK collects conservatively, and the defaults described on this page apply. + +As soon as you pass a `data_collection` dictionary, the categories you don't set explicitly fall back to their `data_collection` defaults, which are more permissive. For example, cookies, query parameters (with sensitive values scrubbed), and AI message content are then collected unless you opt out. Setting `send_default_pii=True` is roughly equivalent to enabling all `data_collection` categories. + +If you set both, `send_default_pii` is ignored entirely and the SDK emits a `DeprecationWarning`. + +Regardless of these options, you can always scrub any data before it's sent to Sentry. See Scrubbing Sensitive Data for details. + + + +## HTTP Headers + +By default, the Sentry SDK sends HTTP request headers to Sentry but filters out any headers that contain sensitive data. (See the [list of headers](https://github.com/getsentry/sentry-python/blob/master/sentry_sdk/integrations/_wsgi_common.py#L28-L35) that are filtered). The Python SDK doesn't capture response headers. + +When using `data_collection`, request headers are collected with sensitive values scrubbed. Use `http_headers` to control this: + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + # Collect nothing: + "http_headers": {"request": {"mode": "off"}}, + # Or only send real values for the listed headers: + # "http_headers": {"request": {"mode": "allowlist", "terms": ["content-type"]}}, + # Or collect everything, filtering additional terms: + # "http_headers": {"request": {"mode": "denylist", "terms": ["-ip"]}}, + }, +) +``` + +Values whose keys match Sentry's built-in sensitive denylist (such as `auth`, `token`, or `password`) are always scrubbed, while the keys are kept. See [Key-Value Collection Behavior](#key-value-collection-behavior) below for details on `mode` and `terms`. + +If you use `send_default_pii` instead, set it to `True` in the `sentry_sdk.init()` call to send all HTTP headers. + +Additionally a [data scrubber](/platforms/python/data-management/sensitive-data/) removes sensitive data from headers (and a lot of other fields) right before sending data to Sentry. + +## Cookies + +By default, the Sentry SDK doesn't send cookies. Sentry tries to remove any cookies that contain sensitive information, such as the Session ID and CSRF Token cookies in Django. + +When using `data_collection`, cookies are collected by default with sensitive values scrubbed. Opt out with `{"mode": "off"}`, or restrict which values are sent using `"allowlist"` or `"denylist"` mode: + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "cookies": {"mode": "off"}, + }, +) +``` + +If you use `send_default_pii` instead, set it to `True` in the `sentry_sdk.init()` call to send cookies. + +Additionally a [data scrubber](/platforms/python/data-management/sensitive-data/) removes sensitive data from cookies (and a lot of other fields) right before sending data to Sentry. + +## Information About Logged-in User + +By default, the Sentry SDK doesn't send any information about the logged-in user, such as email address, user ID, or username. Even if enabled, the type of logged-in user information you'll be able to send depends on the integrations you enable in Sentry's SDK. Most integrations won't send any user information. Some will only set the user ID, but there are a few that will set the user ID, username, and email address. + +When using `data_collection`, the SDK populates user identity fields (`user.id`, `user.email`, `user.username`) from instrumentation by default. To disable this, set `user_info` to `False`: + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "user_info": False, + }, +) +``` + +If you use `send_default_pii` instead, set it to `True` in the `sentry_sdk.init()` call to start sending logged-in user information. + +## Users' IP Address + +By default, the Sentry SDK doesn't send the user's IP address. Even if enabled, whether you're able to send the user's IP address or not, will depend on the integrations you enable in Sentry's SDK. Most integrations won't set the user's IP address at all. + +When using `data_collection`, the user's IP address is sent by default. Disable it by setting `user_info` to `False`. + +Even when this is disabled, IP addresses can still reach Sentry through collected HTTP headers, cookies, or query parameters (for example, the `X-Forwarded-For` header). If you use `data_collection`, add these terms to the deny lists for those categories so their values are filtered: + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "http_headers": { + "request": { + "mode": "denylist", + "terms": ["forwarded", "-ip", "remote-", "via", "-user"], + }, + }, + "cookies": { + "mode": "denylist", + "terms": ["forwarded", "-ip", "remote-", "via", "-user"], + }, + "url_query_params": { + "mode": "denylist", + "terms": ["forwarded", "-ip", "remote-", "via", "-user"], + }, + }, +) +``` + +If you use `send_default_pii` instead, set it to `True` in the `sentry_sdk.init()` call to send the user's IP address. + +## Request URL + +The full request URL of outgoing and incoming HTTP requests is **always sent to Sentry**. Depending on your application, this could contain PII data. + +## Request Query String + +By default, the full request query string of outgoing and incoming HTTP requests is sent to Sentry. Depending on your application, this could contain PII data. For example, a query string like `?user_id=1234`, where `1234` is a user id (which may be considered PII). + +When using `data_collection`, use `url_query_params` to control this. Set it to `{"mode": "off"}` to disable collection entirely, or use `"allowlist"` / `"denylist"` mode to filter which values are sent. Values whose keys match the built-in sensitive denylist (terms like `auth`, `token`, `password`, and `secret`) are scrubbed automatically. + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "url_query_params": {"mode": "off"}, + }, +) +``` + +Sentry also has some additional [server-side data scrubbing](/security-legal-pii/scrubbing/server-side-scrubbing/) in place to remove sensitive data from the query string. + +## Request Body + +The request body of incoming HTTP requests can be sent to Sentry. Whether it's sent or not, depends on the type and size of request body as described below: + +- **The type of the request body:** + - JSON and form bodies are sent + - Raw request bodies are always removed + - Uploaded files in the request bodies are never sent to Sentry +- **The size of the request body:** There's a ["max_request_body_size"](/platforms/python/configuration/options/#max-request-body-size) option that's set to `medium` by default. This means that larger request bodies aren't sent to Sentry. + +If you want to prevent bodies from being sent to Sentry altogether, set `max_request_body_size` to `"never"`. + +When using `data_collection`, incoming and outgoing request bodies, as well as outgoing response bodies, are collected by default. To disable body collection, set `http_bodies` to an empty list, or provide only the body types you want: + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + # Collect only incoming request bodies: + data_collection={ + "http_bodies": ["incoming_request"], + }, +) +``` + +The valid body types are `"incoming_request"`, `"outgoing_request"`, and `"outgoing_response"`. Currently, only the Ariadne and Strawberry integrations use `"outgoing_response"`, to attach the GraphQL response to error events. The Python SDK doesn't capture incoming response bodies. + +`max_request_body_size` still applies on top of `http_bodies`. + +## Source Context + +When an unhandled exception is sent to Sentry, a snapshot of the source code surrounding the line where the error originates is sent with it. + +To opt out of sending this source context to Sentry, set `include_source_context` to `False`. + +When using `data_collection`, use `frame_context_lines` to control how many lines above and below each stack frame are captured. It defaults to `5`. Set it to `0` (or `False`) to opt out: + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "frame_context_lines": 0, + }, +) +``` + +## Local Variables In Stack Trace + +When unhandled errors and exceptions are sent to Sentry, the names and values of local variables that were set when the errors occurred are sent at the same time. + +You can stop sending local variables to Sentry by setting `include_local_variables=False` in the `sentry_sdk.init()` call. + +When using `data_collection`, `stack_frame_variables` controls this and defaults to `True`. + +To opt out explicitly, set `stack_frame_variables` to `False`: + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "stack_frame_variables": False, + }, +) +``` + +## SQL Queries + +While SQL queries are sent to Sentry, neither the full SQL query (`UPDATE app_user SET password='supersecret' WHERE id=1;`), nor the values of its parameters will ever be sent. A parameterized version of the query (`UPDATE app_user SET password='%s' WHERE id=%s;`) is sent instead. + +When using `data_collection`, set `database_query_data` to `False` to stop collecting database query data: + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "database_query_data": False, + }, +) +``` + +## GraphQL Documents And Variables + +When using `data_collection`, the GraphQL query document and its variables are collected by default. Both can be disabled independently: + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "graphql": {"document": False, "variables": False}, + }, +) +``` + +Without `data_collection` (and with `send_default_pii` unset or `False`), GraphQL documents and variables aren't collected. + +## Queue And Task Message Data + +When using `data_collection`, message body data for queue and task-queue integrations is collected by default. Set `queues` to `False` to opt out: + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "queues": False, + }, +) +``` + +Without `data_collection` (and with `send_default_pii` unset or `False`), this data isn't collected. + +## LLM Inputs And Responses + +When using Sentry in your AI apps, the SDK by default won't add LLM prompts, messages, or responses to spans. Some integrations still attach tool data by default, such as tool definitions and MCP tool arguments. See the documentation for the specific AI framework for details on what's attached and how to remove it. + +When using `data_collection`, the `gen_ai` category records both inputs and outputs unless you opt out. Metadata like the model ID and token counts is always collected. + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "gen_ai": {"inputs": False, "outputs": False}, + }, +) +``` + +`gen_ai` supersedes the per-integration `include_prompts` parameter. When `data_collection` is set, `gen_ai` determines whether prompt content is recorded, regardless of what an individual integration's `include_prompts` is set to. + +If you use `send_default_pii` instead, add `send_default_pii=True` to your `sentry_sdk.init()` call to start recording LLM inputs and responses. Most AI integrations have an additional parameter to control whether prompts should be included called `include_prompts`. See the documentation for the specific AI framework for more information. + +## `data_collection` Reference + +### Keys + +| Key | Type | Default | Description | +| ----------------------- | --------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `user_info` | `bool` | `True` | Populate `user.*` fields (`id`, `email`, `username`, `ip_address`) from instrumentation. | +| `cookies` | key-value behavior | `{"mode": "denylist"}` | Collect cookies. | +| `http_headers` | `{"request": key-value behavior}` | `{"request": {"mode": "denylist"}}` | Collect HTTP request headers. The Python SDK currently doesn't capture response headers. | +| `http_bodies` | `list[str]` | `["incoming_request", "outgoing_request", "outgoing_response"]` | Body types to collect. Set to `[]` to disable. The Python SDK currently doesn't capture incoming response bodies. | +| `url_query_params` | key-value behavior | `{"mode": "denylist"}` | Collect URL query parameters. | +| `graphql` | `{"document": bool, "variables": bool}` | both `True` | Collect the GraphQL query document and its variables. | +| `gen_ai` | `{"inputs": bool, "outputs": bool}` | both `True` | Collect generative AI input and output content. Metadata such as the model ID and token counts is always collected. | +| `database_query_data` | `bool` | `True` | Collect database query data. Query parameter values are never sent; queries are parameterized first. | +| `queues` | `bool` | `True` | Collect message body data for queue and task-queue integrations. | +| `stack_frame_variables` | `bool` or key-value behavior | `True` | Include local variable values captured within stack frames. Accepts a boolean (`True` collects all variables, `False` collects none) or a key-value behavior to filter which variables are sent by name (see [Filtering Stack Frame Variables](https://develop.sentry.dev/sdk/foundations/client/data-collection/#filtering-stack-frame-variables)). | +| `frame_context_lines` | `int` or `bool` | `5` | Source code lines captured above and below each stack frame. `True` means the default of `5`, `False` means `0`. | + +### Key-Value Collection Behavior + +The `cookies`, `http_headers["request"]`, and `url_query_params` categories take a dictionary with a `mode` and an optional list of `terms`: + +```python +{"mode": "denylist", "terms": ["forwarded", "-ip", "remote-", "via", "-user"]} +``` + +| `mode` | Behavior | +| ------------- | --------------------------------------------------------------------------------------------------------------------- | +| `"denylist"` | Collect everything, replacing the value of any key matching `terms` (in addition to the built-in sensitive denylist). | +| `"allowlist"` | Only keys matching `terms` send their real value. Every other key is kept, but its value is replaced. | +| `"off"` | Collect nothing in this category. | + +`terms` match partially and case-insensitively, so `"-ip"` matches `X-Real-IP`. Filtered values are replaced with `[Filtered]`; the key itself is always preserved. The built-in sensitive denylist (`auth`, `token`, `secret`, `password`, `key`, `session`, and similar) always applies, even in `"allowlist"` mode. + +### Preserving `send_default_pii=False` Behavior + +To keep the conservative collection you get from `send_default_pii=False` while using `data_collection`, opt out of each category explicitly: + +```python +import sentry_sdk + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + data_collection={ + "user_info": False, + "gen_ai": {"inputs": False, "outputs": False}, + "graphql": {"document": False, "variables": False}, + "database_query_data": False, + "queues": False, + "http_bodies": [], + "cookies": { + "mode": "denylist", + "terms": ["forwarded", "-ip", "remote-", "via", "-user"], + }, + "http_headers": { + "request": { + "mode": "denylist", + "terms": ["forwarded", "-ip", "remote-", "via", "-user"], + }, + }, + "url_query_params": { + "mode": "denylist", + "terms": ["forwarded", "-ip", "remote-", "via", "-user"], + }, + }, +) +``` diff --git a/docs/platforms/python/data-management/sensitive-data/index.mdx b/docs/platforms/python/data-management/sensitive-data/index.mdx index ed92f8e4d661f..4556c6d55e2f4 100644 --- a/docs/platforms/python/data-management/sensitive-data/index.mdx +++ b/docs/platforms/python/data-management/sensitive-data/index.mdx @@ -33,7 +33,7 @@ Ensure that your team is aware of your company's policy around what can and cann The SDK can be configured to collect or ignore specific data using the [`data_collection`](../../configuration/options/#data_collection) option. -Alternately, you can use the simpler [`send_default_pii`](../../configuration/options/#send_default_pii) option by setting it to `True` or `False`. Note that `send_default_pii` will be removed in version 3.0 of the SDK in favor of the more fine-grained [`data_collection`](../../configuration/options/#data_collection). +In SDK versions prior to `3.0`, you can alternatively use the simpler [`send_default_pii`](../../configuration/options/#send_default_pii) option by setting it to `True` or `False`. If you _do not_ wish to use the default PII behavior, you can also choose to identify users in a more controlled manner, using our [user identity context](../../enriching-events/identify-user/). @@ -41,21 +41,27 @@ If you _do not_ wish to use the default PII behavior, you can also choose to ide ### `event_scrubber` + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, the SDK scrubs sensitive values through the built-in denylist of the [`data_collection`](../../configuration/options/#data_collection) option, which you can extend with your own `terms`. Use for custom scrubbing. + + + If using `send_default_pii`, you can use the configuration parameter to simplify removing sensitive data from your event payload. The event scrubber has no effect when using `data_collection`. ### , , & -The SDK provides a hook, which is invoked before an error or message event is sent and can be used to modify event data to remove sensitive information. The SDK also provides a hook, that does the same thing for transactions, and a hook, that does the same thing for spans in stream mode. We recommend using these hooks in the SDK to **scrub any data before it is sent**, to ensure that sensitive data never leaves the local environment. +The SDK provides a hook, which is invoked before an error or message event is sent and can be used to modify event data to remove sensitive information. The SDK also provides a hook, that does the same thing for spans. In SDK versions prior to `3.0`, does the same thing for transactions, and is only available in stream mode. We recommend using these hooks in the SDK to **scrub any data before it is sent**, to ensure that sensitive data never leaves the local environment. Sensitive data may appear in the following areas: -- Stack-locals → The SDK picks up variable values within the stack trace. These can be scrubbed, or this behavior can be disabled altogether if necessary. +- Stack-locals → The SDK picks up variable values within the stack trace. These can be scrubbed with the `stack_frame_variables` setting of `data_collection`, or this behavior can be disabled altogether if necessary. - Breadcrumbs → The SDK picks up previously executed log statements. **Do not log PII** if using this feature and including log statements as breadcrumbs in the event. The SDK will also record database queries, which may need to be scrubbed. The SDK will add the HTTP query string and fragment as a data attribute to the breadcrumb, which may need to be scrubbed. -- User context → Automated behavior is controlled via . +- User context → Automated behavior is controlled via the `user_info` setting of `data_collection` (in SDK versions prior to `3.0`, also via ). - HTTP context → Query strings are picked up in web frameworks as part of the HTTP request context. - Transaction Names → In certain situations, transaction names might contain sensitive data. For example, an HTTP request transaction might have a raw URL like `/users/1234/details` as its name (where `1234` is a user id, which may be considered PII). In most cases, our SDK can parameterize URLs and routes successfully, that is, turn `/users/1234/details` into `/users/:userid/details`. However, depending on the web framework, your routing configuration, and a few other factors, the SDKs might not be able to completely parameterize all of your URLs. - HTTP Spans → The SDK includes the HTTP query string and fragment as a data attribute, which means the HTTP span may need to be scrubbed. @@ -86,4 +92,4 @@ As a best practice you should always avoid logging confidential information. If - Anonymize the confidential information within the log statements (for example, swap out email addresses -> for internal identifiers) - Use to filter it out from breadcrumbs before it is attached -- Set the `level` parameter in the logging integrations you use to `None`. +- Set the `breadcrumb_level` parameter in the logging integrations you use to `None` (in SDK versions prior to `3.0`, the `level` parameter). diff --git a/docs/platforms/python/index.mdx b/docs/platforms/python/index.mdx index 871d81a8f54aa..d03e19ab9abd4 100644 --- a/docs/platforms/python/index.mdx +++ b/docs/platforms/python/index.mdx @@ -92,7 +92,7 @@ asyncio.run(main()) The Sentry SDK automatically enables integrations for many popular libraries, so operations like HTTP requests or database queries made with supported libraries will be captured as spans automatically. -However, spans are only created within an existing transaction. If you're not using a supported framework that creates transactions automatically, you'll need to create them manually using `sentry_sdk.start_transaction()`. +In SDK versions prior to `3.0`, these spans are only created within an existing transaction. If you're not using a supported framework that starts transactions automatically, start one manually using `sentry_sdk.start_transaction()`. See Custom Instrumentation for more info. @@ -100,7 +100,7 @@ See Custom I import sentry_sdk def some_function(): - with sentry_sdk.start_transaction(op="task", name="Test Transaction"): + with sentry_sdk.start_span(name="Test Span", attributes={"sentry.op": "task"}): ... ``` @@ -108,7 +108,7 @@ def some_function(): Use `sentry_sdk.logger` to send structured logs at different levels. You can include searchable attributes with each message. -To capture records from Python's standard-library `logging` module or Loguru, configure `capture_sentry_logs=True` on the corresponding integration. See the standard logging and Loguru integration guides. +To capture records from Python's standard-library `logging` module or Loguru as Sentry logs, add the corresponding integration to your `integrations`. See the standard logging and Loguru integration guides. See Set Up Logs for all available logging methods and formatting options. @@ -142,7 +142,8 @@ Run this code after `sentry_sdk.init()` to send a test error, along with a trace ```python import sentry_sdk -with sentry_sdk.start_transaction(op="test", name="Verify Sentry setup"): +# In SDK 2.x, use sentry_sdk.start_transaction(op="test", name="Verify Sentry setup") instead +with sentry_sdk.start_span(name="Verify Sentry setup", attributes={"sentry.op": "test"}): sentry_sdk.logger.info("Sentry verification log") sentry_sdk.metrics.count("sentry.verification", 1) 1 / 0 diff --git a/docs/platforms/python/integrations/aiohttp/aiohttp-client.mdx b/docs/platforms/python/integrations/aiohttp/aiohttp-client.mdx index 3b0d108c40653..38d1f5e9b192d 100644 --- a/docs/platforms/python/integrations/aiohttp/aiohttp-client.mdx +++ b/docs/platforms/python/integrations/aiohttp/aiohttp-client.mdx @@ -38,8 +38,8 @@ import aiohttp async def main(): sentry_sdk.init(...) # same as above - # or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): async with aiohttp.ClientSession() as session: async with session.get("https://sentry.io/") as response: print("Status:", response.status) @@ -49,7 +49,7 @@ async def main(): asyncio.run(main()) ``` -This will create a transaction called `testing_sentry` in the Performance section of [sentry.io](https://sentry.io) and will create spans for the outgoing HTTP requests. +This will create a service span called `testing_sentry`, visible in the Traces section of [sentry.io](https://sentry.io), with child spans for the outgoing HTTP requests. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). diff --git a/docs/platforms/python/integrations/aiohttp/index.mdx b/docs/platforms/python/integrations/aiohttp/index.mdx index 7f44429622870..a35d63cefdcf7 100644 --- a/docs/platforms/python/integrations/aiohttp/index.mdx +++ b/docs/platforms/python/integrations/aiohttp/index.mdx @@ -67,7 +67,6 @@ sentry_sdk.init( # same as above integrations=[ AioHttpIntegration( - transaction_style="...", # type: str failed_request_status_codes={...} # type: collections.abc.Set[int] ), ], @@ -78,6 +77,12 @@ You can pass the following keyword arguments to `AioHttpIntegration()`: ### `transaction_style` + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, service spans are always named after the route pattern, for example `/path/{id}`. + + + Configure the way Sentry names transactions: - `GET /path/{id}` if you set `transaction_style="method_and_path_pattern"` diff --git a/docs/platforms/python/integrations/aiomysql/index.mdx b/docs/platforms/python/integrations/aiomysql/index.mdx index 64345d846c756..3d1b1469c90d3 100644 --- a/docs/platforms/python/integrations/aiomysql/index.mdx +++ b/docs/platforms/python/integrations/aiomysql/index.mdx @@ -71,8 +71,8 @@ async def main(): db="test", ) try: - # or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): async with conn.cursor() as cur: await cur.execute("SELECT 'Hello World'") result = await cur.fetchone() @@ -82,7 +82,7 @@ async def main(): asyncio.run(main()) ``` -This will create a transaction called `testing_sentry` in the Performance section of [sentry.io](https://sentry.io) and will create a span for the `SELECT` statement. +This will create a service span called `testing_sentry` in the Traces section of [sentry.io](https://sentry.io) and will create a span for the `SELECT` statement. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). diff --git a/docs/platforms/python/integrations/ariadne/index.mdx b/docs/platforms/python/integrations/ariadne/index.mdx index 7f082a1e4c9be..3156c4688d5e1 100644 --- a/docs/platforms/python/integrations/ariadne/index.mdx +++ b/docs/platforms/python/integrations/ariadne/index.mdx @@ -78,10 +78,9 @@ This will create a corresponding `GraphQLError` in the Issues section of ## Options The Ariadne integration can capture request and response payload for each GraphQL -error that happens. Since these may contain sensitive data, no request and response -data will be attached by default. +error that happens. This is enabled by default. -To attach this data, use the `data_collection` option. The `graphql` key controls the query document and its variables in the request +To control which data is attached, use the `data_collection` option. The `graphql` key controls the query document and its variables in the request payload, and the `outgoing_response` entry in `http_bodies` controls the response payload: @@ -95,26 +94,9 @@ sentry_sdk.init( ) ``` -These are also the defaults when you pass a `data_collection` dictionary, so you only -need to set the keys you want to change. See Data Collected for all available keys. +These are the defaults, so you only need to set the keys you want to change. See Data Collected for all available keys. -Alternatively, you can initialize the SDK with the `send_default_pii` option set to `True`, though `send_default_pii` will be removed in version 3.0 of the SDK: - -```python -sentry_sdk.init( - # same options as above - send_default_pii=True, -) -``` - - - -Since `send_default_pii` is a global SDK option, setting it to `True` will affect all integrations, not just Ariadne. Please make sure to -[scrub sensitive data](/platforms/python/data-management/sensitive-data/) -from events before enabling this option. With `data_collection`, you can enable -only the categories you need instead. - - +In SDK versions prior to `3.0`, this data isn't attached by default. To attach it, pass a `data_collection` dictionary as shown above, or set the `send_default_pii` option to `True`. Since `send_default_pii` is a global SDK option, setting it to `True` affects all integrations, so make sure to [scrub sensitive data](/platforms/python/data-management/sensitive-data/) from events first. ## Supported Versions diff --git a/docs/platforms/python/integrations/arq/index.mdx b/docs/platforms/python/integrations/arq/index.mdx index f093b455856be..fee9a4c409226 100644 --- a/docs/platforms/python/integrations/arq/index.mdx +++ b/docs/platforms/python/integrations/arq/index.mdx @@ -39,14 +39,14 @@ async def main(): sentry_sdk.init(...) # same as above redis = await create_pool(RedisSettings()) - # or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): r = await redis.enqueue_job("add_numbers", 1, 2) asyncio.run(main()) ``` -When you run `run.py` it will create a transaction called `testing_sentry` in the Performance section of [sentry.io](https://sentry.io), and create a span for enqueuing the job. +When you run `run.py` it will create a service span called `testing_sentry` in the Traces section of [sentry.io](https://sentry.io), and create a span for enqueuing the job. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). @@ -66,7 +66,7 @@ class WorkerSettings: functions = [add_numbers] ``` -When you run a worker with `arq demo.WorkerSettings` it will create a transaction called `add_numbers` in the Performance section of [sentry.io](https://sentry.io), and will also create and issue in Sentry and connect it to the transaction. +When you run a worker with `arq demo.WorkerSettings` it will create a service span called `add_numbers` in the Traces section of [sentry.io](https://sentry.io), and will also create an issue in Sentry and connect it to the service span. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). diff --git a/docs/platforms/python/integrations/asgi/index.mdx b/docs/platforms/python/integrations/asgi/index.mdx index aa54565fbf41d..ae30612db4387 100644 --- a/docs/platforms/python/integrations/asgi/index.mdx +++ b/docs/platforms/python/integrations/asgi/index.mdx @@ -103,7 +103,7 @@ Additionally, a transaction will show up in the "Performance" section on [sentry ## Behavior -- Request data is attached to all events: **HTTP method, URL, headers**. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: **HTTP method, URL, headers**. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. - Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. diff --git a/docs/platforms/python/integrations/asyncpg/index.mdx b/docs/platforms/python/integrations/asyncpg/index.mdx index cae445b7f0bb4..15dc6d7b1fa83 100644 --- a/docs/platforms/python/integrations/asyncpg/index.mdx +++ b/docs/platforms/python/integrations/asyncpg/index.mdx @@ -34,8 +34,8 @@ import asyncpg async def main(): sentry_sdk.init(...) # same as above - # or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): conn = await asyncpg.connect(DATABASE_URL) await conn.fetch("SELECT * FROM pg_catalog.pg_tables;") await conn.close() @@ -43,7 +43,7 @@ async def main(): asyncio.run(main()) ``` -This will create a transaction called `testing_sentry` in the Performance section of [sentry.io](https://sentry.io), and create spans for the `connect` and the `SELECT` operations. +This will create a service span called `testing_sentry`, visible in the Traces section of [sentry.io](https://sentry.io), with child spans for the `connect` and the `SELECT` operations. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). diff --git a/docs/platforms/python/integrations/aws-lambda/manual-instrumentation/index.mdx b/docs/platforms/python/integrations/aws-lambda/manual-instrumentation/index.mdx index 95942b5485dfc..5bd74aeae0d3b 100644 --- a/docs/platforms/python/integrations/aws-lambda/manual-instrumentation/index.mdx +++ b/docs/platforms/python/integrations/aws-lambda/manual-instrumentation/index.mdx @@ -96,7 +96,7 @@ With the AWS Lambda integration enabled, the Python SDK will: You can add more data as described here. -- Request data including **HTTP method, URL, headers, form data, and JSON payloads** will be attached to all events. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information such as user ids, usernames, cookies, authorization headers, and IP addresses, unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data including **HTTP method, URL, headers, form data, and JSON payloads** will be attached to all events. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. - Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. diff --git a/docs/platforms/python/integrations/boto3/index.mdx b/docs/platforms/python/integrations/boto3/index.mdx index 03011e503e660..13019a5986d48 100644 --- a/docs/platforms/python/integrations/boto3/index.mdx +++ b/docs/platforms/python/integrations/boto3/index.mdx @@ -27,7 +27,7 @@ Sentry's Boto3 integration is enabled automatically if you have the `boto3` pack ## Verify Your Setup -To verify that Sentry captures your Boto3 requests to Amazon Web Services, add this code to your app, which will create a transaction called `testing_sentry` in the [Traces](https://sentry.io/orgredirect/organizations/:orgslug/explore/traces/) section: +To verify that Sentry captures your Boto3 requests to Amazon Web Services, add this code to your app, which will create a service span called `testing_sentry` in the [Traces](https://sentry.io/orgredirect/organizations/:orgslug/explore/traces/) section: ```python import sentry_sdk @@ -39,8 +39,8 @@ def main(): s3 = boto3.resource('s3') - # or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): # make a request to the service and print out bucket names for bucket in s3.buckets.all(): print(bucket.name) diff --git a/docs/platforms/python/integrations/bottle/index.mdx b/docs/platforms/python/integrations/bottle/index.mdx index 78e85a4331b9c..a3ce50c4bfc22 100644 --- a/docs/platforms/python/integrations/bottle/index.mdx +++ b/docs/platforms/python/integrations/bottle/index.mdx @@ -54,7 +54,7 @@ It takes a couple of moments for the data to appear in [sentry.io](https://sentr - All exceptions leading to an Internal Server Error are reported. -- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. - Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. @@ -72,7 +72,6 @@ sentry_sdk.init( # same as above integrations=[ BottleIntegration( - transaction_style="endpoint", failed_request_status_codes={*range(500, 600)}, ), ], @@ -84,6 +83,12 @@ Each of the following options are supported as keyword arguments to `BottleInteg ### `transaction_style` + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, service spans are always named after the route pattern, for example `/myurl/`. + + + The `transaction_style` option specifies how the transaction name is generated. You can set the option to `"endpoint"` (the default) or `"url"`. For example, given the following route: diff --git a/docs/platforms/python/integrations/celery/index.mdx b/docs/platforms/python/integrations/celery/index.mdx index 74f6d04882f84..b731a2a65d29e 100644 --- a/docs/platforms/python/integrations/celery/index.mdx +++ b/docs/platforms/python/integrations/celery/index.mdx @@ -82,7 +82,7 @@ def init_sentry(**_kwargs): # Enables Profiling. # Set to 1.0 to profile 100% of sessions. profile_session_sample_rate=1.0, - # Profiles are collected while a transaction is active. + # Profiles are collected while a span is active. profile_lifecycle="trace", ) @@ -115,13 +115,13 @@ def main(): # Enables Profiling. # Set to 1.0 to profile 100% of sessions. profile_session_sample_rate=1.0, - # Profiles are collected while a transaction is active. + # Profiles are collected while a span is active. profile_lifecycle="trace", ) # Enqueueing a task to be processed by Celery - with sentry_sdk.start_transaction(name="calling-a-celery-task"): - # or sentry_sdk.traces.start_span(name="calling-a-celery-task", parent_span=None) in stream mode + # In SDK 2.x, use sentry_sdk.start_transaction(name="calling-a-celery-task") instead + with sentry_sdk.start_span(name="calling-a-celery-task"): result = add.delay(4, 4) if __name__ == "__main__": @@ -150,7 +150,7 @@ You can also manually capture performance data – see standard logging and Loguru integration guides. +To capture records from Python's standard-library `logging` module or Loguru as Sentry logs, add the corresponding integration to your `integrations`. See the standard logging and Loguru integration guides. See Set Up Logs for all available logging methods and formatting options. diff --git a/docs/platforms/python/integrations/chalice/index.mdx b/docs/platforms/python/integrations/chalice/index.mdx index 00367578f4898..301ffe8828acb 100644 --- a/docs/platforms/python/integrations/chalice/index.mdx +++ b/docs/platforms/python/integrations/chalice/index.mdx @@ -43,7 +43,7 @@ When you enter the `"/"` route or the scheduled task is run, an error event will ## Behavior -- Request data is attached to all events: HTTP method, URL, headers, form data, JSON payloads. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: HTTP method, URL, headers, form data, JSON payloads. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. - Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. diff --git a/docs/platforms/python/integrations/clickhouse-driver/index.mdx b/docs/platforms/python/integrations/clickhouse-driver/index.mdx index a4b518f2315c7..5af31e964f8a0 100644 --- a/docs/platforms/python/integrations/clickhouse-driver/index.mdx +++ b/docs/platforms/python/integrations/clickhouse-driver/index.mdx @@ -27,7 +27,7 @@ If you have the `clickhouse-driver` package in your dependencies, the clickhouse -By default, the parameters of the query are not retrieved. To see the query parameters in Sentry, enable `database_query_data` in the `data_collection` option, or enable `send_default_pii`. `send_default_pii` will be removed in version 3.0 of the SDK. +The integration doesn't record query parameters or the query ID. In SDK versions prior to `3.0`, you can see the query parameters in Sentry by enabling `database_query_data` in the `data_collection` option, or by enabling `send_default_pii`. ## Verify @@ -37,8 +37,8 @@ from clickhouse_driver import Client def main(): sentry_init(...) # same as above - # or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): client = Client(host=DATABASE_HOST) client.execute("DROP TABLE IF EXISTS sentry_test") client.execute("CREATE TABLE sentry_test (x Int32) ENGINE = Memory") @@ -47,7 +47,7 @@ def main(): main() ``` -This will create a transaction called `testing_sentry` in the Performance section of [sentry.io](https://sentry.io), and create spans for the database operations. +This will create a service span called `testing_sentry` in the Traces section of [sentry.io](https://sentry.io), and create spans for the database operations. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). diff --git a/docs/platforms/python/integrations/django/index.mdx b/docs/platforms/python/integrations/django/index.mdx index b848d8274af8e..7bef7aa986c98 100644 --- a/docs/platforms/python/integrations/django/index.mdx +++ b/docs/platforms/python/integrations/django/index.mdx @@ -77,9 +77,9 @@ To further customize your setup, review the [Options section](#options) below. Sentry automatically captures errors and reports issues for you. You can also expect the following for your Django project: -- If you use `django.contrib.auth`, and you've either enabled `user_info` in the `data_collection` option or set `send_default_pii=True` in your call to `init`, user data (such as current user ID, email address, username) will be attached to error events. `send_default_pii` will be removed in version 3.0 of the SDK. +- If you use `django.contrib.auth`, user data (such as current user ID, email address, username) will be attached to error events. Turn this off by setting `user_info` to `False` in the `data_collection` option. In SDK versions prior to `3.0`, user data is only attached if you enable `user_info` in `data_collection` or set `send_default_pii=True`. - Request data will be attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. -- Logs emitted by any logger will be recorded as breadcrumbs by the [Logging](/platforms/python/integrations/logging/) integration (this integration is enabled by default). +- If you add the [Logging](/platforms/python/integrations/logging/) integration, logs emitted by any logger will be recorded as breadcrumbs. In SDK versions prior to `3.0`, the Logging integration is enabled by default. To learn how to manually report issues, see Capturing Errors. @@ -101,7 +101,7 @@ You can also manually capture performance data – see standard logging and Loguru integration guides. +To capture records from Python's standard-library `logging` module or Loguru as Sentry logs, add the corresponding integration to your `integrations`. See the standard logging and Loguru integration guides. See Set Up Logs for all available logging methods and formatting options. @@ -163,7 +163,6 @@ sentry_sdk.init( # ... integrations=[ DjangoIntegration( - transaction_style='url', middleware_spans=True, signals_spans=True, signals_denylist=[ @@ -181,6 +180,12 @@ You can pass the following keyword arguments to `DjangoIntegration()`: + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, service spans are always named after the route pattern, for example `/myproject/myview/`. + + + How to name transactions that show up in Sentry tracing. - `"/myproject/myview/"` if you set `transaction_style="url"`. @@ -211,10 +216,10 @@ The default is `[]`. - + -Create spans and track performance of all read operations to configured caches. The spans also include information if the cache access was a hit or a miss. Set to `True` to enable. -The default is `False`. +Create spans and track performance of all read operations to configured caches. The spans also include information if the cache access was a hit or a miss. Set to `False` to disable. +The default is `True`. In SDK versions prior to `3.0`, the default is `False`. diff --git a/docs/platforms/python/integrations/falcon/index.mdx b/docs/platforms/python/integrations/falcon/index.mdx index ad966bb3badcc..a42b9836b9aca 100644 --- a/docs/platforms/python/integrations/falcon/index.mdx +++ b/docs/platforms/python/integrations/falcon/index.mdx @@ -57,12 +57,18 @@ It takes a couple of moments for the data to appear in [sentry.io](https://sentr - All exceptions leading to an Internal Server Error are reported. -- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. - Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. ## Options + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, `FalconIntegration` doesn't accept any options, and service spans are always named after the route pattern, for example `/message/{message_id}`. + + + By adding `FalconIntegration` to your `sentry_sdk.init()` call explicitly, you can set options for `FalconIntegration` to change its behavior: diff --git a/docs/platforms/python/integrations/fastapi/index.mdx b/docs/platforms/python/integrations/fastapi/index.mdx index a8b591a8c6838..e4ea4214120c9 100644 --- a/docs/platforms/python/integrations/fastapi/index.mdx +++ b/docs/platforms/python/integrations/fastapi/index.mdx @@ -85,7 +85,7 @@ You can also expect the following for your FastAPI project: - By default, all exceptions leading to an Internal Server Error are captured and reported. The HTTP status codes to report on are configurable via the `failed_request_status_codes` [option](#options). - Request data will be attached to all events: HTTP method, URL, headers, form data, JSON payloads. Sentry excludes raw bodies and multipart file uploads. -- Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. To learn how to manually report issues, see Capturing Errors. @@ -104,7 +104,7 @@ You can also manually capture performance data – see standard logging and Loguru integration guides. +To capture records from Python's standard-library `logging` module or Loguru as Sentry logs, add the corresponding integration to your `integrations`. See the standard logging and Loguru integration guides. See Set Up Logs for all available logging methods and formatting options. @@ -167,12 +167,10 @@ sentry_sdk.init( # same as above integrations=[ StarletteIntegration( - transaction_style="endpoint", failed_request_status_codes={403, *range(500, 599)}, http_methods_to_capture=("GET",), ), FastApiIntegration( - transaction_style="endpoint", failed_request_status_codes={403, *range(500, 599)}, http_methods_to_capture=("GET",), ), @@ -184,6 +182,12 @@ You can pass the following keyword arguments to `StarletteIntegration()` and `Fa + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, service spans are always named after the route pattern, for example `/catalog/product/{product_id}`. + + + How to name transactions that show up in Sentry tracing. The default is `"url"`. diff --git a/docs/platforms/python/integrations/flask/index.mdx b/docs/platforms/python/integrations/flask/index.mdx index cb6c15eb2d78c..51f74c2ac86ee 100644 --- a/docs/platforms/python/integrations/flask/index.mdx +++ b/docs/platforms/python/integrations/flask/index.mdx @@ -85,9 +85,9 @@ To further customize your setup, review the [Options section](#options) below. Sentry automatically captures errors and reports issues for you. You can also expect the following for your Flask app: -- If you use `flask-login`, and you've either enabled `user_info` in the `data_collection` option or set `send_default_pii=True` in your call to `init`, user data (such as current user ID, email address, username) will be attached to error events. `send_default_pii` will be removed in version 3.0 of the SDK. +- If you use `flask-login`, user data (such as current user ID, email address, username) will be attached to error events. Turn this off by setting `user_info` to `False` in the `data_collection` option. In SDK versions prior to `3.0`, user data is only attached if you enable `user_info` in `data_collection` or set `send_default_pii=True`. - Request data will be attached to all events: HTTP method, URL, headers, form data, JSON payloads. Sentry excludes raw bodies and multipart file uploads. -- Logs emitted by any `app.logger` or _any_ logger will be recorded by the [Logging](/platforms/python/integrations/logging/) integration (this integration is enabled by default). +- If you add the [Logging](/platforms/python/integrations/logging/) integration, logs emitted by any `app.logger` or _any_ logger will be recorded by it. In SDK versions prior to `3.0`, the Logging integration is enabled by default. @@ -95,7 +95,7 @@ You can also expect the following for your Flask app: Use `sentry_sdk.logger` to send structured logs at different levels. You can include searchable attributes with each message. -To capture records from Python's standard-library `logging` module or Loguru, configure `capture_sentry_logs=True` on the corresponding integration. See the standard logging and Loguru integration guides. +To capture records from Python's standard-library `logging` module or Loguru as Sentry logs, add the corresponding integration to your `integrations`. See the standard logging and Loguru integration guides. See Set Up Logs for all available logging methods and formatting options. @@ -152,7 +152,6 @@ sentry_sdk.init( # ... integrations = [ FlaskIntegration( - transaction_style="url", http_methods_to_capture=("GET",), ), ], @@ -163,6 +162,12 @@ You can pass the following keyword arguments to `FlaskIntegration()`: + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, service spans are always named after the route pattern, for example `/myurl/`. + + + How to name transactions that show up in Sentry tracing. The default is `"endpoint"`. diff --git a/docs/platforms/python/integrations/gcp-functions/index.mdx b/docs/platforms/python/integrations/gcp-functions/index.mdx index a12ba3305f1c7..600242fe54d78 100644 --- a/docs/platforms/python/integrations/gcp-functions/index.mdx +++ b/docs/platforms/python/integrations/gcp-functions/index.mdx @@ -106,6 +106,6 @@ With the Google Cloud Functions integration enabled, the Python SDK will: - Function configured time (in seconds) - You can add more data as described here -- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. - Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. diff --git a/docs/platforms/python/integrations/gql/index.mdx b/docs/platforms/python/integrations/gql/index.mdx index fa6be7b4b4834..e8ae6282b16e6 100644 --- a/docs/platforms/python/integrations/gql/index.mdx +++ b/docs/platforms/python/integrations/gql/index.mdx @@ -28,11 +28,7 @@ If you have the `gql` package in your dependencies, the GQL integration will be ## Data Privacy and the GQL Integration -To ensure data privacy, the SDK avoids sending any information that may potentially contain personally identifiable information (PII) by default. See the docs for the `data_collection` and `send_default_pii` options for more information. - -For the GQL integration, this policy means that the SDK **doesn't send** the GraphQL queries and the `errors` information that the GraphQL server returns, unless you override the default configuration. - -To have Sentry record the GraphQL queries and the `errors` information returned by the GraphQL server, enable the `graphql` key of the `data_collection` option in your SDK init. The `document` key controls the queries and the `errors` information, and the `variables` key controls the query variables: +By default, the SDK records the GraphQL queries and the `errors` information that the GraphQL server returns. To control this, use the `graphql` key of the `data_collection` option in your SDK init. The `document` key controls the queries and the `errors` information, and the `variables` key controls the query variables: ```python sentry_sdk.init( @@ -43,21 +39,6 @@ sentry_sdk.init( ) ``` -These are also the defaults when you pass a `data_collection` dictionary. See Data Collected for all available keys. - -Alternatively, you can set `send_default_pii` to `True`, though `send_default_pii` will be removed in version 3.0 of the SDK: - -```python -sentry_sdk.init( - # ... - # Add data like request headers and IP for users, if applicable; - # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info - send_default_pii=True, -) -``` - - - -Before enabling the `send_default_pii` flag, ensure you've configured Sentry's [sensitive data scrubbing](/platforms/python/data-management/sensitive-data/) tools to scrub all PII. Since `send_default_pii` affects all integrations, consider using `data_collection` to enable only the categories you need instead. +These are the defaults. See Data Collected for all available keys. - +In SDK versions prior to `3.0`, this data isn't sent by default. To send it, pass a `data_collection` dictionary as shown above, or set the `send_default_pii` option to `True`. Since `send_default_pii` is a global SDK option, setting it to `True` affects all integrations, so make sure to [scrub sensitive data](/platforms/python/data-management/sensitive-data/) from events first. diff --git a/docs/platforms/python/integrations/graphene/index.mdx b/docs/platforms/python/integrations/graphene/index.mdx index 02ba4011bd6c4..99164e96368b1 100644 --- a/docs/platforms/python/integrations/graphene/index.mdx +++ b/docs/platforms/python/integrations/graphene/index.mdx @@ -57,8 +57,7 @@ When used together with one of our web framework integrations like [FastAPI](/platforms/python/integrations/fastapi/) or [Flask](/platforms/python/integrations/flask/), the Graphene integration can capture the request body for each GraphQL error that happens. -Since the requests may contain sensitive data, no request bodies will be attached -by default. +This is enabled by default. To capture request bodies: @@ -77,28 +76,9 @@ sentry_sdk.init( ) ``` -Both are enabled by default when you pass a `data_collection` dictionary. See Data Collected for all available keys. +Both are enabled by default. See Data Collected for all available keys. -Alternatively, you can initialize the SDK with the `send_default_pii` option set to `True`, though `send_default_pii` will be removed in version 3.0 of the SDK: - -```python -sentry_sdk.init( - # same options as above - # Add data like request headers and IP for users, if applicable; - # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info - send_default_pii=True, -) -``` - - - -Since `send_default_pii` is a global SDK option, setting it to `True` affects all -integrations, not just Graphene. Please make sure to take care of -[scrubbing sensitive data](/platforms/python/data-management/sensitive-data/) -from events before enabling this option. With `data_collection`, you can enable -only the categories you need instead. - - +In SDK versions prior to `3.0`, the request body isn't attached by default. To attach it, pass a `data_collection` dictionary as shown above, or set the `send_default_pii` option to `True`. Since `send_default_pii` is a global SDK option, setting it to `True` affects all integrations, so make sure to [scrub sensitive data](/platforms/python/data-management/sensitive-data/) from events first. ## Supported Versions diff --git a/docs/platforms/python/integrations/grpc/index.mdx b/docs/platforms/python/integrations/grpc/index.mdx index c731a310824da..7f8176292608f 100644 --- a/docs/platforms/python/integrations/grpc/index.mdx +++ b/docs/platforms/python/integrations/grpc/index.mdx @@ -5,7 +5,7 @@ description: "Learn about the gRPC integration and how it adds support for the g The [gRPC](https://grpc.io/) integration instruments incoming unary-unary grpc requests and outgoing unary-unary, unary-stream grpc requests using grpcio channels. -Use this integration to start or continue transactions for incoming grpc requests, create spans for outgoing requests, +Use this integration to start or continue traces for incoming grpc requests, create spans for outgoing requests, and ensure traces are properly propagated to downstream services. @@ -133,7 +133,7 @@ In older versions of this integration you had to add the interceptors by hand. S ### Server -If you added the `GRPCIntegration` as described above, the server will create a transaction for each call to a function and send it to [sentry.io](https://sentry.io). +If you added the `GRPCIntegration` as described above, the server will create a service span for each call to a function and send it to [sentry.io](https://sentry.io). It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). @@ -146,19 +146,19 @@ sentry_sdk.init(...) # same as above ... -# or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode -with sentry_sdk.start_transaction(op="function", name="testing_sentry"): +# In SDK 2.x, use sentry_sdk.start_transaction(op="function", name="testing_sentry") instead +with sentry_sdk.start_span(name="testing_sentry", attributes={"sentry.op": "function"}): with grpc.insecure_channel("example.com:12345") as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name="you")) ``` -This will create a transaction called `testing_sentry` in the Performance section of [sentry.io](https://sentry.io) and will create a span for the call to the `SayHello` method on the server. +This will create a service span called `testing_sentry`, visible in the Traces section of [sentry.io](https://sentry.io), with a child span for the call to the `SayHello` method on the server. -The transaction created in the client will also be connected to the transaction on the server, giving you a full trace of your request. +The span created in the client will also be connected to the span on the server, giving you a full trace of your request. -If you use a framework (like Django, Flask, FastAPI, etc.) the transaction will be created for you automatically. +If you use a framework (like Django, Flask, FastAPI, etc.) the service span will be created for you automatically. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). diff --git a/docs/platforms/python/integrations/httpx/index.mdx b/docs/platforms/python/integrations/httpx/index.mdx index f3443931418a4..2e073c3e1ede6 100644 --- a/docs/platforms/python/integrations/httpx/index.mdx +++ b/docs/platforms/python/integrations/httpx/index.mdx @@ -26,7 +26,7 @@ Sentry's HTTPX integration is enabled automatically if you have the `httpx` pack ## Verify Your Setup -To verify that Sentry captures your HTTPX requests, add this code to your app, which will create a transaction called `testing_sentry` in the [Traces](https://sentry.io/orgredirect/organizations/:orgslug/explore/traces/) section and create spans for the outgoing HTTP requests: +To verify that Sentry captures your HTTPX requests, add this code to your app, which will create a service span called `testing_sentry` in the [Traces](https://sentry.io/orgredirect/organizations/:orgslug/explore/traces/) section and create spans for the outgoing HTTP requests: ```python import sentry_sdk @@ -36,8 +36,8 @@ def main(): # same as in the Python quick start guide (https://docs.sentry.io/platforms/python) sentry_sdk.init(...) - # or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): r1 = httpx.get("https://sentry.io/") r2 = httpx.post("http://httpbin.org/post") diff --git a/docs/platforms/python/integrations/httpx2/index.mdx b/docs/platforms/python/integrations/httpx2/index.mdx index 49068037d9074..0c250c38df00c 100644 --- a/docs/platforms/python/integrations/httpx2/index.mdx +++ b/docs/platforms/python/integrations/httpx2/index.mdx @@ -34,15 +34,15 @@ import httpx2 def main(): sentry_init(...) # same as above - # or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): r1 = httpx2.get("https://sentry.io/") r2 = httpx2.post("http://httpbin.org/post") main() ``` -This will create a transaction called `testing_sentry` in the Performance section of [sentry.io](https://sentry.io), and create spans for the outgoing HTTP requests. +This will create a service span called `testing_sentry` in the Traces section of [sentry.io](https://sentry.io), and create spans for the outgoing HTTP requests. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). diff --git a/docs/platforms/python/integrations/huey/index.mdx b/docs/platforms/python/integrations/huey/index.mdx index 2a181f3e001ad..fbf843af1ec11 100644 --- a/docs/platforms/python/integrations/huey/index.mdx +++ b/docs/platforms/python/integrations/huey/index.mdx @@ -39,14 +39,14 @@ huey = SqliteHuey(filename='demo.db') def add(a, b): return a + b -# or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode -with sentry_sdk.start_transaction(name="testing_huey"): +# In SDK 2.x, use sentry_sdk.start_transaction(name="testing_huey") instead +with sentry_sdk.start_span(name="testing_huey"): result = add(1, 2) ``` -Running this will create a new transaction called `testing_huey` in the -Performance section of [sentry.io](https://sentry.io). It may -take a couple of moments for the transaction to show up. +Running this will create a new service span called `testing_huey` in the +Traces section of [sentry.io](https://sentry.io). It may +take a couple of moments for the span to show up. ## Supported Versions diff --git a/docs/platforms/python/integrations/index.mdx b/docs/platforms/python/integrations/index.mdx index e8f60c96662ad..be051ed5c1803 100644 --- a/docs/platforms/python/integrations/index.mdx +++ b/docs/platforms/python/integrations/index.mdx @@ -44,6 +44,7 @@ The tables on this page show which integrations are auto-enabled in the current | | **Auto-enabled** | | --------------------------------------------------------------------------------------------------------------------------------- | :--------------: | +| | ✓ | | | ✓ | | | ✓ | | | ✓ | @@ -169,9 +170,9 @@ from sentry_sdk.integrations.flask import FlaskIntegration sentry_sdk.init( integrations=[ - # The Flask integration is auto-enabling, but we want to change - # transaction_style from the default "endpoint" to "url" - FlaskIntegration(transaction_style="url"), + # The Flask integration is auto-enabling, but we want to only + # create spans for GET requests + FlaskIntegration(http_methods_to_capture=("GET",)), # The asyncio integration is not enabled automatically # and needs to be added manually. AsyncioIntegration(), diff --git a/docs/platforms/python/integrations/logging/index.mdx b/docs/platforms/python/integrations/logging/index.mdx index 3cad947696cf0..9df6f8589dba6 100644 --- a/docs/platforms/python/integrations/logging/index.mdx +++ b/docs/platforms/python/integrations/logging/index.mdx @@ -5,9 +5,11 @@ description: "Learn about logging with Python." The logging integration adds support for the `logging` framework from Python's standard library. Depending on your settings, logs can be captured as Sentry logs, as error events, or as breadcrumbs, or a combination of those. +This page describes the logging integration in version `3.x` of the Python SDK. For `2.x`, switch to `2.x` in the version selector. + -Enable the Sentry Logs feature with `LoggingIntegration(capture_sentry_logs=True)` to unlock Sentry's full logging power. With Sentry Logs, you can search, filter, and analyze logs from across your entire application in one place. +Add `LoggingIntegration()` to your `integrations` to send log records as Sentry logs. With Sentry Logs, you can search, filter, and analyze logs from across your entire application in one place. @@ -25,7 +27,7 @@ uv add "sentry-sdk" ## Configure -The logging integration is a default integration, so it will be enabled automatically when you initialize the Sentry SDK. To capture log records as [Sentry logs](/platforms/python/logs/), set `capture_sentry_logs` to `True` on the integration. +To enable the integration, add `LoggingIntegration()` to your `integrations` list: ```python import sentry_sdk @@ -38,7 +40,7 @@ sentry_sdk.init( "user_info": True, }, integrations=[ - LoggingIntegration(capture_sentry_logs=True), + LoggingIntegration(), ], ) ``` @@ -56,15 +58,15 @@ def main(): main() ``` -This will capture both logs and send them to Sentry Logs. Additionally, an error event will be created from the `ERROR`-level log. In addition to that, a breadcrumb will be created from the `INFO`-level log. +This sends log records to Sentry as [Sentry logs](/platforms/python/logs/) and records them as breadcrumbs. ## Behavior -When the integration is capturing Sentry logs, logs with a level of `INFO` and higher will be captured as Sentry logs if the log level set in the `logging` module is `INFO` or below. The threshold can be configured via the [`sentry_logs_level` option](#options). +By default, logs with a level of `INFO` and higher are captured as Sentry logs, as long as the log level set in the `logging` module is `INFO` or below. Use the [`level` option](#options) to change the threshold. -Additionally, the logging integration will create an error event from all `ERROR`-level logs. This feature is configurable via the [`event_level` integration option](#options). +`INFO` and above logs are also recorded as breadcrumbs. Use the [`breadcrumb_level` option](#options) to change the threshold. -`INFO` and above logs will also be captured as breadcrumbs. Use the [`level` integration option](#options) to adjust the threshold. +The integration doesn't create error events from log records by default. To create error events from `ERROR` logs and higher, set the [`event_level` option](#options) to `logging.ERROR`. ```python import logging @@ -75,7 +77,7 @@ from sentry_sdk.integrations.logging import LoggingIntegration sentry_sdk.init( ..., integrations=[ - LoggingIntegration(capture_sentry_logs=True), + LoggingIntegration(event_level=logging.ERROR), ], ) @@ -88,13 +90,12 @@ logging.exception("I'm an exception log") logging.debug("I'm a DEBUG log") ``` -- All of the above logs except for the `DEBUG` level message will be sent to Sentry as logs. +- All of the above logs except for the `DEBUG` level message are sent to Sentry as logs. - An error event with the message `"I'm an ERROR log"` will be created. - `"I'm an INFO log"` will be attached as a breadcrumb to that event. - `bar` will end up in the `extra` attributes of that event. - `"I'm an exception log"` will send the current exception from `sys.exc_info()` with the stack trace to Sentry. If there's no exception, the current stack will be attached. -- The debug message `"I'm a DEBUG log"` will not be captured by Sentry. See the [`sentry_logs_level` option](#option) to adjust which levels should be sent to Sentry as logs, and the [`level` option](#option) to do adjust the level for capturing breadcrumbs. - +- The debug message `"I'm a DEBUG log"` isn't captured. See the [`level` option](#options) to adjust which levels should be sent to Sentry as logs, and the [`breadcrumb_level` option](#options) to adjust the level for capturing breadcrumbs. ### Working with Extra Fields @@ -108,7 +109,7 @@ from sentry_sdk.integrations.logging import LoggingIntegration sentry_sdk.init( # ... integrations=[ - LoggingIntegration(capture_sentry_logs=True), + LoggingIntegration(), ], ) @@ -116,10 +117,10 @@ logger = logging.getLogger(__name__) # Extra fields become top-level searchable attributes logger.error( - "Payment processing failed", + "Payment processing failed", extra={ "user_id": 12345, - "transaction_id": "txn_abc123", + "transaction_id": "txn_abc123", "payment_method": "credit_card", "amount": 99.99 } @@ -130,7 +131,7 @@ In this example, `user_id`, `transaction_id`, `payment_method`, and `amount` wil ## Options -To change the default behavior of the logging integration, instantiate the integration manually and pass it to Sentry's `init` function: +To change the default behavior of the logging integration, pass options to `LoggingIntegration()`: ```python import logging @@ -146,10 +147,9 @@ sentry_sdk.init( # ... integrations=[ LoggingIntegration( - capture_sentry_logs=True, # Capture log records as Sentry logs - sentry_logs_level=logging.INFO, # Capture INFO and above as logs - level=logging.INFO, # Capture INFO and above as breadcrumbs - event_level=logging.ERROR, # Send ERROR records as events + level=logging.INFO, # Capture INFO and above as logs + breadcrumb_level=logging.INFO, # Capture INFO and above as breadcrumbs + event_level=logging.ERROR, # Send ERROR records as events ), ], ) @@ -157,20 +157,15 @@ sentry_sdk.init( You can pass the following keyword arguments to `LoggingIntegration()`: -- `capture_sentry_logs` (default: unset, which behaves as `False`): Set to `True` to capture log records as [Sentry structured logs](/platforms/python/logs/). If you leave this unset and have the deprecated [`enable_logs`](/platforms/python/configuration/options/#enable_logs) set to `True`, the SDK captures records as Sentry logs. Setting this option explicitly always wins over `enable_logs`. - -- `sentry_logs_level` (default `INFO`): The Sentry Python SDK will capture records with a level higher than or equal to `sentry_logs_level` as [Sentry structured logs](/platforms/python/logs/), as long as the integration is capturing Sentry logs. - -- `level` (default `INFO`): The Sentry Python SDK will record log records with a level higher than or equal to `level` as breadcrumbs. Inversely, the SDK completely ignores any log record with a level lower than this one. If a value of `None` occurs, the SDK won't send log records as breadcrumbs. +- `level` (default `INFO`): The SDK captures records with a level higher than or equal to `level` as [Sentry structured logs](/platforms/python/logs/). If set to `None`, the SDK won't send records as Sentry logs. -- `event_level` (default `ERROR`): The Sentry Python SDK will report log records with a level higher than or equal to `event_level` as events as long as the logger itself is set to output records of those log levels (see note below). If a value of `None` occurs, the SDK won't send log records as events. +- `breadcrumb_level` (default `INFO`): The SDK records log records with a level higher than or equal to `breadcrumb_level` as breadcrumbs. If set to `None`, the SDK won't record log records as breadcrumbs. +- `event_level` (default `None`): The SDK reports log records with a level higher than or equal to `event_level` as events, as long as the logger itself is set to output records of those log levels (see [Troubleshooting](#troubleshooting)). If set to `None`, the SDK won't send log records as events. +## Ignoring a Logger - -## Ignoring a logger - -Sometimes a logger is extremely noisy and spams you with pointless errors. You can ignore that logger by calling `ignore_logger`: +To stop the SDK from sending a noisy logger's records as Sentry logs, call `ignore_logger`: ```python from sentry_sdk.integrations.logging import ignore_logger @@ -178,24 +173,29 @@ from sentry_sdk.integrations.logging import ignore_logger ignore_logger("a.spammy.logger") logger = logging.getLogger("a.spammy.logger") -logger.error("hi") # no error sent to sentry +logger.error("hi") # no Sentry log sent ``` -You can also use `before-send` and `before-breadcrumb` to ignore -only certain messages. See Filtering Events for more information. +To stop a logger from creating events and breadcrumbs, call `ignore_logger_for_events`: - +```python +from sentry_sdk.integrations.logging import ignore_logger_for_events -Using `ignore_logger` removes the entries from specified logger **only** for breadcrumbs and events. -If you **do not** wish to collect logs from the specified logger altogether, use also `ignore_logger_for_sentry_logs`. +ignore_logger_for_events("a.spammy.logger") - +logger = logging.getLogger("a.spammy.logger") +logger.error("hi") # no error event or breadcrumb created +``` + +To ignore a logger completely, call both functions. Use `unignore_logger` and `unignore_logger_for_events` to revert them. + +You can also use `before_send_log` (for Sentry logs), `before_send` (for Sentry errors) and `before_breadcrumb` (for breadcrumbs) to ignore only certain messages. See Filtering Events for more information. -## Handler classes +## Handler Classes -Instead of using `LoggingIntegration`, you can use two regular logging `logging.Handler` subclasses that the integration exports. +Instead of using `LoggingIntegration`, you can attach the `logging.Handler` subclasses that the integration exports to your loggers yourself: `LogsHandler` (for Sentry logs), `EventHandler` (for error events), and `BreadcrumbHandler` (for breadcrumbs). -**Usually, you don't need this.** You _can_ use this together with `default_integrations=False` if you want to opt into what the Sentry Python SDK captures. However, correctly setting up logging is difficult. Also, an opt-in approach to capture data will miss errors you may not think of on your own. +**Usually, you don't need this.** Correctly setting up logging is difficult, and attaching handlers to specific loggers may miss records you didn't think of. See the [API documentation](https://getsentry.github.io/sentry-python/integrations.html#module-sentry_sdk.integrations.logging) for more information. @@ -203,10 +203,16 @@ See the [API documentation](https://getsentry.github.io/sentry-python/integratio - First, make sure you're on the latest version of the SDK. If you're using the `sentry_sdk.logger` API directly (e.g., `sentry_sdk.logger.info(...)`), logs are sent automatically. If you're using Python's `logging` module and want those log records captured as Sentry logs, make sure you have `capture_sentry_logs=True` set on your `LoggingIntegration`. Setting the deprecated `enable_logs=True` also works, but only if `capture_sentry_logs` is left unset on the integration. +First, make sure you're on the latest version of the SDK. If you're using the `sentry_sdk.logger` API directly (e.g., `sentry_sdk.logger.info(...)`), logs are sent automatically. If you're using Python's `logging` module and want those log records captured as Sentry logs, make sure you've added `LoggingIntegration()` to your `integrations` and that its `level` option isn't set to `None`. + +The SDK will honor the configured level of each logger (set with `logger.setLevel(level)` or `logging.basicConfig(level=level)`). That means you won't see any `INFO` or `DEBUG` events from a logger with the level set to `WARNING`, regardless of how you configure the integration. If not set explicitly, the logging level defaults to `WARNING`. + +Some frameworks, such as `uvicorn`, may reset or override your `logging` configuration. To ensure your log level is applied and logs at or above the configured level are picked up by the SDK, you can pass `force=True` to `logging.basicConfig()`, for example `logging.basicConfig(level=level, force=True)`. + + - The SDK will honor the configured level of each logger (set with `logger.setLevel(level)` or `logging.basicConfig(level=level)`). That means that you will not see any `INFO` or `DEBUG` events from a logger with the level set to `WARNING`, regardless of how you configure the integration. If not set explicitly, the logging level defaults to `WARNING`. + - Some frameworks, such as `uvicorn`, may reset or override your `logging` configuration. To ensure your log level is applied and logs at or above the configured level are picked up by the SDK, you can use the `force=True` flag when configuring your log level. For example `logger.setLevel(level, force=True)` and `logging.basicConfig(level=level, force=True)`. +Starting with SDK `3.0`, the logging integration doesn't create error events from log records by default. Set `event_level=logging.ERROR` on `LoggingIntegration()` to create error events from `ERROR` logs and higher. diff --git a/docs/platforms/python/integrations/logging/index__v2.x.mdx b/docs/platforms/python/integrations/logging/index__v2.x.mdx new file mode 100644 index 0000000000000..297b65881b375 --- /dev/null +++ b/docs/platforms/python/integrations/logging/index__v2.x.mdx @@ -0,0 +1,214 @@ +--- +title: Logging +description: "Learn about logging with Python." +--- + +This page describes the logging integration in version `2.x` of the Python SDK. Version `3.x` changed how the integration is enabled and renamed its options. To see the `3.x` docs, switch to `latest` in the version selector. + +The logging integration adds support for the `logging` framework from Python's standard library. Depending on your settings, logs can be captured as Sentry logs, as error events, or as breadcrumbs, or a combination of those. + + + +Enable the Sentry Logs feature with `LoggingIntegration(capture_sentry_logs=True)` to unlock Sentry's full logging power. With Sentry Logs, you can search, filter, and analyze logs from across your entire application in one place. + + + +## Install + +Install `sentry-sdk` from PyPI: + +```bash {tabTitle:pip} +pip install "sentry-sdk" +``` + +```bash {tabTitle:uv} +uv add "sentry-sdk" +``` + +## Configure + +The logging integration is a default integration, so it will be enabled automatically when you initialize the Sentry SDK. To capture log records as [Sentry logs](/platforms/python/logs/), set `capture_sentry_logs` to `True` on the integration. + +```python +import sentry_sdk +from sentry_sdk.integrations.logging import LoggingIntegration + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + # Check https://docs.sentry.io/platforms/python/data-management/data-collected/ to configure what data is collected + data_collection={ + "user_info": True, + }, + integrations=[ + LoggingIntegration(capture_sentry_logs=True), + ], +) +``` + +## Verify + +```python +import logging + +def main(): + sentry_sdk.init(...) # same as above + logging.info("Logging some info") + logging.error("Logging an error") + +main() +``` + +This will capture both logs and send them to Sentry Logs. Additionally, an error event will be created from the `ERROR`-level log. In addition to that, a breadcrumb will be created from the `INFO`-level log. + +## Behavior + +When the integration is capturing Sentry logs, logs with a level of `INFO` and higher will be captured as Sentry logs if the log level set in the `logging` module is `INFO` or below. The threshold can be configured via the [`sentry_logs_level` option](#options). + +Additionally, the logging integration will create an error event from all `ERROR`-level logs. This feature is configurable via the [`event_level` integration option](#options). + +`INFO` and above logs will also be captured as breadcrumbs. Use the [`level` integration option](#options) to adjust the threshold. + +```python +import logging + +import sentry_sdk +from sentry_sdk.integrations.logging import LoggingIntegration + +sentry_sdk.init( + ..., + integrations=[ + LoggingIntegration(capture_sentry_logs=True), + ], +) + +# The following will be captured as Sentry logs: +logging.info("I'm an INFO log") +logging.error("I'm an ERROR log", extra={"bar": 43}) +logging.exception("I'm an exception log") + +# DEBUG-level logs won't be captured by default +logging.debug("I'm a DEBUG log") +``` + +- All of the above logs except for the `DEBUG` level message will be sent to Sentry as logs. +- An error event with the message `"I'm an ERROR log"` will be created. +- `"I'm an INFO log"` will be attached as a breadcrumb to that event. +- `bar` will end up in the `extra` attributes of that event. +- `"I'm an exception log"` will send the current exception from `sys.exc_info()` with the stack trace to Sentry. If there's no exception, the current stack will be attached. +- The debug message `"I'm a DEBUG log"` will not be captured by Sentry. See the [`sentry_logs_level` option](#option) to adjust which levels should be sent to Sentry as logs, and the [`level` option](#option) to do adjust the level for capturing breadcrumbs. + + +### Working with Extra Fields + +When sending log records as Sentry logs, any fields provided in the `extra` dictionary are automatically promoted to top-level attributes on the log entry. This makes them searchable and filterable in the Sentry UI. + +```python +import logging +import sentry_sdk +from sentry_sdk.integrations.logging import LoggingIntegration + +sentry_sdk.init( + # ... + integrations=[ + LoggingIntegration(capture_sentry_logs=True), + ], +) + +logger = logging.getLogger(__name__) + +# Extra fields become top-level searchable attributes +logger.error( + "Payment processing failed", + extra={ + "user_id": 12345, + "transaction_id": "txn_abc123", + "payment_method": "credit_card", + "amount": 99.99 + } +) +``` + +In this example, `user_id`, `transaction_id`, `payment_method`, and `amount` will appear as separate, searchable attributes in the Sentry logs interface, not nested within an `extra` object. You can filter and query logs using these attributes directly, such as `user_id:12345` or `payment_method:credit_card`. + +## Options + +To change the default behavior of the logging integration, instantiate the integration manually and pass it to Sentry's `init` function: + +```python +import logging +import sentry_sdk +from sentry_sdk.integrations.logging import LoggingIntegration + +# The SDK will honor the level set by the logging library, which is WARNING by default. +# If we want to capture records with lower severity, we need to configure +# the logger level first. +logging.basicConfig(level=logging.INFO) + +sentry_sdk.init( + # ... + integrations=[ + LoggingIntegration( + capture_sentry_logs=True, # Capture log records as Sentry logs + sentry_logs_level=logging.INFO, # Capture INFO and above as logs + level=logging.INFO, # Capture INFO and above as breadcrumbs + event_level=logging.ERROR, # Send ERROR records as events + ), + ], +) +``` + +You can pass the following keyword arguments to `LoggingIntegration()`: + +- `capture_sentry_logs` (default: unset, which behaves as `False`): Set to `True` to capture log records as [Sentry structured logs](/platforms/python/logs/). If you leave this unset and have the deprecated [`enable_logs`](/platforms/python/configuration/options/#enable_logs) set to `True`, the SDK captures records as Sentry logs. Setting this option explicitly always wins over `enable_logs`. + +- `sentry_logs_level` (default `INFO`): The Sentry Python SDK will capture records with a level higher than or equal to `sentry_logs_level` as [Sentry structured logs](/platforms/python/logs/), as long as the integration is capturing Sentry logs. + +- `level` (default `INFO`): The Sentry Python SDK will record log records with a level higher than or equal to `level` as breadcrumbs. Inversely, the SDK completely ignores any log record with a level lower than this one. If a value of `None` occurs, the SDK won't send log records as breadcrumbs. + +- `event_level` (default `ERROR`): The Sentry Python SDK will report log records with a level higher than or equal to `event_level` as events as long as the logger itself is set to output records of those log levels (see note below). If a value of `None` occurs, the SDK won't send log records as events. + + + + +## Ignoring a logger + +Sometimes a logger is extremely noisy and spams you with pointless errors. You can ignore that logger by calling `ignore_logger`: + +```python +from sentry_sdk.integrations.logging import ignore_logger + +ignore_logger("a.spammy.logger") + +logger = logging.getLogger("a.spammy.logger") +logger.error("hi") # no error sent to sentry +``` + +You can also use `before-send` and `before-breadcrumb` to ignore +only certain messages. See Filtering Events for more information. + + + +Using `ignore_logger` removes the entries from specified logger **only** for breadcrumbs and events. +If you **do not** wish to collect logs from the specified logger altogether, use also `ignore_logger_for_sentry_logs`. + + + +## Handler classes + +Instead of using `LoggingIntegration`, you can use two regular logging `logging.Handler` subclasses that the integration exports. + +**Usually, you don't need this.** You _can_ use this together with `default_integrations=False` if you want to opt into what the Sentry Python SDK captures. However, correctly setting up logging is difficult. Also, an opt-in approach to capture data will miss errors you may not think of on your own. + +See the [API documentation](https://getsentry.github.io/sentry-python/integrations.html#module-sentry_sdk.integrations.logging) for more information. + +## Troubleshooting + + + + First, make sure you're on the latest version of the SDK. If you're using the `sentry_sdk.logger` API directly (e.g., `sentry_sdk.logger.info(...)`), logs are sent automatically. If you're using Python's `logging` module and want those log records captured as Sentry logs, make sure you have `capture_sentry_logs=True` set on your `LoggingIntegration`. Setting the deprecated `enable_logs=True` also works, but only if `capture_sentry_logs` is left unset on the integration. + + The SDK will honor the configured level of each logger (set with `logger.setLevel(level)` or `logging.basicConfig(level=level)`). That means that you will not see any `INFO` or `DEBUG` events from a logger with the level set to `WARNING`, regardless of how you configure the integration. If not set explicitly, the logging level defaults to `WARNING`. + + Some frameworks, such as `uvicorn`, may reset or override your `logging` configuration. To ensure your log level is applied and logs at or above the configured level are picked up by the SDK, you can pass `force=True` to `logging.basicConfig()`, for example `logging.basicConfig(level=level, force=True)`. + + diff --git a/docs/platforms/python/integrations/loguru/index.mdx b/docs/platforms/python/integrations/loguru/index.mdx index e9dcb80815aed..1a842d0ee7752 100644 --- a/docs/platforms/python/integrations/loguru/index.mdx +++ b/docs/platforms/python/integrations/loguru/index.mdx @@ -7,13 +7,14 @@ The [Loguru](https://github.com/Delgan/loguru#readme) integration lets you captu The [`logging`](/platforms/python/integrations/logging/) integration provides most of the Loguru functionality and most examples on that page work with Loguru. +This page describes the Loguru integration in version `3.x` of the Python SDK. For `2.x`, switch to `2.x` in the version selector. + -Enable the Sentry Logs feature with `LoguruIntegration(capture_sentry_logs=True)` to unlock Sentry's full logging power. With Sentry Logs, you can search, filter, and analyze logs from across your entire application in one place. +Add `LoguruIntegration()` to your `integrations` to send Loguru log records as Sentry logs. With Sentry Logs, you can search, filter, and analyze logs from across your entire application in one place. - ## Install Install `sentry-sdk` from PyPI: @@ -28,7 +29,7 @@ uv add sentry-sdk ## Configure -If you have the `loguru` package in your dependencies, the Loguru integration will be enabled automatically when you initialize the Sentry SDK. To capture Loguru log records as [Sentry logs](/platforms/python/logs/), set `capture_sentry_logs` to `True` on the integration. +To use the integration, add `LoguruIntegration()` to your `integrations` list: ```python import sentry_sdk @@ -41,7 +42,7 @@ sentry_sdk.init( "user_info": True, }, integrations=[ - LoguruIntegration(capture_sentry_logs=True), + LoguruIntegration(), ], ) ``` @@ -59,28 +60,27 @@ def main(): main() ``` -This will capture both logs and send them to Sentry Logs. Additionally, an error event will be created from the `ERROR`-level log. In addition to that, a breadcrumb will be created from the `INFO`-level log. - +This sends both log records to Sentry as [Sentry logs](/platforms/python/logs/) and record them as breadcrumbs. ## Behavior -Logs with a level of `INFO` and higher will be captured as Sentry logs as long as the integration is capturing Sentry logs and the log level set in the `logging` module is `INFO` or below. The threshold can be configured via the [`sentry_logs_level` option](#options). +By default, logs with a level of `INFO` and higher are captured as Sentry logs. Use the [`level` option](#options) to change the threshold. -Additionally, the Loguru integration will create an error event from all `ERROR`-level logs. This feature is configurable via the [`event_level` integration option](#options). +`INFO` and above logs are also recorded as breadcrumbs. Use the [`breadcrumb_level` option](#options) to change the threshold. -`INFO` and above logs will also be captured as breadcrumbs. Use the [`level` integration option](#options) to adjust the threshold. +The integration doesn't create error events from log records by default. To create error events from `ERROR` logs and higher, set the [`event_level` option](#options). -The following snippet demonstrates the default behavior: +The following snippet demonstrates the behavior with `event_level` set: ```python import sentry_sdk from loguru import logger -from sentry_sdk.integrations.loguru import LoguruIntegration +from sentry_sdk.integrations.loguru import LoggingLevels, LoguruIntegration sentry_sdk.init( ..., integrations=[ - LoguruIntegration(capture_sentry_logs=True), + LoguruIntegration(event_level=LoggingLevels.ERROR.value), ], ) @@ -93,41 +93,42 @@ logger.exception("I'm an exception log") logger.debug("I'm a DEBUG log") ``` -- All of the above logs except for the `DEBUG`-level message will be sent to Sentry as logs. +- All of the above logs except for the `DEBUG`-level message are sent to Sentry as logs. - An error event with the message `"I'm an ERROR log"` will be created. - `"I'm an INFO log"` will be attached as a breadcrumb to that event. - `bar` will end up in the `extra` attributes of that event. - `"I'm an exception log"` will send the current exception from `sys.exc_info()` with the stack trace to Sentry. If there's no exception, the current stack will be attached. -- The debug message `"I'm a DEBUG log"` will not be captured by Sentry. See the [`sentry_logs_level` option](#option) to adjust which log levels should be sent to Sentry as logs, and the [`level` option](#option) to adjust the level for capturing breadcrumbs. +- The debug message `"I'm a DEBUG log"` isn't captured. See the [`level` option](#options) to adjust which log levels should be sent to Sentry as logs, and the [`breadcrumb_level` option](#options) to adjust the level for capturing breadcrumbs. +### Ignoring a Logger -### Ignoring a logger +To stop a noisy logger from creating events and breadcrumbs, call `ignore_logger_for_events`. -Loggers can be noisy. You can ignore a logger by calling `ignore_logger`. - -Since most of the logic is proxied to `logging` integration, we use it instead of the Loguru integration: +Since most of the logic is proxied to the `logging` integration, import it from there: ```python -# Import form `logging` integration -from sentry_sdk.integrations.logging import ignore_logger +# Import from `logging` integration +from sentry_sdk.integrations.logging import ignore_logger_for_events -ignore_logger("a.spammy.logger") +ignore_logger_for_events("a.spammy.logger") ``` In `a.spammy.logger` module: ```python from loguru import logger -logger.error("hi") # Nothing is sent to Sentry +logger.error("hi") # No error event or breadcrumb is created ``` -This will work with `logging`'s logger too +This will work with `logging`'s logger too: ```python logger = logging.getLogger("a.spammy.logger") -logger.error("hi") # Again, nothing is sent to Sentry +logger.error("hi") # Again, no error event or breadcrumb is created ``` +`ignore_logger_for_events` doesn't affect Sentry logs. To filter Loguru records out of Sentry logs, use `before_send_log`. + You can also use `before_send_log` (for Sentry logs), `before_send` (for Sentry errors) and `before_breadcrumb` (for breadcrumbs) to ignore only certain messages. See Filtering Events for more information. ## Options @@ -145,59 +146,57 @@ sentry_sdk.init( # ... integrations=[ LoguruIntegration( - capture_sentry_logs=True, # Capture Loguru logs as Sentry logs - sentry_logs_level=LoggingLevels.INFO.value, # Capture INFO and above as logs - level=LoggingLevels.INFO.value, # Capture INFO and above as breadcrumbs - event_level=LoggingLevels.ERROR.value, # Send ERROR logs as events + level=LoggingLevels.INFO.value, # Capture INFO and above as logs + breadcrumb_level=LoggingLevels.INFO.value, # Capture INFO and above as breadcrumbs + event_level=LoggingLevels.ERROR.value, # Send ERROR logs as events ) ], ) ``` +Pass these options as keyword arguments. Their position in the `LoguruIntegration()` signature isn't guaranteed to stay the same. -- `capture_sentry_logs` - - Set to `True` to capture Loguru log records as [Sentry structured logs](/platforms/python/logs/). If you leave this unset and have the deprecated [`enable_logs`](/platforms/python/configuration/options/#enable_logs) set to `True`, the SDK captures records as Sentry logs. Setting this option explicitly always wins over `enable_logs`. - - Default: unset, which behaves as `False` - -- `sentry_logs_level` +- `level` - The Sentry Python SDK will capture log records with a level higher than or equal to `sentry_logs_level` as [Sentry structured logs](/platforms/python/logs/). If set to `None`, the SDK won't send records as logs. Only applies when the integration is capturing Sentry logs. + The SDK captures log records with a level higher than or equal to `level` as [Sentry structured logs](/platforms/python/logs/). If set to `None`, the SDK won't send records as Sentry logs. Default: `INFO` -- `level` +- `breadcrumb_level` - The Sentry Python SDK will record log records with a level higher than or equal to `level` as breadcrumbs. Inversely, the SDK will not capture breadcrumbs for logs with a level lower than this one. If set to `None`, the SDK won't send log records as breadcrumbs. + The SDK records log records with a level higher than or equal to `breadcrumb_level` as breadcrumbs. If set to `None`, the SDK won't record log records as breadcrumbs. Default: `INFO` - `event_level` - The Sentry Python SDK will report log records with a level higher than or equal to `event_level` as events. If set to `None`, the SDK won't send log records as events. + The SDK reports log records with a level higher than or equal to `event_level` as events. If set to `None`, the SDK won't send log records as events. - Default: `ERROR` + Default: `None` ## Troubleshooting - First, make sure you're on the latest version of the SDK. If you're using the `sentry_sdk.logger` API directly (e.g., `sentry_sdk.logger.info(...)`), logs are sent automatically. If you're using Loguru and want those log records captured as Sentry logs, make sure you have `capture_sentry_logs=True` set on your `LoguruIntegration`. Setting the deprecated `enable_logs=True` also works, but only if `capture_sentry_logs` is left unset on the integration. +First, make sure you're on the latest version of the SDK. If you're using the `sentry_sdk.logger` API directly (e.g., `sentry_sdk.logger.info(...)`), logs are sent automatically. If you're using Loguru and want those log records captured as Sentry logs, make sure you've added `LoguruIntegration()` to your `integrations` and that its `level` option isn't set to `None`. + +Your logs could be missing because of the logging level of the logger. The SDK will honor the configured level of each logger. That means that you won't see any `INFO` or `DEBUG` data in Sentry from a logger with the level set to `WARNING`, regardless of how you configure the integration. - Your logs could be missing because of the logging level of the logger. The SDK will honor the configured level of each logger. That means that you won't see any `INFO` or `DEBUG` data in Sentry from a logger with the level set to `WARNING`, regardless of how you configure the integration. +It might also be the case that the SDK's Loguru setup is being overwritten in your app. Sentry plugs into Loguru by adding its own handlers when you call `sentry_sdk.init()`. If those handlers are later overridden, for example by calling `logger.configure(handlers=...)`, the integration won't work. + +Another reason why you might not be seeing your logs in Sentry is because they were rejected client- or server-side. This could be due to them being too large, or because of reasons like rate limits or backpressure management. In Sentry, you can go to [**Settings > Stats & Usage**](https://sentry.io/orgredirect/organizations/:orgslug/settings/stats/) and select `Logs` from the `Category` dropdown to see what logs were dropped. + + - It might also be the case that the SDK's Loguru setup is being overwritten in your app. Sentry plugs into Loguru by adding its own handlers when you call `sentry_sdk.init()`. If those handlers are later overridden, for example by calling `logger.configure(handlers=...)`, the integration won't work. + - Another reason why you might not be seeing your logs in Sentry is because they were rejected client- or server-side. This could be due to them being too large, or because of reasons like rate limits or backpressure management. In Sentry, you can go to [**Settings > Stats & Usage**](https://sentry.io/orgredirect/organizations/:orgslug/settings/stats/) and select `Logs` from the `Category` dropdown to see what logs were dropped. +Starting with SDK `3.0`, the Loguru integration doesn't create error events from log records by default. Set `event_level=LoggingLevels.ERROR.value` on `LoguruIntegration()` to create error events from `ERROR` logs and higher. ## Supported Versions - Loguru: 0.7.0+ -- Python: - - 3.6+ (SDK <3.0) - - 3.7+ (SDK 3.0+) +- Python: 3.7+ diff --git a/docs/platforms/python/integrations/loguru/index__v2.x.mdx b/docs/platforms/python/integrations/loguru/index__v2.x.mdx new file mode 100644 index 0000000000000..7a39f4e2a21d4 --- /dev/null +++ b/docs/platforms/python/integrations/loguru/index__v2.x.mdx @@ -0,0 +1,205 @@ +--- +title: Loguru +description: Learn about using Sentry with Loguru. +--- + +This page describes the Loguru integration in version `2.x` of the Python SDK. Version `3.x` changed how the integration is enabled and renamed its options. To see the `3.x` docs, switch to `latest` in the version selector. + +The [Loguru](https://github.com/Delgan/loguru#readme) integration lets you capture log messages and send them to Sentry. + +The [`logging`](/platforms/python/integrations/logging/) integration provides most of the Loguru functionality and most examples on that page work with Loguru. + + + +Enable the Sentry Logs feature with `LoguruIntegration(capture_sentry_logs=True)` to unlock Sentry's full logging power. With Sentry Logs, you can search, filter, and analyze logs from across your entire application in one place. + + + + +## Install + +Install `sentry-sdk` from PyPI: + +```bash {tabTitle:pip} +pip install sentry-sdk +``` + +```bash {tabTitle:uv} +uv add sentry-sdk +``` + +## Configure + +If you have the `loguru` package in your dependencies, the Loguru integration will be enabled automatically when you initialize the Sentry SDK. To capture Loguru log records as [Sentry logs](/platforms/python/logs/), set `capture_sentry_logs` to `True` on the integration. + +```python +import sentry_sdk +from sentry_sdk.integrations.loguru import LoguruIntegration + +sentry_sdk.init( + dsn="___PUBLIC_DSN___", + # Check https://docs.sentry.io/platforms/python/data-management/data-collected/ to configure what data is collected + data_collection={ + "user_info": True, + }, + integrations=[ + LoguruIntegration(capture_sentry_logs=True), + ], +) +``` + +## Verify + +```python +from loguru import logger + +def main(): + sentry_sdk.init(...) # same as above + logger.info("Logging some info") + logger.error("Logging an error") + +main() +``` + +This will capture both logs and send them to Sentry Logs. Additionally, an error event will be created from the `ERROR`-level log. In addition to that, a breadcrumb will be created from the `INFO`-level log. + + +## Behavior + +Logs with a level of `INFO` and higher will be captured as Sentry logs as long as the integration is capturing Sentry logs and the log level set in the `logging` module is `INFO` or below. The threshold can be configured via the [`sentry_logs_level` option](#options). + +Additionally, the Loguru integration will create an error event from all `ERROR`-level logs. This feature is configurable via the [`event_level` integration option](#options). + +`INFO` and above logs will also be captured as breadcrumbs. Use the [`level` integration option](#options) to adjust the threshold. + +The following snippet demonstrates the default behavior: + +```python +import sentry_sdk +from loguru import logger +from sentry_sdk.integrations.loguru import LoguruIntegration + +sentry_sdk.init( + ..., + integrations=[ + LoguruIntegration(capture_sentry_logs=True), + ], +) + +# The following will be captured as Sentry logs: +logger.info("I'm an INFO log") +logger.error("I'm an ERROR log", extra={"bar": 43}) +logger.exception("I'm an exception log") + +# DEBUG-level logs won't be captured by default +logger.debug("I'm a DEBUG log") +``` + +- All of the above logs except for the `DEBUG`-level message will be sent to Sentry as logs. +- An error event with the message `"I'm an ERROR log"` will be created. +- `"I'm an INFO log"` will be attached as a breadcrumb to that event. +- `bar` will end up in the `extra` attributes of that event. +- `"I'm an exception log"` will send the current exception from `sys.exc_info()` with the stack trace to Sentry. If there's no exception, the current stack will be attached. +- The debug message `"I'm a DEBUG log"` will not be captured by Sentry. See the [`sentry_logs_level` option](#option) to adjust which log levels should be sent to Sentry as logs, and the [`level` option](#option) to adjust the level for capturing breadcrumbs. + + +### Ignoring a logger + +Loggers can be noisy. You can ignore a logger by calling `ignore_logger`. + +Since most of the logic is proxied to `logging` integration, we use it instead of the Loguru integration: + +```python +# Import form `logging` integration +from sentry_sdk.integrations.logging import ignore_logger + +ignore_logger("a.spammy.logger") +``` + +In `a.spammy.logger` module: + +```python +from loguru import logger +logger.error("hi") # Nothing is sent to Sentry +``` + +This will work with `logging`'s logger too + +```python +logger = logging.getLogger("a.spammy.logger") +logger.error("hi") # Again, nothing is sent to Sentry +``` + +You can also use `before_send_log` (for Sentry logs), `before_send` (for Sentry errors) and `before_breadcrumb` (for breadcrumbs) to ignore only certain messages. See Filtering Events for more information. + +## Options + +You can pass the following keyword arguments to `LoguruIntegration()`: + +```python +import sentry_sdk +from loguru import logger + +from sentry_sdk.integrations.loguru import LoguruIntegration +from sentry_sdk.integrations.loguru import LoggingLevels + +sentry_sdk.init( + # ... + integrations=[ + LoguruIntegration( + capture_sentry_logs=True, # Capture Loguru logs as Sentry logs + sentry_logs_level=LoggingLevels.INFO.value, # Capture INFO and above as logs + level=LoggingLevels.INFO.value, # Capture INFO and above as breadcrumbs + event_level=LoggingLevels.ERROR.value, # Send ERROR logs as events + ) + ], +) +``` + + +- `capture_sentry_logs` + + Set to `True` to capture Loguru log records as [Sentry structured logs](/platforms/python/logs/). If you leave this unset and have the deprecated [`enable_logs`](/platforms/python/configuration/options/#enable_logs) set to `True`, the SDK captures records as Sentry logs. Setting this option explicitly always wins over `enable_logs`. + + Default: unset, which behaves as `False` + +- `sentry_logs_level` + + The Sentry Python SDK will capture log records with a level higher than or equal to `sentry_logs_level` as [Sentry structured logs](/platforms/python/logs/). If set to `None`, the SDK won't send records as logs. Only applies when the integration is capturing Sentry logs. + + Default: `INFO` + +- `level` + + The Sentry Python SDK will record log records with a level higher than or equal to `level` as breadcrumbs. Inversely, the SDK will not capture breadcrumbs for logs with a level lower than this one. If set to `None`, the SDK won't send log records as breadcrumbs. + + Default: `INFO` + +- `event_level` + + The Sentry Python SDK will report log records with a level higher than or equal to `event_level` as events. If set to `None`, the SDK won't send log records as events. + + Default: `ERROR` + +## Troubleshooting + + + + First, make sure you're on the latest version of the SDK. If you're using the `sentry_sdk.logger` API directly (e.g., `sentry_sdk.logger.info(...)`), logs are sent automatically. If you're using Loguru and want those log records captured as Sentry logs, make sure you have `capture_sentry_logs=True` set on your `LoguruIntegration`. Setting the deprecated `enable_logs=True` also works, but only if `capture_sentry_logs` is left unset on the integration. + + Your logs could be missing because of the logging level of the logger. The SDK will honor the configured level of each logger. That means that you won't see any `INFO` or `DEBUG` data in Sentry from a logger with the level set to `WARNING`, regardless of how you configure the integration. + + It might also be the case that the SDK's Loguru setup is being overwritten in your app. Sentry plugs into Loguru by adding its own handlers when you call `sentry_sdk.init()`. If those handlers are later overridden, for example by calling `logger.configure(handlers=...)`, the integration won't work. + + Another reason why you might not be seeing your logs in Sentry is because they were rejected client- or server-side. This could be due to them being too large, or because of reasons like rate limits or backpressure management. In Sentry, you can go to [**Settings > Stats & Usage**](https://sentry.io/orgredirect/organizations/:orgslug/settings/stats/) and select `Logs` from the `Category` dropdown to see what logs were dropped. + + + +## Supported Versions + +- Loguru: 0.7.0+ +- Python: + - 3.6+ (SDK <3.0) + - 3.7+ (SDK 3.0+) + + diff --git a/docs/platforms/python/integrations/mcp/index.mdx b/docs/platforms/python/integrations/mcp/index.mdx index f8c61f3a64fdd..b876e115649ae 100644 --- a/docs/platforms/python/integrations/mcp/index.mdx +++ b/docs/platforms/python/integrations/mcp/index.mdx @@ -198,21 +198,21 @@ Data on the following will be collected: - **Request context**: Request IDs, session IDs, and transport types (stdio/HTTP) - **Execution spans**: Timing information for all handler invocations -Sentry considers tool inputs/outputs and prompt content as PII. By default, it doesn't include tool results or prompt content, but tool and prompt arguments (`mcp.request.argument.*`) are still attached; setting `inputs` to `False` in the `gen_ai` key described below removes them. To include tool results and prompt content, use the `gen_ai` key of the `data_collection` option, which lets you control inputs and outputs separately. When you pass a `data_collection` dictionary, both are collected by default, and `include_prompts` is ignored: +By default, the SDK collects tool arguments, tool results, and prompt content. To control this, use the `mcp` key of the `data_collection` option, which lets you control inputs and outputs separately: ```python sentry_sdk.init( # ... data_collection={ # Collect tool and prompt inputs, but not outputs - "gen_ai": {"inputs": True, "outputs": False}, + "mcp": {"inputs": True, "outputs": False}, }, ) ``` Setting `inputs` to `False` removes the `mcp.request.argument.*` attributes from spans, and setting `outputs` to `False` removes tool results and prompt message content. -Alternatively, set `send_default_pii=True` in the `sentry_sdk.init()` call. To explicitly exclude this data despite `send_default_pii=True`, configure the integration with `include_prompts=False` as shown in the [Options section](#options) below. `send_default_pii` will be removed in version 3.0 of the SDK. +In SDK versions prior to `3.0`, this data is controlled by the `gen_ai` key of `data_collection` instead. Without `data_collection`, tool results and prompt content are only collected with `send_default_pii=True`, and can be excluded with the integration's `include_prompts=False` option. ### Captured Span Data @@ -223,26 +223,34 @@ For each operation, the following span data attributes are captured: - `mcp.transport`: Transport type (`http` for Streamable HTTP, `sse` for Server-Sent Events or `stdio`) - `mcp.request_id`: Request identifier (when available) - `mcp.session_id`: Session identifier (when available) +- `network.transport`: Network transport (for example, `pipe` for stdio or `tcp` for HTTP) **Tools:** -- `mcp.tool.name`: The name of the tool being executed -- `mcp.request.argument.*`: Tool input arguments -- `mcp.tool.result.content`: Tool output (when `gen_ai.outputs` is enabled in `data_collection`, or when `send_default_pii=True`) -- `mcp.tool.result.is_error`: Whether the tool execution resulted in an error +- `gen_ai.tool.name`: The name of the tool being executed +- `mcp.request.argument.*`: Tool input arguments (when `mcp.inputs` is enabled in `data_collection`) +- `gen_ai.tool.call.result`: Tool output (when `mcp.outputs` is enabled in `data_collection`) **Prompts:** -- `mcp.prompt.name`: The name of the prompt being requested -- `mcp.request.argument.*`: Prompt input arguments -- `mcp.prompt.result.message.count`: Number of messages in the prompt result -- `mcp.prompt.result.message.role`: Role of the message (for single-message prompts) -- `mcp.prompt.result.message.content`: Message content (for single-message prompts, when `gen_ai.outputs` is enabled in `data_collection`, or when `send_default_pii=True`) +- `gen_ai.prompt.name`: The name of the prompt being requested +- `mcp.request.argument.*`: Prompt input arguments (when `mcp.inputs` is enabled in `data_collection`) +- `mcp.prompt.result.message_count`: Number of messages in the prompt result +- `mcp.prompt.result.message_role`: Role of the message (for single-message prompts) +- `mcp.prompt.result.message_content`: Message content (for single-message prompts, when `mcp.outputs` is enabled in `data_collection`) **Resources:** - `mcp.resource.uri`: The URI of the resource being accessed - `mcp.resource.protocol`: The URI protocol/scheme (e.g., `config`, `data`, `file`) +In SDK versions prior to `3.0`, the tool and prompt names and the tool output are recorded as `mcp.tool.name`, `mcp.prompt.name`, and `mcp.tool.result.content`. + ## Options + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, `MCPIntegration` doesn't accept any options. Use the `mcp` key of the `data_collection` option instead, as described in [Behavior](#behavior). + + + By adding `MCPIntegration` to your `sentry_sdk.init()` call explicitly, you can set options for `MCPIntegration` to change its behavior: ```python diff --git a/docs/platforms/python/integrations/otlp/index.mdx b/docs/platforms/python/integrations/otlp/index.mdx index ac8a5b58eb877..b8ced275f232f 100644 --- a/docs/platforms/python/integrations/otlp/index.mdx +++ b/docs/platforms/python/integrations/otlp/index.mdx @@ -54,7 +54,7 @@ sentry_sdk.init( Under the hood, the `OTLPIntegration` sets up the following parts: * A [`SpanExporter`](https://opentelemetry.io/docs/concepts/components/#exporters) that automatically configures the OTLP ingestion endpoint from your Sentry DSN. This enables tracing in Sentry. **Note:** _Do not_ also set up tracing via the Python SDK (i.e. do not set `traces_sample_rate` or `traces_sampler`). -* A Sentry [`Propagator`](https://opentelemetry.io/docs/concepts/context-propagation/#propagation) for compatibility with services using Sentry's native tracing (see note below) +* Optionally, a Sentry [`Propagator`](https://opentelemetry.io/docs/concepts/context-propagation/#propagation) for compatibility with services using Sentry's native tracing (see the `setup_propagator` option below) * Trace/Span linking for all other Sentry events such as Errors, Logs, and Metrics Cross-service trace propagation uses OTel's default W3C `traceparent` headers and does not require additional configuration. See [Exporters, Event Linking, and Propagation](/concepts/otlp/sentry-with-otel/#exporters-event-linking-and-propagation) for details. @@ -76,15 +76,21 @@ You can pass the following keyword arguments to `OTLPIntegration()`: - `setup_propagator`: - Automatically configure the Sentry propagator for distributed tracing, defaults to `True`. + Replace the global OpenTelemetry propagator with the Sentry propagator, which uses Sentry's `sentry-trace` and `baggage` headers. Defaults to `False`, so distributed tracing uses the propagators configured in OpenTelemetry (by default, W3C `traceparent` and `baggage`). In SDK versions prior to `3.0`, the default is `True`. - Set to `False` to configure propagators manually or to disable propagation. + To propagate both W3C and Sentry headers, set up the `SentryOTLPPropagator` manually instead: - + ```python + from opentelemetry.propagate import set_global_textmap + from opentelemetry.propagators.composite import CompositePropagator + from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator - The automatic propagator setup will be removed in the next major version. Configure propagators manually using the [OpenTelemetry propagation API](https://opentelemetry.io/docs/languages/python/propagation/) instead. + from sentry_sdk.integrations.otlp import SentryOTLPPropagator - + set_global_textmap( + CompositePropagator([TraceContextTextMapPropagator(), SentryOTLPPropagator()]) + ) + ``` - `capture_exceptions`: diff --git a/docs/platforms/python/integrations/pymongo/index.mdx b/docs/platforms/python/integrations/pymongo/index.mdx index aea9b73f03d7e..d76f45830648f 100644 --- a/docs/platforms/python/integrations/pymongo/index.mdx +++ b/docs/platforms/python/integrations/pymongo/index.mdx @@ -40,15 +40,15 @@ def main(): db = client["sentry_test_db"] collection = db["sentry_test"] - # or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): collection.insert_one({"test": "sentry"}) collection.find_one({"test": "sentry"}) main() ``` -This will create a transaction called `testing_sentry` in the Performance section of [sentry.io](https://sentry.io), and create spans for the database operations. +This will create a service span called `testing_sentry` in the Traces section of [sentry.io](https://sentry.io), and create spans for the database operations. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). @@ -58,7 +58,7 @@ The following information about your MongoDB queries will be available to you on - Performance traces for all MongoDB queries - Breadcrumbs for all MongoDB queries -- Personal identifiable information (PII) will be stripped from all MongoDB queries unless you enable `database_query_data` in the `data_collection` option or set `send_default_pii` to `True`. (This was tested for PyMongo 4.2 and below, but "should" also be future proof) `send_default_pii` will be removed in version 3.0 of the SDK. +- Personal identifiable information (PII) will be stripped from all MongoDB queries if you set `database_query_data` to `False` in the `data_collection` option. (This was tested for PyMongo 4.2 and below, but "should" also be future proof) In SDK versions prior to `3.0`, PII is stripped unless you enable `database_query_data` in `data_collection` or set `send_default_pii` to `True`. ### Other MongoDB libraries diff --git a/docs/platforms/python/integrations/pyramid/index.mdx b/docs/platforms/python/integrations/pyramid/index.mdx index 033d0619abf85..9fc3c1a9901f1 100644 --- a/docs/platforms/python/integrations/pyramid/index.mdx +++ b/docs/platforms/python/integrations/pyramid/index.mdx @@ -60,7 +60,7 @@ When you point your browser to [http://localhost:6543/](http://localhost:6543/) - exceptions that are not handled by any exception view - exceptions whose exception view returns a status code of 500 -- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. - Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. @@ -70,6 +70,12 @@ When you point your browser to [http://localhost:6543/](http://localhost:6543/) ## Options + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, `PyramidIntegration` doesn't accept any options, and service spans are always named after the route pattern, for example `/myurl/{id}`. + + + By adding `PyramidIntegration` to your `sentry_sdk.init()` call explicitly, you can set options for `PyramidIntegration` to change its behavior: diff --git a/docs/platforms/python/integrations/pyreqwest/index.mdx b/docs/platforms/python/integrations/pyreqwest/index.mdx index b4b53e3dd9a8e..a64e889c302c3 100644 --- a/docs/platforms/python/integrations/pyreqwest/index.mdx +++ b/docs/platforms/python/integrations/pyreqwest/index.mdx @@ -58,17 +58,17 @@ def example_sync(): with SyncClientBuilder().error_for_status(True).build() as client: response = client.get("http://example.com").build().send() -# or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode -with sentry_sdk.start_transaction(name="pyreqwest async"): +# In SDK 2.x, use sentry_sdk.start_transaction(name="pyreqwest async") instead +with sentry_sdk.start_span(name="pyreqwest async"): asyncio.run(example_async()) -# or sentry_sdk.traces.start_span(name="your_span_name", parent_span=None) in stream mode -with sentry_sdk.start_transaction(name="pyreqwest sync"): +# In SDK 2.x, use sentry_sdk.start_transaction(name="pyreqwest sync") instead +with sentry_sdk.start_span(name="pyreqwest sync"): example_sync() ``` -This will create two transactions, `pyreqwest async` and `pyreqwest sync`, in the Traces section of [sentry.io](https://sentry.io), and create spans for the outgoing HTTP requests. +This will create two service spans, `pyreqwest async` and `pyreqwest sync`, in the Traces section of [sentry.io](https://sentry.io), and create spans for the outgoing HTTP requests. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). diff --git a/docs/platforms/python/integrations/quart/index.mdx b/docs/platforms/python/integrations/quart/index.mdx index 0aaa51f3915c9..c68b3696483e8 100644 --- a/docs/platforms/python/integrations/quart/index.mdx +++ b/docs/platforms/python/integrations/quart/index.mdx @@ -52,7 +52,7 @@ It takes a couple of moments for the data to appear in [sentry.io](https://sentr - All exceptions leading to an Internal Server Error, from before/after serving functions, and background tasks are reported. -- Request data is attached to all events: **HTTP method, URL, headers**. Sentry also excludes personally identifiable information (such as user IDs, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: **HTTP method, URL, headers**. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. - Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. diff --git a/docs/platforms/python/integrations/ray/index.mdx b/docs/platforms/python/integrations/ray/index.mdx index d309028888b67..801ae1e3be98f 100644 --- a/docs/platforms/python/integrations/ray/index.mdx +++ b/docs/platforms/python/integrations/ray/index.mdx @@ -91,8 +91,8 @@ ray.init( def divide(a, b): return a/b -# or sentry_sdk.traces.start_span(name="ray-test", parent_span=None) in stream mode -with sentry_sdk.start_transaction(name="ray-test"): +# In SDK 2.x, use sentry_sdk.start_transaction(name="ray-test") instead +with sentry_sdk.start_span(name="ray-test"): futures = [ divide.remote(10, 5), divide.remote(10, 0), @@ -100,12 +100,12 @@ with sentry_sdk.start_transaction(name="ray-test"): print(ray.get(futures)) ``` -Running this will create an error event (`ZeroDivisionError`) that will be sent to [sentry.io](https://sentry.io). Additionally, trace information will be created in the Performance section of [sentry.io](https://sentry.io). +Running this will create an error event (`ZeroDivisionError`) that will be sent to [sentry.io](https://sentry.io). Additionally, trace information will be created in the Traces section of [sentry.io](https://sentry.io). ## Behavior - All unhandled exceptions will be captured and can be seen on [sentry.io](https://sentry.io). -- Performance data will be captured and available in the Performance section of [sentry.io](https://sentry.io). +- Performance data will be captured and available in the Traces section of [sentry.io](https://sentry.io). - Performance data from [Ray Tasks](https://docs.ray.io/en/latest/ray-core/tasks.html) will be captured and linked to the calling code. - **Note**: Capturing performance data from [Ray Actors](https://docs.ray.io/en/latest/ray-core/actors.html) is currently **not supported**. (As always, [PRs are welcome](https://github.com/getsentry/sentry-python/blob/master/CONTRIBUTING.md)) diff --git a/docs/platforms/python/integrations/redis/index.mdx b/docs/platforms/python/integrations/redis/index.mdx index 370de83b72bb3..f1ca06d6d38b6 100644 --- a/docs/platforms/python/integrations/redis/index.mdx +++ b/docs/platforms/python/integrations/redis/index.mdx @@ -27,12 +27,12 @@ The following information will be available to you on Sentry: - Performance information about requests to Redis will be available in the waterfall diagram in the [Traces](https://sentry.io/orgredirect/organizations/:orgslug/explore/traces/) section on Sentry. - Redis commands will be added as [breadcrumbs](/product/issues/issue-details/breadcrumbs/). -- If you enable `database_query_data` in the `data_collection` option, or set `send_default_pii` to `True` in your app's `sentry_sdk.init()` call, you will also see the data used in your Redis commands. `send_default_pii` will be removed in version 3.0 of the SDK. +- By default, you will also see the data used in your Redis commands. Turn this off by setting `database_query_data` to `False` in the `data_collection` option. In SDK versions prior to `3.0`, this data is only shown if you enable `database_query_data` in `data_collection` or set `send_default_pii` to `True`. - Sentry will never collect data of the `AUTH` command. ## Verify Your Setup -To verify that Sentry captures your Redis commands, add this code to your app, which will create a transaction called `testing_sentry` in the [Traces](https://sentry.io/orgredirect/organizations/:orgslug/explore/traces/) section: +To verify that Sentry captures your Redis commands, add this code to your app, which will create a service span called `testing_sentry` in the [Traces](https://sentry.io/orgredirect/organizations/:orgslug/explore/traces/) section: ### Standard Redis @@ -43,8 +43,8 @@ def main(): sentry_sdk.init(...) # same as above r = redis.Redis(host='localhost', port=6379, decode_responses=True) - # or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): r.set("foo", "bar") r.get("foo") @@ -60,8 +60,8 @@ def main(): sentry_sdk.init(...) # same as above rc = RedisCluster(host='localhost', port=16379) - # or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): rc.set("foo", "bar") rc.get("foo") @@ -78,8 +78,8 @@ async def main(): sentry_sdk.init(...) # same as above r = redis.Redis(host='localhost', port=6379) - # or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): await r.set("foo", "bar") await r.get("foo") @@ -98,7 +98,6 @@ sentry_sdk.init( # ... integrations=[ RedisIntegration( - max_data_size=None, cache_prefixes=["mycache", "template.cache"], ), ], @@ -109,6 +108,12 @@ You can pass the following keyword arguments to `RedisIntegration()`: + + +Only available in SDK versions prior to `3.0`. + + + Set `max_data_size` to an integer to control how many characters should be collected. When you set this option to a value that evaluates to `False` (like `0` or `None`), no trimming will take place, and the entire Redis command will be recorded. diff --git a/docs/platforms/python/integrations/rq/index.mdx b/docs/platforms/python/integrations/rq/index.mdx index 5196e5c164d02..e5b60e7caf966 100644 --- a/docs/platforms/python/integrations/rq/index.mdx +++ b/docs/platforms/python/integrations/rq/index.mdx @@ -183,14 +183,14 @@ sentry_sdk.init( q = Queue(connection=Redis()) -# or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode -with sentry_sdk.start_transaction(name="testing_sentry"): +# In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead +with sentry_sdk.start_span(name="testing_sentry"): result = q.enqueue(hello, "World") ``` -When you run `python main.py` a transaction named `testing_sentry` will be created in the Performance section of [sentry.io](https://sentry.io) and spans for the enqueueing will be created. +When you run `python main.py` a service span named `testing_sentry` will be created in the Traces section of [sentry.io](https://sentry.io) and spans for the enqueueing will be created. -If you run the RQ worker with `rq worker -c mysettings`, a transaction for the execution of `hello()` will be created. Additionally, an error event will be sent to [sentry.io](https://sentry.io) and will be connected to the transaction. +If you run the RQ worker with `rq worker -c mysettings`, a service span for the execution of `hello()` will be created. Additionally, an error event will be sent to [sentry.io](https://sentry.io) and will be connected to the service span. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). diff --git a/docs/platforms/python/integrations/rust_tracing/index.mdx b/docs/platforms/python/integrations/rust_tracing/index.mdx index 54a8215671885..3360e3bfc9da7 100644 --- a/docs/platforms/python/integrations/rust_tracing/index.mdx +++ b/docs/platforms/python/integrations/rust_tracing/index.mdx @@ -189,15 +189,15 @@ The `pyo3-python-tracing-subscriber` crate has [a working example of a Sentry in The `data_collection` option doesn't affect this behavior. If you use `data_collection` and want field values on your spans, set `include_tracing_fields` to `True` explicitly. - If it is `None`, this behavior will be controlled by the `send_default_pii` option set during SDK initialization. If it is `False`, field values will be redacted on Sentry spans. If it is `True`, field values will be included on Sentry spans. `send_default_pii` will be removed in version 3.0 of the SDK. + If it is `None` or `False`, field values will be redacted on Sentry spans. If it is `True`, field values will be included on Sentry spans. In SDK versions prior to `3.0`, `None` defers to the `send_default_pii` option instead. The default value of this option is `None`. - When the `tracing::instrument` attribute is applied to a Rust function, `tracing` will set all of the function's arguments as span fields by default. This behavior can cause a function argument that contains sensitive data to unintentionally be sent to Sentry. To avoid that, `include_tracing_fields` by default will defer to the `send_default_pii` option which can be set during SDK initialization. + When the `tracing::instrument` attribute is applied to a Rust function, `tracing` will set all of the function's arguments as span fields by default. This behavior can cause a function argument that contains sensitive data to unintentionally be sent to Sentry. To avoid that, field values are redacted unless you set `include_tracing_fields` to `True`. - If you want to set `include_tracing_fields` or `send_default_pii` to `True`, see our documentation for managing sensitive data for ways to keep sensitive data from leaking. + If you want to set `include_tracing_fields` to `True`, see our documentation for managing sensitive data for ways to keep sensitive data from leaking. diff --git a/docs/platforms/python/integrations/sanic/index.mdx b/docs/platforms/python/integrations/sanic/index.mdx index edf2ff60971d6..5b9b23200f0df 100644 --- a/docs/platforms/python/integrations/sanic/index.mdx +++ b/docs/platforms/python/integrations/sanic/index.mdx @@ -69,6 +69,12 @@ async def init_sentry(_): ### Configuration options + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, `SanicIntegration` doesn't accept `unsampled_statuses`, and the integration creates spans for requests with any HTTP status. + + + If you're using tracing, you can configure the Sanic integration to not send transactions for requests that resulted in certain HTTP statuses using the `unsampled_statuses` option. By default, the Sanic integration generates transactions for all requests, except requests that result in a 404 HTTP status. To generate transactions for all HTTP statuses, including 404, or change which HTTP statuses don't generate transactions, you can manually instantiate the Sanic integration when initializing the Sentry SDK, like so: @@ -94,7 +100,7 @@ async def init_sentry(_): ) ``` -To specify a different set of HTTP statuses for which no transactions should be generated, set `unsampled_statuses` to a set containing the HTTP statuses that don't generate transactions. For example, if you wish to have no transactions for requests resulting in a 200 or 404 HTTP status, use `SanicIntegration(unsampled_statuses={200, 400})`. +To specify a different set of HTTP statuses for which no transactions should be generated, set `unsampled_statuses` to a set containing the HTTP statuses that don't generate transactions. For example, if you wish to have no transactions for requests resulting in a 200 or 404 HTTP status, use `SanicIntegration(unsampled_statuses={200, 404})`. ## Verify @@ -124,7 +130,7 @@ When you point your browser to [http://localhost:8000/](http://localhost:8000/) - All exceptions leading to an Internal Server Error are reported. -- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. - Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. diff --git a/docs/platforms/python/integrations/serverless/index.mdx b/docs/platforms/python/integrations/serverless/index.mdx index df39e5ec668c3..427464de534dd 100644 --- a/docs/platforms/python/integrations/serverless/index.mdx +++ b/docs/platforms/python/integrations/serverless/index.mdx @@ -90,7 +90,7 @@ Now deploy your function. When you now run your function an error event will be - You can add more context as described here. -- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. - Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. diff --git a/docs/platforms/python/integrations/socket/index.mdx b/docs/platforms/python/integrations/socket/index.mdx index c1b49a1f78ecb..c8e66d8f01160 100644 --- a/docs/platforms/python/integrations/socket/index.mdx +++ b/docs/platforms/python/integrations/socket/index.mdx @@ -68,15 +68,15 @@ import socket def main(): sentry_init(...) # same as above - # or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): timeout = 10 socket.getaddrinfo("sentry.io", 443) socket.create_connection(("sentry.io", 443), timeout, None) main() ``` -This example will create a transaction called `testing_sentry` in the Performance section of [sentry.io](https://sentry.io), and create spans for the socket commands. +This example will create a service span called `testing_sentry` in the Traces section of [sentry.io](https://sentry.io), and create spans for the socket commands. It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io). diff --git a/docs/platforms/python/integrations/sqlalchemy/index.mdx b/docs/platforms/python/integrations/sqlalchemy/index.mdx index 52d2f326747e3..b69ae91cbdbc2 100644 --- a/docs/platforms/python/integrations/sqlalchemy/index.mdx +++ b/docs/platforms/python/integrations/sqlalchemy/index.mdx @@ -27,7 +27,7 @@ Sentry's SQLAlchemy integration is enabled automatically if you have the `sqlalc ## Verify Your Setup -To verify that Sentry captures your SQLAlchemy queries, add this code to your app, which will create a transaction called `testing_sentry` in the [Traces](https://sentry.io/orgredirect/organizations/:orgslug/explore/traces/) section and will create a span for the `SELECT` statement: +To verify that Sentry captures your SQLAlchemy queries, add this code to your app, which will create a service span called `testing_sentry` in the [Traces](https://sentry.io/orgredirect/organizations/:orgslug/explore/traces/) section and will create a span for the `SELECT` statement: ```python from sqlalchemy import create_engine @@ -41,8 +41,8 @@ def main(): statement = text("SELECT 'Hello World'") with engine.connect() as conn: - # or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode - with sentry_sdk.start_transaction(name="testing_sentry"): + # In SDK 2.x, use sentry_sdk.start_transaction(name="testing_sentry") instead + with sentry_sdk.start_span(name="testing_sentry"): result = conn.execute(statement) main() diff --git a/docs/platforms/python/integrations/starlette/index.mdx b/docs/platforms/python/integrations/starlette/index.mdx index 7e9607c586fb5..b1cd4567a8334 100644 --- a/docs/platforms/python/integrations/starlette/index.mdx +++ b/docs/platforms/python/integrations/starlette/index.mdx @@ -84,7 +84,7 @@ You can also expect the following for your Starlette project: - By default, all exceptions leading to an Internal Server Error are reported. The HTTP status codes to report on are configurable via the `failed_request_status_codes` [option](#options). - Request data will be attached to all events: HTTP method, URL, headers, form data, JSON payloads. Sentry excludes raw bodies and multipart file uploads. -- Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. To learn how to manually report issues, see Capturing Errors. @@ -92,7 +92,7 @@ To learn how to manually report issues, see Capturing Use `sentry_sdk.logger` to send structured logs at different levels. You can include searchable attributes with each message. -To capture records from Python's standard-library `logging` module or Loguru, configure `capture_sentry_logs=True` on the corresponding integration. See the standard logging and Loguru integration guides. +To capture records from Python's standard-library `logging` module or Loguru as Sentry logs, add the corresponding integration to your `integrations`. See the standard logging and Loguru integration guides. See Set Up Logs for all available logging methods and formatting options. @@ -152,7 +152,6 @@ sentry_sdk.init( # ... integrations=[ StarletteIntegration( - transaction_style="endpoint", failed_request_status_codes={403, *range(500, 599)}, middleware_spans=False, http_methods_to_capture=("GET",), @@ -165,6 +164,12 @@ You can pass the following keyword arguments to `StarletteIntegration()`: + + +Only available in SDK versions prior to `3.0`. In SDK `3.x`, service spans are always named after the route pattern, for example `/catalog/product/{product_id}`. + + + How to name transactions that show up in Sentry tracing. The default is `"url"`. diff --git a/docs/platforms/python/integrations/strawberry/index.mdx b/docs/platforms/python/integrations/strawberry/index.mdx index 06db2ff927509..dc39dbb215746 100644 --- a/docs/platforms/python/integrations/strawberry/index.mdx +++ b/docs/platforms/python/integrations/strawberry/index.mdx @@ -139,10 +139,9 @@ sentry_sdk.init( ### Capturing Request and Response Bodies The Strawberry integration can capture request and response bodies -for each GraphQL error that happens. Since these may contain sensitive data, -this isn't the default behavior. +for each GraphQL error that happens. This is enabled by default. -To enable capturing request and response bodies, use the `data_collection` option. The `graphql` key controls the query document and its variables in the request +To control capturing request and response bodies, use the `data_collection` option. The `graphql` key controls the query document and its variables in the request body, and the `outgoing_response` entry in `http_bodies` controls the response body: ```python @@ -155,27 +154,9 @@ sentry_sdk.init( ) ``` -These are also the defaults when you pass a `data_collection` dictionary, so you only -need to set the keys you want to change. See Data Collected for all available keys. +These are the defaults, so you only need to set the keys you want to change. See Data Collected for all available keys. -Alternatively, you can initialize the SDK with the `send_default_pii` option set to `True`, though `send_default_pii` will be removed in version 3.0 of the SDK: - -```python -sentry_sdk.init( - # ... - send_default_pii=True, -) -``` - - - -Since `send_default_pii` is a global SDK option, setting it to `True` will affect all -integrations, not just Strawberry. Please make sure to -[remove sensitive data](/platforms/python/data-management/sensitive-data/) -from events before enabling this option. With `data_collection`, you can enable -only the categories you need instead. - - +In SDK versions prior to `3.0`, this data isn't attached by default. To attach it, pass a `data_collection` dictionary as shown above, or set the `send_default_pii` option to `True`. Since `send_default_pii` is a global SDK option, setting it to `True` affects all integrations, so make sure to [scrub sensitive data](/platforms/python/data-management/sensitive-data/) from events first. ## Notes diff --git a/docs/platforms/python/integrations/tornado/index.mdx b/docs/platforms/python/integrations/tornado/index.mdx index 452849a127145..bddabfa47d441 100644 --- a/docs/platforms/python/integrations/tornado/index.mdx +++ b/docs/platforms/python/integrations/tornado/index.mdx @@ -61,7 +61,7 @@ It takes a couple of moments for the data to appear in [sentry.io](https://sentr - All exceptions leading to a Internal Server Error are reported. -- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. - Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. diff --git a/docs/platforms/python/integrations/tryton/index.mdx b/docs/platforms/python/integrations/tryton/index.mdx index 49ec2d21caa32..041154fee7b97 100644 --- a/docs/platforms/python/integrations/tryton/index.mdx +++ b/docs/platforms/python/integrations/tryton/index.mdx @@ -81,7 +81,7 @@ def _(app, request, e): - All uncaught exceptions not inherited from Tryton exceptions are reported. -- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. diff --git a/docs/platforms/python/integrations/wsgi/index.mdx b/docs/platforms/python/integrations/wsgi/index.mdx index dd963ea1de8d4..b6a937a9e241d 100644 --- a/docs/platforms/python/integrations/wsgi/index.mdx +++ b/docs/platforms/python/integrations/wsgi/index.mdx @@ -90,7 +90,7 @@ make_server('', 8000, app).serve_forever() -- Request data is attached to all events: **HTTP method, URL, headers**. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you configure which categories to collect with the `data_collection` option or set `send_default_pii` to `True`. `send_default_pii` will be removed in version 3.0 of the SDK. +- Request data is attached to all events: **HTTP method, URL, headers**. Sentry excludes raw bodies and multipart file uploads. Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the `data_collection` option to configure which categories to collect. In SDK versions prior to `3.0`, Sentry excludes this information unless you use `data_collection` or set `send_default_pii` to `True`. Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled. diff --git a/docs/platforms/python/profiling/index.mdx b/docs/platforms/python/profiling/index.mdx index 2befc779e36ae..a5c8ef736238f 100644 --- a/docs/platforms/python/profiling/index.mdx +++ b/docs/platforms/python/profiling/index.mdx @@ -91,7 +91,7 @@ Continuous profiling was experimental in SDK versions prior to `2.24.1`. Learn h -Transaction-based profiling is deprecated and will be removed in SDK version `3.0`. Use continuous profiling instead. +Only available in SDK versions prior to `3.0`. Use [continuous profiling](#enabling-continuous-profiling) instead. Transaction-based profiling was available starting in SDK version `1.18.0`. It's not available in stream mode. diff --git a/docs/platforms/python/tracing/configure-sampling/index.mdx b/docs/platforms/python/tracing/configure-sampling/index.mdx index 9ab31a0f77f9a..372a1473fd516 100644 --- a/docs/platforms/python/tracing/configure-sampling/index.mdx +++ b/docs/platforms/python/tracing/configure-sampling/index.mdx @@ -10,7 +10,9 @@ Effective sampling is key to getting the most value from Sentry's performance mo -This page covers both transaction mode (default) and stream mode. See Streamed Spans to learn more. +The examples on this page are for SDK `3.x`. The **SDK 2.x** tabs show the equivalent code for the default transaction mode of SDK `2.x`. + +If you use stream mode in SDK `2.x`, follow the **SDK 3.x** examples, but call the tracing functions on `sentry_sdk.traces` (for example, `sentry_sdk.traces.start_span()`) and set `trace_lifecycle="stream"` in `sentry_sdk.init()`. @@ -18,19 +20,19 @@ This page covers both transaction mode (default) and stream mode. See stream mode) will be sampled. This works the same way in both transaction mode and stream mode: +`traces_sample_rate` is a floating-point value between `0.0` and `1.0`, inclusive, which controls the probability with which each service span (in SDK `2.x`, each transaction) will be sampled: -With `traces_sample_rate` set to `0.25`, each transaction/service span in your application is randomly sampled with a probability of `0.25`, so you can expect that one in every four transactions/service spans will be sent to Sentry. +With `traces_sample_rate` set to `0.25`, each service span in your application is randomly sampled with a probability of `0.25`, so you can expect that one in every four service spans will be sent to Sentry. ### 2. Sampling Function (`traces_sampler`) For more granular control, you can provide a `traces_sampler` function. This approach allows you to: -- Apply different sampling rates to different types of transactions/service spans -- Filter out specific transactions/service spans entirely -- Make sampling decisions based on transaction/service span data +- Apply different sampling rates to different types of service spans +- Filter out specific service spans entirely +- Make sampling decisions based on service span data - Control the inheritance of sampling decisions in distributed traces - Use custom attributes to modify sampling @@ -48,7 +50,7 @@ In distributed systems, implementing inheritance logic when trace information is 1. Prioritizing Critical User Flows -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk from sentry_sdk.types import SamplingContext @@ -60,15 +62,15 @@ def traces_sampler(sampling_context: SamplingContext) -> float: if parent_sampling_decision is not None: return float(parent_sampling_decision) - transaction_ctx = sampling_context["transaction_context"] - name = transaction_ctx["name"] - op = transaction_ctx["op"] + span_ctx = sampling_context["transaction_context"] + name = span_ctx["name"] + op = span_ctx["op"] - # Sample all checkout transactions + # Sample all checkout spans if name and ('/checkout' in name or op == 'checkout'): return 1.0 - # Sample 50% of login transactions + # Sample 50% of login spans if name and ('/login' in name or op == 'login'): return 0.5 @@ -81,7 +83,7 @@ sentry_sdk.init( ) ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk from sentry_sdk.types import SamplingContext @@ -93,15 +95,15 @@ def traces_sampler(sampling_context: SamplingContext) -> float: if parent_sampling_decision is not None: return float(parent_sampling_decision) - span_ctx = sampling_context["transaction_context"] - name = span_ctx["name"] - op = span_ctx["op"] + transaction_ctx = sampling_context["transaction_context"] + name = transaction_ctx["name"] + op = transaction_ctx["op"] - # Sample all checkout spans + # Sample all checkout transactions if name and ('/checkout' in name or op == 'checkout'): return 1.0 - # Sample 50% of login spans + # Sample 50% of login transactions if name and ('/login' in name or op == 'login'): return 0.5 @@ -111,13 +113,12 @@ def traces_sampler(sampling_context: SamplingContext) -> float: sentry_sdk.init( # ... traces_sampler=traces_sampler, - trace_lifecycle="stream", ) ``` 2. Handling Different Environments and Error Rates -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import os import sentry_sdk from sentry_sdk.types import SamplingContext @@ -132,11 +133,11 @@ def traces_sampler(sampling_context: SamplingContext) -> float: environment = os.environ.get("ENVIRONMENT", "development") - # Sample all transactions in development + # Sample all spans in development if environment == "development": return 1.0 - # Sample more transactions if there are recent errors + # Sample more spans if there are recent errors # Note: hasRecentErrors is a custom attribute that needs to be set if sampling_context.get("hasRecentErrors") is True: return 0.8 @@ -156,18 +157,19 @@ sentry_sdk.init( traces_sampler=traces_sampler, ) -# Custom attributes need to be set on transaction start via -# the `custom_sampling_context` argument in order to be available +# Custom attributes need to be set on the scope, after continue_trace +# (which resets the propagation context) and before start_span +# (which is when sampling happens), in order to be available # in the traces_sampler -with sentry_sdk.start_transaction( +sentry_sdk.Scope.set_custom_sampling_context({"hasRecentErrors": True}) +with sentry_sdk.start_span( name="GET /api/users", - op="http.request", - custom_sampling_context={"hasRecentErrors": True}, -) as transaction: + attributes={"sentry.op": "http.request"}, +) as span: # your code here ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import os import sentry_sdk from sentry_sdk.types import SamplingContext @@ -182,11 +184,11 @@ def traces_sampler(sampling_context: SamplingContext) -> float: environment = os.environ.get("ENVIRONMENT", "development") - # Sample all spans in development + # Sample all transactions in development if environment == "development": return 1.0 - # Sample more spans if there are recent errors + # Sample more transactions if there are recent errors # Note: hasRecentErrors is a custom attribute that needs to be set if sampling_context.get("hasRecentErrors") is True: return 0.8 @@ -204,24 +206,22 @@ def traces_sampler(sampling_context: SamplingContext) -> float: sentry_sdk.init( # ... traces_sampler=traces_sampler, - trace_lifecycle="stream", ) -# Custom attributes need to be set on the scope, after continue_trace -# (which resets the propagation context) and before start_span -# (which is when sampling happens), in order to be available +# Custom attributes need to be set on transaction start via +# the `custom_sampling_context` argument in order to be available # in the traces_sampler -sentry_sdk.Scope.set_custom_sampling_context({"hasRecentErrors": True}) -with sentry_sdk.traces.start_span( +with sentry_sdk.start_transaction( name="GET /api/users", - attributes={"sentry.op": "http.request"}, -) as span: + op="http.request", + custom_sampling_context={"hasRecentErrors": True}, +) as transaction: # your code here ``` 3. Controlling Sampling Based on User and Transaction Properties -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk from sentry_sdk.types import SamplingContext @@ -238,7 +238,7 @@ def traces_sampler(sampling_context: SamplingContext) -> float: if sampling_context.get("user", {}).get("tier") == "premium": return 1.0 - # Sample more transactions for users experiencing errors + # Sample more spans for users experiencing errors # Note: hasRecentErrors is a custom attribute if sampling_context.get("hasRecentErrors") is True: return 0.8 @@ -258,15 +258,17 @@ sentry_sdk.init( ) # To set custom attributes for this example: -with sentry_sdk.start_transaction( +sentry_sdk.Scope.set_custom_sampling_context( + {"user": {"tier": "premium"}, "hasRecentErrors": True} +) +with sentry_sdk.start_span( name="GET /api/users", - op="http.request", - custom_sampling_context={"user": {"tier": "premium"}, "hasRecentErrors": True}, -) as transaction: + attributes={"sentry.op": "http.request"}, +) as span: # Your code here ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk from sentry_sdk.types import SamplingContext @@ -283,7 +285,7 @@ def traces_sampler(sampling_context: SamplingContext) -> float: if sampling_context.get("user", {}).get("tier") == "premium": return 1.0 - # Sample more spans for users experiencing errors + # Sample more transactions for users experiencing errors # Note: hasRecentErrors is a custom attribute if sampling_context.get("hasRecentErrors") is True: return 0.8 @@ -300,23 +302,20 @@ def traces_sampler(sampling_context: SamplingContext) -> float: sentry_sdk.init( # ... traces_sampler=traces_sampler, - trace_lifecycle="stream", ) # To set custom attributes for this example: -sentry_sdk.Scope.set_custom_sampling_context( - {"user": {"tier": "premium"}, "hasRecentErrors": True} -) -with sentry_sdk.traces.start_span( +with sentry_sdk.start_transaction( name="GET /api/users", - attributes={"sentry.op": "http.request"}, -) as span: + op="http.request", + custom_sampling_context={"user": {"tier": "premium"}, "hasRecentErrors": True}, +) as transaction: # Your code here ``` 4. Complex Business Logic Sampling -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk from sentry_sdk.types import SamplingContext @@ -329,9 +328,9 @@ def traces_sampler(sampling_context: SamplingContext) -> float: return float(parent_sampling_decision) # Always sample critical business operations - # Note: op is an SDK-provided attribute - transaction_ctx = sampling_context["transaction_context"] - if transaction_ctx["op"] in ["payment.process", "order.create", "user.verify"]: + # Note: sentry.op is an SDK-provided attribute + span_ctx = sampling_context["transaction_context"] + if span_ctx["op"] in ["payment.process", "order.create", "user.verify"]: return 1.0 # Sample based on user segment @@ -364,15 +363,17 @@ sentry_sdk.init( ) # To set custom attributes for this example: -with sentry_sdk.start_transaction( +sentry_sdk.Scope.set_custom_sampling_context( + {"user": {"segment": "enterprise"}, "transaction": {"value": 1500}, "service": {"error_rate": 0.03}} +) +with sentry_sdk.start_span( name="Process Payment", - op="payment.process", - custom_sampling_context={"user": {"segment": "enterprise"}, "transaction": {"value": 1500}, "service": {"error_rate": 0.03}}, -) as transaction: + attributes={"sentry.op": "payment.process"}, +) as span: # Your code here ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk from sentry_sdk.types import SamplingContext @@ -385,9 +386,9 @@ def traces_sampler(sampling_context: SamplingContext) -> float: return float(parent_sampling_decision) # Always sample critical business operations - # Note: sentry.op is an SDK-provided attribute - span_ctx = sampling_context["transaction_context"] - if span_ctx["op"] in ["payment.process", "order.create", "user.verify"]: + # Note: op is an SDK-provided attribute + transaction_ctx = sampling_context["transaction_context"] + if transaction_ctx["op"] in ["payment.process", "order.create", "user.verify"]: return 1.0 # Sample based on user segment @@ -417,23 +418,20 @@ def traces_sampler(sampling_context: SamplingContext) -> float: sentry_sdk.init( # ... traces_sampler=traces_sampler, - trace_lifecycle="stream", ) # To set custom attributes for this example: -sentry_sdk.Scope.set_custom_sampling_context( - {"user": {"segment": "enterprise"}, "transaction": {"value": 1500}, "service": {"error_rate": 0.03}} -) -with sentry_sdk.traces.start_span( +with sentry_sdk.start_transaction( name="Process Payment", - attributes={"sentry.op": "payment.process"}, -) as span: + op="payment.process", + custom_sampling_context={"user": {"segment": "enterprise"}, "transaction": {"value": 1500}, "service": {"error_rate": 0.03}}, +) as transaction: # Your code here ``` 5. Performance-Based Sampling -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk from sentry_sdk.types import SamplingContext @@ -445,19 +443,19 @@ def traces_sampler(sampling_context: SamplingContext) -> float: if parent_sampling_decision is not None: return float(parent_sampling_decision) - # Sample more transactions with high memory usage + # Sample more spans with high memory usage # Note: memory_usage_mb is a custom attribute memory_usage = sampling_context.get("memory_usage_mb") if memory_usage is not None and memory_usage > 500: return 0.8 - # Sample more transactions with high CPU usage + # Sample more spans with high CPU usage # Note: cpu_percent is a custom attribute cpu_percent = sampling_context.get("cpu_percent") if cpu_percent is not None and cpu_percent > 80: return 0.8 - # Sample more transactions with high database load + # Sample more spans with high database load # Note: db_connections is a custom attribute db_connections = sampling_context.get("db_connections") if db_connections is not None and db_connections > 100: @@ -473,15 +471,17 @@ sentry_sdk.init( ) # To set custom attributes for this example: -with sentry_sdk.start_transaction( +sentry_sdk.Scope.set_custom_sampling_context( + {"memory_usage_mb": 600, "cpu_percent": 85, "db_connections": 120} +) +with sentry_sdk.start_span( name="Process Data", - op="data.process", - custom_sampling_context={"memory_usage_mb": 600, "cpu_percent": 85, "db_connections": 120}, -) as transaction: + attributes={"sentry.op": "data.process"}, +) as span: # Your code here ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk from sentry_sdk.types import SamplingContext @@ -493,19 +493,19 @@ def traces_sampler(sampling_context: SamplingContext) -> float: if parent_sampling_decision is not None: return float(parent_sampling_decision) - # Sample more spans with high memory usage + # Sample more transactions with high memory usage # Note: memory_usage_mb is a custom attribute memory_usage = sampling_context.get("memory_usage_mb") if memory_usage is not None and memory_usage > 500: return 0.8 - # Sample more spans with high CPU usage + # Sample more transactions with high CPU usage # Note: cpu_percent is a custom attribute cpu_percent = sampling_context.get("cpu_percent") if cpu_percent is not None and cpu_percent > 80: return 0.8 - # Sample more spans with high database load + # Sample more transactions with high database load # Note: db_connections is a custom attribute db_connections = sampling_context.get("db_connections") if db_connections is not None and db_connections > 100: @@ -518,17 +518,14 @@ def traces_sampler(sampling_context: SamplingContext) -> float: sentry_sdk.init( # ... traces_sampler=traces_sampler, - trace_lifecycle="stream", ) # To set custom attributes for this example: -sentry_sdk.Scope.set_custom_sampling_context( - {"memory_usage_mb": 600, "cpu_percent": 85, "db_connections": 120} -) -with sentry_sdk.traces.start_span( +with sentry_sdk.start_transaction( name="Process Data", - attributes={"sentry.op": "data.process"}, -) as span: + op="data.process", + custom_sampling_context={"memory_usage_mb": 600, "cpu_percent": 85, "db_connections": 120}, +) as transaction: # Your code here ``` @@ -538,31 +535,31 @@ with sentry_sdk.traces.start_span( When the `traces_sampler` function is called, the Sentry SDK passes a `sampling_context` object with information from the relevant span to help make sampling decisions: -### Transaction Mode (Default) +### SDK 3.x ```python { "transaction_context": { - "name": str, # transaction title at creation time (SDK-provided) - "op": str, # short description of transaction type (SDK-provided) - "data": Optional[dict[str, Any]] + "name": str, # span title at creation time (SDK-provided) + "op": str, # short description of span type (SDK-provided) + "data": dict[str, Any] # attributes set at span-creation time (SDK- and user-provided) }, - "parent_sampled": Optional[bool], # whether the parent transaction was sampled (SDK-provided) - ... # additional custom data for sampling provided via custom_sampling_context + "parent_sampled": Optional[bool], # whether the parent span was sampled (SDK-provided) + ... # additional custom key-value pairs for sampling set via custom sampling context } ``` -### Stream Mode +### SDK 2.x ```python { "transaction_context": { - "name": str, # span title at creation time (SDK-provided) - "op": str, # short description of span type (SDK-provided) - "data": dict[str, Any] # attributes set at span-creation time (SDK- and user-provided) + "name": str, # transaction title at creation time (SDK-provided) + "op": str, # short description of transaction type (SDK-provided) + "data": Optional[dict[str, Any]] }, - "parent_sampled": Optional[bool], # whether the parent span was sampled (SDK-provided) - ... # additional custom key-value pairs for sampling set via custom sampling context + "parent_sampled": Optional[bool], # whether the parent transaction was sampled (SDK-provided) + ... # additional custom data for sampling provided via custom_sampling_context } ``` @@ -570,35 +567,42 @@ When the `traces_sampler` function is called, the Sentry SDK passes a `sampling_ The sampling context contains both SDK-provided attributes and custom attributes: -#### Transaction Mode (Default) +#### SDK 3.x **SDK-Provided Attributes:** -- `transaction_context.name`: The name of the transaction -- `transaction_context.op`: The operation type -- `parent_sampled`: Whether the parent transaction was sampled +- `transaction_context.name`: The name of the span +- `transaction_context.data`: Attributes set on the span at creation time, including `sentry.op` +- `parent_sampled`: Whether the parent span was sampled **Custom Attributes:** -- Any data you add to the `custom_sampling_context` parameter in `start_transaction`. Use this for data that you want to use for sampling decisions but don't want to include in the transaction data that gets sent to Sentry. Read more about sampling context [here](/platforms/python/sampling/#sampling-context). +- Any data you add via `sentry_sdk.Scope.set_custom_sampling_context()`, called after `continue_trace` and before `start_span`. Use this for data that you want to use for sampling decisions but don't want to include in the span data that gets sent to Sentry. Read more about sampling context [here](/platforms/python/sampling/#sampling-context). -#### Stream Mode +#### SDK 2.x **SDK-Provided Attributes:** -- `transaction_context.name`: The name of the span -- `transaction_context.data`: Attributes set on the span at creation time, including `sentry.op` -- `parent_sampled`: Whether the parent span was sampled +- `transaction_context.name`: The name of the transaction +- `transaction_context.op`: The operation type +- `parent_sampled`: Whether the parent transaction was sampled **Custom Attributes:** -- Any data you add via `sentry_sdk.Scope.set_custom_sampling_context()`, called after `continue_trace` and before `start_span`. Use this for data that you want to use for sampling decisions but don't want to include in the span data that gets sent to Sentry. Read more about sampling context [here](/platforms/python/sampling/#sampling-context). +- Any data you add to the `custom_sampling_context` parameter in `start_transaction`. Use this for data that you want to use for sampling decisions but don't want to include in the transaction data that gets sent to Sentry. Read more about sampling context [here](/platforms/python/sampling/#sampling-context). ## Sampling Decision Precedence When multiple sampling mechanisms could apply, Sentry follows this order of precedence: -### Transaction Mode (Default) +### SDK 3.x + +1. If `traces_sampler` is defined, its decision is used. Although the `traces_sampler` can override the parent sampling decision, most users will want to ensure their `traces_sampler` respects the parent sampling decision. +2. If no `traces_sampler` is defined, but there is a parent sampling decision from an incoming distributed trace, we use the parent sampling decision. +3. If neither of the above, `traces_sample_rate` is used. +4. If none of the above are set, no spans are sampled. This is equivalent to setting `traces_sample_rate=0.0`. + +### SDK 2.x 1. If a sampling decision is passed to `start_transaction`, that decision is used. 2. If `traces_sampler` is defined, its decision is used. Although the `traces_sampler` can override the parent sampling decision, most users will want to ensure their `traces_sampler` respects the parent sampling decision. @@ -606,13 +610,6 @@ When multiple sampling mechanisms could apply, Sentry follows this order of prec 4. If neither of the above, `traces_sample_rate` is used. 5. If none of the above are set, no transactions are sampled. This is equivalent to setting `traces_sample_rate=0.0`. -### Stream Mode - -1. If `traces_sampler` is defined, its decision is used. Although the `traces_sampler` can override the parent sampling decision, most users will want to ensure their `traces_sampler` respects the parent sampling decision. -2. If no `traces_sampler` is defined, but there is a parent sampling decision from an incoming distributed trace, we use the parent sampling decision. -3. If neither of the above, `traces_sample_rate` is used. -4. If none of the above are set, no spans are sampled. This is equivalent to setting `traces_sample_rate=0.0`. - Sampling decisions are made when spans are created. Child spans inherit the sampling decision of their parent span unless filtered by `ignore_spans`. diff --git a/docs/platforms/python/tracing/instrumentation/custom-instrumentation/caches-module.mdx b/docs/platforms/python/tracing/instrumentation/custom-instrumentation/caches-module.mdx index 71a27e01f0058..348a4b89d4118 100644 --- a/docs/platforms/python/tracing/instrumentation/custom-instrumentation/caches-module.mdx +++ b/docs/platforms/python/tracing/instrumentation/custom-instrumentation/caches-module.mdx @@ -18,7 +18,7 @@ If you're using a custom caching solution that doesn't have auto instrumentation To make it possible for Sentry to give you an overview of your cache performance, you'll need to create two spans - one indicating that something is being put into the cache, and a second one indicating that something is being fetched from the cache. -In transaction mode, make sure that there's a transaction running when you create the spans. If you're using a web framework those transactions will be created for you automatically. See Tracing for more information. +In transaction mode, prior to 3.0, make sure that there's a transaction running when you create the spans. If you're using a web framework, it will be created for you automatically. See Tracing for more information. For detailed information about which data can be set, see the [Cache Module Developer Specification](https://develop.sentry.dev/sdk/performance/modules/caches/). diff --git a/docs/platforms/python/tracing/instrumentation/custom-instrumentation/index.mdx b/docs/platforms/python/tracing/instrumentation/custom-instrumentation/index.mdx index 4365df7c95bf6..79d8cdd3a0f9c 100644 --- a/docs/platforms/python/tracing/instrumentation/custom-instrumentation/index.mdx +++ b/docs/platforms/python/tracing/instrumentation/custom-instrumentation/index.mdx @@ -7,7 +7,7 @@ The Sentry SDK for Python does a very good job of auto instrumenting your applic -This page covers both transaction mode (default) and stream mode. See Streamed Spans to learn more. +The examples on this page are for SDK `3.x`. The **SDK 2.x** tabs show the equivalent code for the default transaction mode of SDK `2.x`. If you use stream mode in SDK `2.x`, follow the **SDK 3.x** examples, but call the tracing functions on `sentry_sdk.traces` (for example, `sentry_sdk.traces.start_span()`) and set `trace_lifecycle="stream"` in `sentry_sdk.init()`. @@ -17,104 +17,104 @@ The parameter `name` in `start_span()` used to be called `description`. In versi -## Add a Transaction/Service Span +## Add a Service Span -Adding transactions or service spans (in stream mode) will allow you to instrument and capture certain regions of your code. +Adding service spans (transactions in SDK `2.x`) will allow you to instrument and capture certain regions of your code. -If you're using one of Sentry's SDK integrations, transactions/service spans will be created for you automatically. +If you're using one of Sentry's SDK integrations, service spans will be created for you automatically. -The following example creates a transaction/service span for an expensive operation (in this case, `eat_pizza`), and then sends the result to Sentry: +The following example creates a service span for an expensive operation (in this case, `eat_pizza`), and then sends the result to Sentry: -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk def eat_slice(slice): ... def eat_pizza(pizza): - with sentry_sdk.start_transaction(op="task", name="Eat Pizza"): + with sentry_sdk.start_span( + name="Eat Pizza", + attributes={"sentry.op": "task"}, + # set parent span to None to create service span + parent_span=None, + ): while pizza.slices > 0: + span = sentry_sdk.start_span(name="Eat Slice") eat_slice(pizza.slices.pop()) + span.end() ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk def eat_slice(slice): ... def eat_pizza(pizza): - with sentry_sdk.traces.start_span( - name="Eat Pizza", - attributes={"sentry.op": "task"}, - # set parent span to None to create service span - parent_span=None, - ): + with sentry_sdk.start_transaction(op="task", name="Eat Pizza"): while pizza.slices > 0: - span = sentry_sdk.traces.start_span(name="Eat Slice") eat_slice(pizza.slices.pop()) - span.end() ``` -The [API reference](https://getsentry.github.io/sentry-python/api.html#performance-monitoring) documents `start_transaction` and `start_span`, along with their parameters. +The [API reference](https://getsentry.github.io/sentry-python/api.html#performance-monitoring) documents `start_span`, along with its parameters. -Note that `sentry_sdk.start_transaction()` (transaction mode) is meant be used as a context manager. This ensures that the transaction/service span will be properly set as active and any spans created within will be attached to it. +`sentry_sdk.start_span()` can, but doesn't have to be, used as a context manager. If you don't use it as a context manager, make sure to call `span.end()` to finish the span. -In stream mode, `sentry_sdk.traces.start_span()` can, but doesn't have to be, used as a context manager. If you don't use it as a context manager, make sure to call `span.end()` to finish the span. +In SDK `2.x`, `sentry_sdk.start_transaction()` is meant to be used as a context manager. This ensures that the transaction will be properly set as active and any spans created within will be attached to it. -## Add Spans to a Transaction/Service Span +## Add Spans to a Service Span -If you want to have more fine-grained performance monitoring, you can add child spans to your transaction/service span, which can be done by either: +If you want to have more fine-grained performance monitoring, you can add child spans to your service span, which can be done by either: - Using a context manager - Using a decorator (this works on sync and async functions) - Manually starting and finishing a span -Calling `sentry_sdk.start_span()` in transaction mode or `sentry_sdk.traces.start_span()` in stream mode will find the current active transaction/span and attach the new span to it. +Calling `sentry_sdk.start_span()` will find the current active span and attach the new span to it. ### Using a Context Manager -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk def eat_slice(slice): ... def eat_pizza(pizza): - with sentry_sdk.start_transaction(op="task", name="Eat Pizza"): + with sentry_sdk.start_span( + name="Eat Pizza", + attributes={"sentry.op": "task"}, + parent_span=None, + ): while pizza.slices > 0: with sentry_sdk.start_span(name="Eat Slice"): eat_slice(pizza.slices.pop()) ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk def eat_slice(slice): ... def eat_pizza(pizza): - with sentry_sdk.traces.start_span( - name="Eat Pizza", - attributes={"sentry.op": "task"}, - parent_span=None, - ): + with sentry_sdk.start_transaction(op="task", name="Eat Pizza"): while pizza.slices > 0: - with sentry_sdk.traces.start_span(name="Eat Slice"): + with sentry_sdk.start_span(name="Eat Slice"): eat_slice(pizza.slices.pop()) ``` ### Using a Decorator -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk @sentry_sdk.trace @@ -122,24 +122,24 @@ def eat_slice(slice): ... def eat_pizza(pizza): - with sentry_sdk.start_transaction(op="task", name="Eat Pizza"): + with sentry_sdk.start_span( + name="Eat Pizza", + attributes={"sentry.op": "task"}, + parent_span=None, + ): while pizza.slices > 0: eat_slice(pizza.slices.pop()) ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk -@sentry_sdk.traces.trace +@sentry_sdk.trace def eat_slice(slice): ... def eat_pizza(pizza): - with sentry_sdk.traces.start_span( - name="Eat Pizza", - attributes={"sentry.op": "task"}, - parent_span=None, - ): + with sentry_sdk.start_transaction(op="task", name="Eat Pizza"): while pizza.slices > 0: eat_slice(pizza.slices.pop()) ``` @@ -148,45 +148,45 @@ See the [@sentry_sdk.trace decoration section](#sentry_sdktrace-decorator) below -When tracing a static or class method, you **must** add the `@sentry_sdk.trace` (transaction mode)/`@sentry_sdk.traces.trace` (stream mode) decorator **after** the `@staticmethod` or `@classmethod` decorator (i.e., **closer** to the function definition). Otherwise, your function will break! This applies in both transaction mode and stream mode. +When tracing a static or class method, you **must** add the `@sentry_sdk.trace` decorator **after** the `@staticmethod` or `@classmethod` decorator (i.e., **closer** to the function definition). Otherwise, your function will break. ### Manually Starting and Finishing a Span -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk def eat_slice(slice): ... def eat_pizza(pizza): - with sentry_sdk.start_transaction(op="task", name="Eat Pizza"): + with sentry_sdk.start_span( + name="Eat Pizza", + attributes={"sentry.op": "task"}, + parent_span=None, + ): while pizza.slices > 0: span = sentry_sdk.start_span(name="Eat Slice") eat_slice(pizza.slices.pop()) - span.finish() + span.end() ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk def eat_slice(slice): ... def eat_pizza(pizza): - with sentry_sdk.traces.start_span( - name="Eat Pizza", - attributes={"sentry.op": "task"}, - parent_span=None, - ): + with sentry_sdk.start_transaction(op="task", name="Eat Pizza"): while pizza.slices > 0: - span = sentry_sdk.traces.start_span(name="Eat Slice") + span = sentry_sdk.start_span(name="Eat Slice") eat_slice(pizza.slices.pop()) - span.end() + span.finish() ``` -When you create your span manually, make sure to call `span.finish()` (transaction mode) or `span.end()` (stream mode) after the block of code you want to wrap in a span to finish the span. If you do not finish the span it will not be sent to Sentry. +When you create your span manually, make sure to call `span.end()` (in SDK `2.x`, `span.finish()`) after the block of code you want to wrap in a span to finish the span. If you do not finish the span it will not be sent to Sentry. ## Nested Spans @@ -194,7 +194,7 @@ Spans can be nested to form a span tree. If you'd like to learn more, read our [ ### Using a Context Manager -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk def chew(): @@ -206,21 +206,21 @@ def eat_slice(slice): chew() ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk def chew(): ... def eat_slice(slice): - with sentry_sdk.traces.start_span(name="Eat Slice"): - with sentry_sdk.traces.start_span(name="Chew"): + with sentry_sdk.start_span(name="Eat Slice"): + with sentry_sdk.start_span(name="Chew"): chew() ``` ### Using a Decorator -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk @sentry_sdk.trace @@ -232,14 +232,14 @@ def eat_slice(slice): chew() ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk -@sentry_sdk.traces.trace +@sentry_sdk.trace def chew(): ... -@sentry_sdk.traces.trace +@sentry_sdk.trace def eat_slice(slice): chew() ``` @@ -248,7 +248,7 @@ See the [@sentry_sdk.trace decoration section](#sentry_sdktrace-decorator) below ### Manually Starting and Finishing -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk def chew(): @@ -257,44 +257,45 @@ def chew(): def eat_slice(slice): parent_span = sentry_sdk.start_span(name="Eat Slice") - child_span = parent_span.start_child(name="Chew") + # pass the parent span via `parent_span` to create a child span + child_span = sentry_sdk.start_span(name="Chew", parent_span=parent_span) chew() - child_span.finish() + child_span.end() - parent_span.finish() + parent_span.end() ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk def chew(): ... def eat_slice(slice): - parent_span = sentry_sdk.traces.start_span(name="Eat Slice") + parent_span = sentry_sdk.start_span(name="Eat Slice") - # pass the parent span via `parent_span` to create a child span - child_span = sentry_sdk.traces.start_span(name="Chew", parent_span=parent_span) + child_span = parent_span.start_child(name="Chew") chew() - child_span.end() + child_span.finish() - parent_span.end() + parent_span.finish() ``` -In transaction mode, the parameters of `start_span()` and `start_child()` are the same. See the [API reference](https://getsentry.github.io/sentry-python/api.html#sentry_sdk.api.start_span) for more details. -In stream mode, however, there's no separate `start_child()` method. Instead, the span will become the child of the currently active span. Alternatively, you can pass the parent span explicitly via `parent_span` when starting the child (as shown in the example above). +There's no separate `start_child()` method. Instead, the span will become the child of the currently active span. Alternatively, you can pass the parent span explicitly via `parent_span` when starting the child (as shown in the example above). See the [API reference](https://getsentry.github.io/sentry-python/api.html#sentry_sdk.api.start_span) for more details. + +In SDK `2.x`, the parameters of `start_span()` and `start_child()` are the same. -When you create your span manually, make sure to call `span.finish()` (transaction mode) or `span.end()` (stream mode) after the block of code you want to wrap in a span to finish the span. If you do not finish the span it will not be sent to Sentry. +When you create your span manually, make sure to call `span.end()` (in SDK `2.x`, `span.finish()`) after the block of code you want to wrap in a span to finish the span. If you do not finish the span it will not be sent to Sentry. ### Sibling Spans -Only available in stream mode. +In SDK `2.x`, only available in stream mode. -In stream mode, a span normally attaches to whatever span is currently active. To control parentage explicitly, for example to make a span a sibling instead of a child, pass `parent_span` directly: +A span normally attaches to whatever span is currently active. To control parentage explicitly, for example to make a span a sibling instead of a child, pass `parent_span` directly: ```python import sentry_sdk @@ -306,9 +307,9 @@ def chew(): ... def eat_pizza(pizza): - with sentry_sdk.traces.start_span(name="Eat Pizza") as pizza_span: - with sentry_sdk.traces.start_span(name="Eat Slice"): - with sentry_sdk.traces.start_span(name="Chew", parent_span=pizza_span): + with sentry_sdk.start_span(name="Eat Pizza") as pizza_span: + with sentry_sdk.start_span(name="Eat Slice"): + with sentry_sdk.start_span(name="Chew", parent_span=pizza_span): # "Chew" is a sibling of "Eat Slice", not its child chew() eat_slice(pizza.slices.pop()) @@ -316,9 +317,9 @@ def eat_pizza(pizza): ## @sentry_sdk.trace decorator -In transaction mode, you can set `op`, `name` and `attributes` parameters in the `@sentry_sdk.trace` decorator to customize your spans. Attribute values can only be primitive types (like `int`, `float`, `bool`, `str`) or a list of those types without mixing types. +The `@sentry_sdk.trace` decorator accepts `name`, `attributes`, and `active` to customize your spans. Note that there's no `op` parameter; set the operation as the `sentry.op` key in `attributes` instead. Attribute values can only be primitive types (like `int`, `float`, `bool`, `str`) or a list of those types without mixing types. -In stream mode, the decorator is `@sentry_sdk.traces.trace` and accepts `name`, `attributes`, and `active`. Note that there's no `op` parameter; set the operation as the `sentry.op` key in `attributes` instead. Attribute values can only be primitive types (like `int`, `float`, `bool`, `str`) or a list of those types without mixing types. +In SDK `2.x`, the decorator accepts `op`, `name`, and `attributes`. @@ -326,10 +327,10 @@ When tracing a static or class method, you **must** add the decorator **after** -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk -@sentry_sdk.trace(op="my_op", name="Paul", attributes={"x": True}) +@sentry_sdk.trace(name="Paul", attributes={"sentry.op": "my_op", "x": True}) def my_function(i): ... @@ -341,14 +342,14 @@ def root_function(): root_function() ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk -@sentry_sdk.traces.trace(name="Paul", attributes={"sentry.op": "my_op", "x": True}) +@sentry_sdk.trace(op="my_op", name="Paul", attributes={"x": True}) def my_function(i): ... -@sentry_sdk.traces.trace +@sentry_sdk.trace def root_function(): for i in range(3): my_function(i) @@ -373,7 +374,7 @@ gantt -The `template` parameter is only available in transaction mode. +Only available in SDK versions prior to `3.0`. @@ -451,13 +452,13 @@ To enable performance monitoring for the functions specified in `functions_to_tr -Only available in transaction mode. +Only available in SDK versions prior to `3.0`. Use [`sentry_sdk.get_current_span()`](#accessing-the-current-span) instead. The `sentry_sdk.get_current_scope().transaction` property returns the active transaction or `None` if no transaction is active. You can use this property to modify data on the transaction. -```python {tabTitle:Transaction Mode (Default)} +```python import sentry_sdk def eat_pizza(pizza): @@ -472,11 +473,11 @@ def eat_pizza(pizza): ## Accessing the Current Span -To change data in the current span, use ` sentry_sdk.get_current_span()` (transaction mode) or `sentry_sdk.traces.get_current_span()` (stream mode). This function will return a span if there's one running, otherwise it will return `None`. +To change data in the current span, use `sentry_sdk.get_current_span()`. This function will return a span if there's one running, otherwise it will return `None`. In this example, we'll set custom data in the span created by the `@sentry_sdk.trace` decorator. -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk @sentry_sdk.trace @@ -484,36 +485,28 @@ def eat_slice(slice): span = sentry_sdk.get_current_span() if span is not None: - span.set_tag("slice_id", slice.id) + span.set_attribute("slice_id", slice.id) ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk -@sentry_sdk.traces.trace +@sentry_sdk.trace def eat_slice(slice): - span = sentry_sdk.traces.get_current_span() + span = sentry_sdk.get_current_span() if span is not None: - span.set_attribute("slice_id", slice.id) + span.set_tag("slice_id", slice.id) ``` ## Adding Span Attributes Span attributes describe an operation in a trace: which provider handled a request, which fallback ran, or what outcome it produced. When investigating a slow checkout, compare charge spans by `payment.provider` and open an outlier trace to see what happened. The span already records its duration, so you don't need a separate duration attribute. -Add attributes to the span for the operation they describe, rather than creating an empty span just to hold attributes. In transaction mode, use `set_data()`; in stream mode, use `set_attribute()` or `set_attributes()`. Values can be strings, numbers, booleans, or arrays containing only one of these types. For example, record what happens during a payment charge: +Add attributes to the span for the operation they describe, rather than creating an empty span just to hold attributes. Use `set_attribute()` or `set_attributes()` (in SDK `2.x`, `set_data()`). Values can be strings, numbers, booleans, or arrays containing only one of these types. For example, record what happens during a payment charge: -```python {tabTitle:Transaction Mode (Default)} -with sentry_sdk.start_span(op="payment.charge", name="Charge payment provider") as span: - span.set_data("payment.provider", provider.name) - result = provider.charge(order) - span.set_data("payment.retry_count", result.retry_count) - span.set_data("payment.outcome", result.outcome) -``` - -```python {tabTitle:Stream Mode} -with sentry_sdk.traces.start_span( +```python {tabTitle:SDK 3.x} +with sentry_sdk.start_span( name="Charge payment provider", attributes={"sentry.op": "payment.charge", "payment.provider": provider.name}, ) as span: @@ -524,6 +517,14 @@ with sentry_sdk.traces.start_span( }) ``` +```python {tabTitle:SDK 2.x} +with sentry_sdk.start_span(op="payment.charge", name="Charge payment provider") as span: + span.set_data("payment.provider", provider.name) + result = provider.charge(order) + span.set_data("payment.retry_count", result.retry_count) + span.set_data("payment.outcome", result.outcome) +``` + Choose consistent names and values you can filter or group by. Avoid sensitive values such as raw search terms and payment details. In [Trace Explorer](/product/trace-explorer/), filter on `span.op:payment.charge`, compare `span.duration` by `payment.provider`, and open a slow sample to inspect retries and other bottlenecks. Attributes belong to sampled traces. For counters, gauges, or distributions independent of trace sampling, such as failed checkout counts or queue depth, use [Application Metrics](/product/metrics/) instead. To add shared context to every span, use the appropriate callback for your tracing mode: @@ -544,11 +545,11 @@ Attributes belong to sampled traces. For counters, gauges, or distributions inde -`sentry_sdk.update_current_span()` isn't available in stream mode. Retrieve the current span with `sentry_sdk.traces.get_current_span()` and update its attributes using `set_attribute()` or `set_attributes()`. +Only available in SDK versions prior to `3.0`. Retrieve the current span with `sentry_sdk.get_current_span()` and update its attributes using `set_attribute()` or `set_attributes()` instead. -In transaction mode, you can update the data of the currently running span using the `sentry_sdk.update_current_span()` function. You can set `op`, `name` and `attributes` to update your span. Attribute values can only be primitive types (like `int`, `float`, `bool`, `str`) or a list of those types without mixing types. +In SDK `2.x`, you can update the data of the currently running span using the `sentry_sdk.update_current_span()` function. You can set `op`, `name` and `attributes` to update your span. Attribute values can only be primitive types (like `int`, `float`, `bool`, `str`) or a list of those types without mixing types. ```python {diff} import sentry_sdk diff --git a/docs/platforms/python/tracing/instrumentation/custom-instrumentation/mcp-module.mdx b/docs/platforms/python/tracing/instrumentation/custom-instrumentation/mcp-module.mdx index 11d4e019a8655..5ed4326f27587 100644 --- a/docs/platforms/python/tracing/instrumentation/custom-instrumentation/mcp-module.mdx +++ b/docs/platforms/python/tracing/instrumentation/custom-instrumentation/mcp-module.mdx @@ -10,7 +10,7 @@ As a prerequisite to setting up MCP monitoring with Python, you'll need to first -This page covers both transaction mode (default) and stream mode. See Streamed Spans to learn more. +The examples on this page are for SDK `3.x`. The **SDK 2.x** tabs show the equivalent code for the default transaction mode of SDK `2.x`. If you use stream mode in SDK `2.x`, follow the **SDK 3.x** examples, but call the tracing functions on `sentry_sdk.traces` (for example, `sentry_sdk.traces.start_span()`) and set `trace_lifecycle="stream"` in `sentry_sdk.init()`. @@ -24,8 +24,7 @@ The Python SDK supports automatic instrumentation for MCP servers. We recommend For your MCP data to show up in Sentry, spans must be created with well-defined names and data attributes. See below for the different types of MCP operations you can instrument. -In transaction mode, you can also use the [@sentry_sdk.trace()](/platforms/python/tracing/instrumentation/custom-instrumentation/#span-templates) decorator to create these spans, using its `template` parameter. -In stream mode, these spans need to be created directly with `sentry_sdk.traces.start_span()`, as shown below. +Create these spans directly with `sentry_sdk.start_span()`, as shown below. In SDK `2.x`, you can also use the [@sentry_sdk.trace()](/platforms/python/tracing/instrumentation/custom-instrumentation/#span-templates) decorator with its `template` parameter. ## Spans @@ -35,7 +34,7 @@ In stream mode, these spans need to be created directly with `sentry_sdk.traces. #### Example Tool Execution Span: -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk import json @@ -46,40 +45,42 @@ tool_name = "get_weather" tool_arguments = {"city": "San Francisco"} with sentry_sdk.start_span( - op="mcp.server", name=f"tools/call {tool_name}", + attributes={"sentry.op": "mcp.server"}, ) as span: # Set MCP-specific attributes - span.set_data("mcp.tool.name", tool_name) - span.set_data("mcp.method.name", "tools/call") + span.set_attributes({ + "mcp.tool.name": tool_name, + "mcp.method.name": "tools/call", - # Set request metadata - span.set_data("mcp.request.id", "req_123abc") - span.set_data("mcp.session.id", "session_xyz789") - span.set_data("mcp.transport", "stdio") # or "http", "sse" for HTTP/WebSocket/SSE - span.set_data("network.transport", "pipe") # or "tcp" for HTTP/SSE + # Set request metadata + "mcp.request.id": "req_123abc", + "mcp.session.id": "session_xyz789", + "mcp.transport": "stdio", # or "http", "sse" for HTTP/WebSocket/SSE + "network.transport": "pipe", # or "tcp" for HTTP/SSE + }) # Set tool arguments (keep in mind this might contain PII data, so only set if that's ok) for key, value in tool_arguments.items(): - span.set_data(f"mcp.request.argument.{key}", value) + span.set_attribute(f"mcp.request.argument.{key}", value) # Execute the tool try: result = execute_tool(tool_name, tool_arguments) # Set result data - span.set_data("mcp.tool.result.content", json.dumps(result)) - span.set_data("mcp.tool.result.is_error", False) + span.set_attribute("mcp.tool.result.content", json.dumps(result)) + span.set_attribute("mcp.tool.result.is_error", False) # Set result content count if applicable if isinstance(result, (list, dict)): - span.set_data("mcp.tool.result.content_count", len(result)) + span.set_attribute("mcp.tool.result.content_count", len(result)) except Exception as e: - span.set_data("mcp.tool.result.is_error", True) + span.set_attribute("mcp.tool.result.is_error", True) raise ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk import json @@ -89,39 +90,37 @@ sentry_sdk.init(...) tool_name = "get_weather" tool_arguments = {"city": "San Francisco"} -with sentry_sdk.traces.start_span( +with sentry_sdk.start_span( + op="mcp.server", name=f"tools/call {tool_name}", - attributes={"sentry.op": "mcp.server"}, ) as span: # Set MCP-specific attributes - span.set_attributes({ - "mcp.tool.name": tool_name, - "mcp.method.name": "tools/call", + span.set_data("mcp.tool.name", tool_name) + span.set_data("mcp.method.name", "tools/call") - # Set request metadata - "mcp.request.id": "req_123abc", - "mcp.session.id": "session_xyz789", - "mcp.transport": "stdio", # or "http", "sse" for HTTP/WebSocket/SSE - "network.transport": "pipe", # or "tcp" for HTTP/SSE - }) + # Set request metadata + span.set_data("mcp.request.id", "req_123abc") + span.set_data("mcp.session.id", "session_xyz789") + span.set_data("mcp.transport", "stdio") # or "http", "sse" for HTTP/WebSocket/SSE + span.set_data("network.transport", "pipe") # or "tcp" for HTTP/SSE # Set tool arguments (keep in mind this might contain PII data, so only set if that's ok) for key, value in tool_arguments.items(): - span.set_attribute(f"mcp.request.argument.{key}", value) + span.set_data(f"mcp.request.argument.{key}", value) # Execute the tool try: result = execute_tool(tool_name, tool_arguments) # Set result data - span.set_attribute("mcp.tool.result.content", json.dumps(result)) - span.set_attribute("mcp.tool.result.is_error", False) + span.set_data("mcp.tool.result.content", json.dumps(result)) + span.set_data("mcp.tool.result.is_error", False) # Set result content count if applicable if isinstance(result, (list, dict)): - span.set_attribute("mcp.tool.result.content_count", len(result)) + span.set_data("mcp.tool.result.content_count", len(result)) except Exception as e: - span.set_attribute("mcp.tool.result.is_error", True) + span.set_data("mcp.tool.result.is_error", True) raise ``` @@ -131,7 +130,7 @@ with sentry_sdk.traces.start_span( #### Example Prompt Retrieval Span: -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk import json @@ -142,41 +141,43 @@ prompt_name = "code_review" prompt_arguments = {"language": "python"} with sentry_sdk.start_span( - op="mcp.server", name=f"prompts/get {prompt_name}", + attributes={"sentry.op": "mcp.server"}, ) as span: # Set MCP-specific attributes - span.set_data("mcp.prompt.name", prompt_name) - span.set_data("mcp.method.name", "prompts/get") + span.set_attributes({ + "mcp.prompt.name": prompt_name, + "mcp.method.name": "prompts/get", - # Set request metadata - span.set_data("mcp.request.id", "req_456def") - span.set_data("mcp.session.id", "session_xyz789") - span.set_data("mcp.transport", "http") - span.set_data("network.transport", "tcp") + # Set request metadata + "mcp.request.id": "req_456def", + "mcp.session.id": "session_xyz789", + "mcp.transport": "http", + "network.transport": "tcp", + }) # Set prompt arguments (keep in mind this might contain PII data, so only set if that's ok) for key, value in prompt_arguments.items(): - span.set_data(f"mcp.request.argument.{key}", value) + span.set_attribute(f"mcp.request.argument.{key}", value) # Retrieve the prompt prompt_result = get_prompt(prompt_name, prompt_arguments) # Set result data messages = prompt_result.get("messages", []) - span.set_data("mcp.prompt.result.message_count", len(messages)) + span.set_attribute("mcp.prompt.result.message_count", len(messages)) # For single-message prompts, set role and content if len(messages) == 1: - span.set_data("mcp.prompt.result.message_role", messages[0].get("role")) + span.set_attribute("mcp.prompt.result.message_role", messages[0].get("role")) # Note that content might contain PII data - span.set_data( + span.set_attribute( "mcp.prompt.result.message_content", json.dumps(messages[0].get("content")) ) ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk import json @@ -186,38 +187,36 @@ sentry_sdk.init(...) prompt_name = "code_review" prompt_arguments = {"language": "python"} -with sentry_sdk.traces.start_span( +with sentry_sdk.start_span( + op="mcp.server", name=f"prompts/get {prompt_name}", - attributes={"sentry.op": "mcp.server"}, ) as span: # Set MCP-specific attributes - span.set_attributes({ - "mcp.prompt.name": prompt_name, - "mcp.method.name": "prompts/get", + span.set_data("mcp.prompt.name", prompt_name) + span.set_data("mcp.method.name", "prompts/get") - # Set request metadata - "mcp.request.id": "req_456def", - "mcp.session.id": "session_xyz789", - "mcp.transport": "http", - "network.transport": "tcp", - }) + # Set request metadata + span.set_data("mcp.request.id", "req_456def") + span.set_data("mcp.session.id", "session_xyz789") + span.set_data("mcp.transport", "http") + span.set_data("network.transport", "tcp") # Set prompt arguments (keep in mind this might contain PII data, so only set if that's ok) for key, value in prompt_arguments.items(): - span.set_attribute(f"mcp.request.argument.{key}", value) + span.set_data(f"mcp.request.argument.{key}", value) # Retrieve the prompt prompt_result = get_prompt(prompt_name, prompt_arguments) # Set result data messages = prompt_result.get("messages", []) - span.set_attribute("mcp.prompt.result.message_count", len(messages)) + span.set_data("mcp.prompt.result.message_count", len(messages)) # For single-message prompts, set role and content if len(messages) == 1: - span.set_attribute("mcp.prompt.result.message_role", messages[0].get("role")) + span.set_data("mcp.prompt.result.message_role", messages[0].get("role")) # Note that content might contain PII data - span.set_attribute( + span.set_data( "mcp.prompt.result.message_content", json.dumps(messages[0].get("content")) ) @@ -229,7 +228,7 @@ with sentry_sdk.traces.start_span( #### Example Resource Read Span: -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk sentry_sdk.init(...) @@ -238,24 +237,26 @@ sentry_sdk.init(...) resource_uri = "file:///path/to/resource.txt" with sentry_sdk.start_span( - op="mcp.server", name=f"resources/read {resource_uri}", + attributes={"sentry.op": "mcp.server"}, ) as span: # Set MCP-specific attributes - span.set_data("mcp.resource.uri", resource_uri) - span.set_data("mcp.method.name", "resources/read") + span.set_attributes({ + "mcp.resource.uri": resource_uri, + "mcp.method.name": "resources/read", - # Set request metadata - span.set_data("mcp.request.id", "req_789ghi") - span.set_data("mcp.session.id", "session_xyz789") - span.set_data("mcp.transport", "http") - span.set_data("network.transport", "tcp") + # Set request metadata + "mcp.request.id": "req_789ghi", + "mcp.session.id": "session_xyz789", + "mcp.transport": "http", + "network.transport": "tcp", + }) # Access the resource resource_data = read_resource(resource_uri) ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk sentry_sdk.init(...) @@ -263,21 +264,19 @@ sentry_sdk.init(...) # Example resource access resource_uri = "file:///path/to/resource.txt" -with sentry_sdk.traces.start_span( +with sentry_sdk.start_span( + op="mcp.server", name=f"resources/read {resource_uri}", - attributes={"sentry.op": "mcp.server"}, ) as span: # Set MCP-specific attributes - span.set_attributes({ - "mcp.resource.uri": resource_uri, - "mcp.method.name": "resources/read", + span.set_data("mcp.resource.uri", resource_uri) + span.set_data("mcp.method.name", "resources/read") - # Set request metadata - "mcp.request.id": "req_789ghi", - "mcp.session.id": "session_xyz789", - "mcp.transport": "http", - "network.transport": "tcp", - }) + # Set request metadata + span.set_data("mcp.request.id", "req_789ghi") + span.set_data("mcp.session.id", "session_xyz789") + span.set_data("mcp.transport", "http") + span.set_data("network.transport", "tcp") # Access the resource resource_data = read_resource(resource_uri) diff --git a/docs/platforms/python/tracing/instrumentation/custom-instrumentation/queues-module.mdx b/docs/platforms/python/tracing/instrumentation/custom-instrumentation/queues-module.mdx index 3b5c0b451a11f..fa9b321acdd97 100644 --- a/docs/platforms/python/tracing/instrumentation/custom-instrumentation/queues-module.mdx +++ b/docs/platforms/python/tracing/instrumentation/custom-instrumentation/queues-module.mdx @@ -6,11 +6,11 @@ description: "Learn how to manually instrument your code to use Sentry's Queues Sentry comes with a [queue-monitoring dashboard](https://sentry.io/orgredirect/organizations/:orgslug/dashboards/) that can be auto-instrumented for popular Python queue setups (like Celery). -In case yours isn't supported, you can still instrument custom spans and transactions around your queue producers and consumers to ensure that you have performance data about your messaging queues. +In case yours isn't supported, you can still instrument custom spans around your queue producers and consumers to ensure that you have performance data about your messaging queues. -This page covers both transaction mode (default) and stream mode. See Streamed Spans to learn more. +The examples on this page are for SDK `3.x`. The **SDK 2.x** tabs show the equivalent code for the default transaction mode of SDK `2.x`. If you use stream mode in SDK `2.x`, follow the **SDK 3.x** examples, but call the tracing functions on `sentry_sdk.traces` (for example, `sentry_sdk.traces.start_span()`) and set `trace_lifecycle="stream"` in `sentry_sdk.init()`. @@ -24,13 +24,13 @@ To start capturing performance metrics, use the `start_span()` function to wrap | `messaging.destination.name` | string | The queue or topic name | | `messaging.message.body.size` | int | Size of the message body in bytes | -In transaction mode, your `queue.publish` span must exist inside a transaction in order to be recognized as a producer span. If you are using a supported web framework, the transaction is created by the integration. If you use plain Python, you can start a new one using `sentry_sdk.start_transaction()`. +If your `queue.publish` span has no parent, it's automatically promoted to a service span. If you'd rather group it under an explicit service span, start one with `sentry_sdk.start_span(parent_span=None)` first. -In stream mode, there's no separate transaction to depend on. If your `queue.process` span has no parent, it's automatically promoted to a service span. If you'd rather group it under an explicit service span, start one with `sentry_sdk.traces.start_span(parent_span=None)` first. +In SDK `2.x`, your `queue.publish` span must exist inside a transaction in order to be recognized as a producer span. If you are using a supported web framework, the transaction is created by the integration. If you use plain Python, you can start a new one using `sentry_sdk.start_transaction()`. You must also include trace headers (`sentry-trace` and `baggage`) in your message so that your consumers can continue your trace once your message is picked up. -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} from datetime import datetime, timezone import sentry_sdk @@ -46,22 +46,25 @@ queue = "messages" message = "Hello World!" message_id = "abc123" -# Create transaction +# Create the service span # If you are using a web framework, the framework integration # will create this for you and you can omit this. -with sentry_sdk.start_transaction( - op="function", +with sentry_sdk.start_span( name="queue_producer_transaction", + attributes={"sentry.op": "function"}, + parent_span=None, ): # Create the span with sentry_sdk.start_span( - op="queue.publish", name="queue_producer", + attributes={"sentry.op": "queue.publish"}, ) as span: # Set span data - span.set_data("messaging.message.id", message_id) - span.set_data("messaging.destination.name", queue) - span.set_data("messaging.message.body.size", len(message.encode("utf-8"))) + span.set_attributes({ + "messaging.message.id": message_id, + "messaging.destination.name": queue, + "messaging.message.body.size": len(message.encode("utf-8")), + }) # Publish the message to the queue (including trace information and current time stamp) now = int(datetime.now(timezone.utc).timestamp()) @@ -76,7 +79,7 @@ with sentry_sdk.start_transaction( ) ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} from datetime import datetime, timezone import sentry_sdk @@ -92,25 +95,22 @@ queue = "messages" message = "Hello World!" message_id = "abc123" -# Create the service span +# Create transaction # If you are using a web framework, the framework integration # will create this for you and you can omit this. -with sentry_sdk.traces.start_span( +with sentry_sdk.start_transaction( + op="function", name="queue_producer_transaction", - attributes={"sentry.op": "function"}, - parent_span=None, ): # Create the span - with sentry_sdk.traces.start_span( + with sentry_sdk.start_span( + op="queue.publish", name="queue_producer", - attributes={"sentry.op": "queue.publish"}, ) as span: # Set span data - span.set_attributes({ - "messaging.message.id": message_id, - "messaging.destination.name": queue, - "messaging.message.body.size": len(message.encode("utf-8")), - }) + span.set_data("messaging.message.id", message_id) + span.set_data("messaging.destination.name", queue) + span.set_data("messaging.message.body.size", len(message.encode("utf-8"))) # Publish the message to the queue (including trace information and current time stamp) now = int(datetime.now(timezone.utc).timestamp()) @@ -137,13 +137,13 @@ To start capturing performance metrics, use the `start_span()` function to wrap | `messaging.message.retry.count ` | number | The number of times a message was attempted to be processed | | `messaging.message.receive.latency ` | number | The time in milliseconds that a message awaited processing in queue | -In transaction mode, your `queue.process` span must exist inside a transaction in order to be recognized as a consumer span. If you are using a supported web framework, the transaction is created by the integration. If you use plain Python, you can start a new one using `sentry_sdk.start_transaction()`. +If your `queue.process` span has no parent, it's automatically promoted to a service span. If you'd rather group it under an explicit service span, start one with `sentry_sdk.start_span(parent_span=None)` first. -In stream mode, there's no separate transaction to depend on. If your `queue.process` span has no parent, it's automatically promoted to a service span. If you'd rather group it under an explicit service span, start one with `sentry_sdk.traces.start_span(parent_span=None)` first. +In SDK `2.x`, your `queue.process` span must exist inside a transaction in order to be recognized as a consumer span. If you are using a supported web framework, the transaction is created by the integration. If you use plain Python, you can start a new one using `sentry_sdk.start_transaction()`. -Use `continue_trace()` to connect your consumer spans to their associated producer spans. To mark the trace of your message as success or failed, use `transaction.set_status()` in transaction mode, or set `span.status = "ok"/"error"` directly on the service span in stream mode. +Use `continue_trace()` to connect your consumer spans to their associated producer spans. To mark the trace of your message as success or failed, set `span.status = "ok"/"error"` directly on the service span. In SDK `2.x`, use `transaction.set_status()` instead. -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} from datetime import datetime, timezone import sentry_sdk @@ -166,33 +166,35 @@ latency = now - message_time # Continue the trace started in the producer # If you are using a web framework, the framework integration # will create this for you and you can omit this. -transaction = sentry_sdk.continue_trace( - message["headers"], - op="function", +sentry_sdk.continue_trace(message["headers"]) +with sentry_sdk.start_span( name="queue_consumer_transaction", -) -with sentry_sdk.start_transaction(transaction): + attributes={"sentry.op": "function"}, + parent_span=None, +) as service_span: # Create the span with sentry_sdk.start_span( - op="queue.process", name="queue_consumer", + attributes={"sentry.op": "queue.process"}, ) as span: # Set span data - span.set_data("messaging.message.id", message["message_id"]) - span.set_data("messaging.destination.name", queue) - span.set_data("messaging.message.body.size", len(message["body"].encode("utf-8"))) - span.set_data("messaging.message.receive.latency", latency.total_seconds() * 1000) - span.set_data("messaging.message.retry.count", 0) + span.set_attributes({ + "messaging.message.id": message["message_id"], + "messaging.destination.name": queue, + "messaging.message.body.size": len(message["body"].encode("utf-8")), + "messaging.message.receive.latency": latency.total_seconds() * 1000, + "messaging.message.retry.count": 0, + }) try: # Process the message process_message(message) except Exception: - # In case of an error set the status to "internal_error" - transaction.set_status("internal_error") + # In case of an error set the status to "error" + service_span.status = "error" ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} from datetime import datetime, timezone import sentry_sdk @@ -215,30 +217,28 @@ latency = now - message_time # Continue the trace started in the producer # If you are using a web framework, the framework integration # will create this for you and you can omit this. -sentry_sdk.traces.continue_trace(message["headers"]) -with sentry_sdk.traces.start_span( +transaction = sentry_sdk.continue_trace( + message["headers"], + op="function", name="queue_consumer_transaction", - attributes={"sentry.op": "function"}, - parent_span=None, -) as service_span: +) +with sentry_sdk.start_transaction(transaction): # Create the span - with sentry_sdk.traces.start_span( + with sentry_sdk.start_span( + op="queue.process", name="queue_consumer", - attributes={"sentry.op": "queue.process"}, ) as span: # Set span data - span.set_attributes({ - "messaging.message.id": message["message_id"], - "messaging.destination.name": queue, - "messaging.message.body.size": len(message["body"].encode("utf-8")), - "messaging.message.receive.latency": latency.total_seconds() * 1000, - "messaging.message.retry.count": 0, - }) + span.set_data("messaging.message.id", message["message_id"]) + span.set_data("messaging.destination.name", queue) + span.set_data("messaging.message.body.size", len(message["body"].encode("utf-8"))) + span.set_data("messaging.message.receive.latency", latency.total_seconds() * 1000) + span.set_data("messaging.message.retry.count", 0) try: # Process the message process_message(message) except Exception: - # In case of an error set the status to "error" - service_span.status = "error" + # In case of an error set the status to "internal_error" + transaction.set_status("internal_error") ``` diff --git a/docs/platforms/python/tracing/span-lifecycle/index.mdx b/docs/platforms/python/tracing/span-lifecycle/index.mdx index e411af0b193ea..776fb6ca242d3 100644 --- a/docs/platforms/python/tracing/span-lifecycle/index.mdx +++ b/docs/platforms/python/tracing/span-lifecycle/index.mdx @@ -6,7 +6,7 @@ sidebar_order: 10 -To capture transactions and spans customized to your organization's needs, you must first set up tracing. +To capture spans customized to your organization's needs, you must first set up tracing. @@ -14,7 +14,7 @@ To add custom performance data to your application, you need to add custom instr -This page covers both transaction mode (default) and stream mode. See Streamed Spans to learn more. +The examples on this page are for SDK `3.x`. The **SDK 2.x** tabs show the equivalent code for the default transaction mode of SDK `2.x`. If you use stream mode in SDK `2.x`, follow the **SDK 3.x** examples, but call the tracing functions on `sentry_sdk.traces` (for example, `sentry_sdk.traces.start_span()`) and set `trace_lifecycle="stream"` in `sentry_sdk.init()`. @@ -24,11 +24,14 @@ This page covers both transaction mode (default) and stream mode. See - `op` is not a dedicated argument in stream mode. Set it as the `sentry.op` + `op` is not a dedicated argument in SDK `3.x`. Set it as the `sentry.op` attribute instead. +### SDK 2.x + +| Option | Type | Description | +| ----------------- | ---------------- | --------------------------- | +| `op` | `string` | The operation of the span. | +| `name` | `string` | The name of the span. | +| `start_timestamp` | `datetime/float` | The start time of the span. | + ## Using the Context Manager For most scenarios, we recommend using the context manager approach. This creates a new span that automatically starts when entering the context and ends when exiting it. -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk -with sentry_sdk.start_span(op="db", name="Query Users") as span: +with sentry_sdk.start_span( + name="Query Users", + attributes={"sentry.op": "db"}, +) as span: # Perform a database query users = db.query("SELECT * FROM users") - # You can set data on the span - span.set_data("user_count", len(users)) + # You can set attributes on the span + span.set_attribute("user_count", len(users)) ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk -with sentry_sdk.traces.start_span( - name="Query Users", - attributes={"sentry.op": "db"}, -) as span: +with sentry_sdk.start_span(op="db", name="Query Users") as span: # Perform a database query users = db.query("SELECT * FROM users") - # You can set attributes on the span - span.set_attribute("user_count", len(users)) + # You can set data on the span + span.set_data("user_count", len(users)) ``` The context manager also correctly handles exceptions, marking the span as failed if an exception occurs: -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk try: - with sentry_sdk.start_span(op="http", name="Call External API"): + with sentry_sdk.start_span( + name="Call External API", + attributes={"sentry.op": "http"}, + ): # If this raises an exception, the span will be marked as failed response = requests.get("https://api.example.com/data") response.raise_for_status() @@ -166,14 +169,11 @@ except Exception: pass ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk try: - with sentry_sdk.traces.start_span( - name="Call External API", - attributes={"sentry.op": "http"}, - ): + with sentry_sdk.start_span(op="http", name="Call External API"): # If this raises an exception, the span will be marked as failed response = requests.get("https://api.example.com/data") response.raise_for_status() @@ -186,63 +186,65 @@ except Exception: You can access the currently active span: -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk # Get the current active span current_span = sentry_sdk.get_current_span() if current_span: - current_span.set_data("key", "value") + current_span.set_attribute("key", "value") ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk # Get the current active span -current_span = sentry_sdk.traces.get_current_span() +current_span = sentry_sdk.get_current_span() if current_span: - current_span.set_attribute("key", "value") + current_span.set_data("key", "value") ``` -## Working with Transactions - -`start_transaction` is only available in transaction mode. +## Working with Service Spans -[Transactions](/product/dashboards/sentry-dashboards/transaction-summary/#what-is-a-transaction) are a special type of span that represent a complete operation in your application, such as a web request. You can create transactions explicitly: +A service span (the equivalent of a transaction in SDK `2.x`) is just a span started with no parent in the current application. Pass `parent_span=None` to force this, even if a span is currently active: ```python import sentry_sdk -with sentry_sdk.start_transaction(name="Background Task", op="task") as transaction: +with sentry_sdk.start_span( + name="Background Task", + attributes={"sentry.op": "task"}, + parent_span=None, +) as service_span: # Your code here - # You can add child spans to the transaction - with sentry_sdk.start_span(op="subtask", name="Data Processing"): + # You can add child spans to the service span + with sentry_sdk.start_span( + name="Data Processing", + attributes={"sentry.op": "subtask"}, + ): # Process data pass ``` -## Working with Service Spans +## Working with Transactions -Service spans are only available in stream mode. + -In stream mode, a service span (the equivalent of a transaction) is just a span started with no parent in the current application. Pass `parent_span=None` to force this, even if a span is currently active: +Only available in SDK versions prior to `3.0`. Use a [service span](#working-with-service-spans) instead. + + + +[Transactions](/product/dashboards/sentry-dashboards/transaction-summary/#what-is-a-transaction) are a special type of span that represent a complete operation in your application, such as a web request. You can create transactions explicitly: ```python import sentry_sdk -with sentry_sdk.traces.start_span( - name="Background Task", - attributes={"sentry.op": "task"}, - parent_span=None, -) as service_span: +with sentry_sdk.start_transaction(name="Background Task", op="task") as transaction: # Your code here - # You can add child spans to the service span - with sentry_sdk.traces.start_span( - name="Data Processing", - attributes={"sentry.op": "subtask"}, - ): + # You can add child spans to the transaction + with sentry_sdk.start_span(op="subtask", name="Data Processing"): # Process data pass ``` @@ -253,53 +255,53 @@ with sentry_sdk.traces.start_span( Span attributes customize information you can get through tracing. This information can be found in the traces views in Sentry, once you drill into a span. You can capture additional context with span attributes. These can be key-value pairs of various Python types. -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk -with sentry_sdk.start_span(op="db", name="Query Users") as span: +with sentry_sdk.start_span( + name="Query Users", + attributes={"sentry.op": "db"}, +) as span: # Execute the query users = db.query("SELECT * FROM users WHERE active = true") - # You can add more data during execution - span.set_data("result_count", len(users)) + # You can add more attributes during execution + span.set_attribute("result_count", len(users)) ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk -with sentry_sdk.traces.start_span( - name="Query Users", - attributes={"sentry.op": "db"}, -) as span: +with sentry_sdk.start_span(op="db", name="Query Users") as span: # Execute the query users = db.query("SELECT * FROM users WHERE active = true") - # You can add more attributes during execution - span.set_attribute("result_count", len(users)) + # You can add more data during execution + span.set_data("result_count", len(users)) ``` You can also add attributes to an existing span: -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk # Get the current span span = sentry_sdk.get_current_span() if span: - # Set individual data points - span.set_data("user_id", user.id) - span.set_data("request_size", len(request.body)) + # Set individual attributes + span.set_attribute("user_id", user.id) + span.set_attribute("request_size", len(request.body)) ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk # Get the current span -span = sentry_sdk.traces.get_current_span() +span = sentry_sdk.get_current_span() if span: - # Set individual attributes - span.set_attribute("user_id", user.id) - span.set_attribute("request_size", len(request.body)) + # Set individual data points + span.set_data("user_id", user.id) + span.set_data("request_size", len(request.body)) ``` ### Adding Attributes to All Spans @@ -314,51 +316,51 @@ Spans can have an operation associated with them, which helps Sentry understand Sentry maintains a [list of well-known span operations](https://develop.sentry.dev/sdk/performance/span-operations/#list-of-operations) that you should use when applicable: -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk # HTTP client operation -with sentry_sdk.start_span(op="http.client", name="Fetch User Data"): +with sentry_sdk.start_span( + name="Fetch User Data", + attributes={"sentry.op": "http.client"}, +): response = requests.get("https://api.example.com/users") # Database operation -with sentry_sdk.start_span(op="db", name="Save User"): +with sentry_sdk.start_span( + name="Save User", + attributes={"sentry.op": "db"}, +): db.execute( "INSERT INTO users (name, email) VALUES (%s, %s)", (user.name, user.email), ) # File I/O operation -with sentry_sdk.start_span(op="file.read", name="Read Config"): +with sentry_sdk.start_span( + name="Read Config", + attributes={"sentry.op": "file.read"}, +): with open("config.json", "r") as f: config = json.load(f) ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk # HTTP client operation -with sentry_sdk.traces.start_span( - name="Fetch User Data", - attributes={"sentry.op": "http.client"}, -): +with sentry_sdk.start_span(op="http.client", name="Fetch User Data"): response = requests.get("https://api.example.com/users") # Database operation -with sentry_sdk.traces.start_span( - name="Save User", - attributes={"sentry.op": "db"}, -): +with sentry_sdk.start_span(op="db", name="Save User"): db.execute( "INSERT INTO users (name, email) VALUES (%s, %s)", (user.name, user.email), ) # File I/O operation -with sentry_sdk.traces.start_span( - name="Read Config", - attributes={"sentry.op": "file.read"}, -): +with sentry_sdk.start_span(op="file.read", name="Read Config"): with open("config.json", "r") as f: config = json.load(f) ``` @@ -366,42 +368,42 @@ with sentry_sdk.traces.start_span( ### Updating the Span Status You can update the status of a span to indicate whether it succeeded or failed. -In stream mode, status can only be `ok` (default) or `error`. +In SDK `3.x`, status can only be `ok` (default) or `error`. -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk -with sentry_sdk.start_span(op="task", name="Process Payment") as span: +with sentry_sdk.start_span( + name="Process Payment", + attributes={"sentry.op": "task"}, +) as span: try: result = process_payment(payment_id) if result.success: - # Mark the span as successful - span.set_status("ok") + # Mark the span as successful (this is also the default) + span.status = "ok" else: # Mark the span as failed - span.set_status("error") - span.set_data("error_reason", result.error) + span.status = "error" + span.set_attribute("error_reason", result.error) except Exception: # Span will automatically be marked as failed when an exception occurs raise ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk -with sentry_sdk.traces.start_span( - name="Process Payment", - attributes={"sentry.op": "task"}, -) as span: +with sentry_sdk.start_span(op="task", name="Process Payment") as span: try: result = process_payment(payment_id) if result.success: - # Mark the span as successful (this is also the default) - span.status = "ok" + # Mark the span as successful + span.set_status("ok") else: # Mark the span as failed - span.status = "error" - span.set_attribute("error_reason", result.error) + span.set_status("error") + span.set_data("error_reason", result.error) except Exception: # Span will automatically be marked as failed when an exception occurs raise diff --git a/docs/platforms/react-native/common/manual-setup/manual-setup.mdx b/docs/platforms/react-native/common/manual-setup/manual-setup.mdx index b3ea6b06f2774..07af131d64604 100644 --- a/docs/platforms/react-native/common/manual-setup/manual-setup.mdx +++ b/docs/platforms/react-native/common/manual-setup/manual-setup.mdx @@ -26,6 +26,8 @@ pnpm add @sentry/react-native For iOS, the Sentry SDK wraps the React Native bundle process to upload source maps automatically. The SDK also adds a new Xcode Build Phase to upload debug symbols to ensure you get readable stack traces for your native crashes. +These steps are the same for CocoaPods and [Swift Package Manager](/platforms/react-native/manual-setup/swift-package-manager/) projects. + ### Add Privacy Manifest The SDK needs access to certain information about the device and the application for its essential functionality. Some of the APIs required for this are considered privacy-relevant. Add the privacy manifest to your Xcode project to ensure your app is compliant with Apple's guidelines. Read the [Apple Privacy Manifest](/platforms/react-native/data-management/apple-privacy-manifest/) guide for more info on how to add records required for the Sentry SDKs. diff --git a/docs/platforms/react-native/common/manual-setup/swift-package-manager.mdx b/docs/platforms/react-native/common/manual-setup/swift-package-manager.mdx new file mode 100644 index 0000000000000..b8fbcae73180c --- /dev/null +++ b/docs/platforms/react-native/common/manual-setup/swift-package-manager.mdx @@ -0,0 +1,60 @@ +--- +title: Swift Package Manager +description: "Learn how to use the Sentry React Native SDK in an iOS project that links native dependencies with Swift Package Manager instead of CocoaPods." +sidebar_order: 5 +--- + +React Native 0.87 added an opt-in preview that links iOS native dependencies with Swift Package Manager (SwiftPM) instead of CocoaPods. The Sentry React Native SDK ships a `Package.swift`, so React Native links it like any other SwiftPM dependency. + +CocoaPods is still the default. If your project uses CocoaPods, you don't need to change anything. + +## Requirements + +- React Native 0.87 or newer +- `@sentry/react-native` 8.29.0 or newer +- An iOS app. macOS, tvOS, and visionOS apps keep building with CocoaPods. + +## Switch an Existing Project to SwiftPM + +We recommend that you set up Sentry first and switch to SwiftPM after that. The Sentry build phases that upload source maps and debug symbols stay in your Xcode project when React Native removes CocoaPods. + +1. Set up the SDK with the [wizard](/platforms/react-native/) or the [manual configuration](/platforms/react-native/manual-setup/manual-setup/). + +2. Switch the iOS project to SwiftPM: + + ```bash + cd ios + npx react-native spm add --deintegrate + ``` + + The `--deintegrate` flag runs `pod deintegrate` and removes the React Native lines from your `Podfile`. If your project never used CocoaPods, leave out the flag. + +3. Build the app with `npx react-native run-ios`, or open the `.xcodeproj` file in Xcode. SwiftPM projects don't have an `.xcworkspace` file. + +## Add Sentry to a SwiftPM Project + +If your project already uses SwiftPM, run the [wizard](/platforms/react-native/) as usual. If the wizard asks whether to run `pod install`, select **No, I'll do it later**. SwiftPM projects don't use CocoaPods. + +You can also follow the iOS steps in the [manual configuration](/platforms/react-native/manual-setup/manual-setup/#ios). The build phases are the same for CocoaPods and SwiftPM projects. + +## Expo + +If you use the Sentry Expo config plugin in a SwiftPM project, use `@sentry/react-native` 8.32.0 or newer. In older versions, the _Upload Debug Symbols to Sentry_ build phase can't find `ios/.xcode.env` in SwiftPM projects, so it can fail to find Node. + +## Troubleshooting + +### `Package.swift is missing for library "@sentry/react-native"` + +Your SDK version doesn't support SwiftPM. Upgrade `@sentry/react-native` to 8.29.0 or newer. + +### `Package.swift is missing` for Another Library + +Every autolinked library needs a `Package.swift`, and many community libraries don't ship one yet. This is a React Native requirement, not a Sentry one. React Native prints the steps to fix it. For example, `npx react-native spm scaffold` can generate a `Package.swift` for a library that has a podspec. + +### `Sentry.xcframework` Fails to Download + +When Xcode resolves the packages, SwiftPM downloads `Sentry.xcframework` from the [sentry-cocoa GitHub releases](https://github.com/getsentry/sentry-cocoa/releases). If your network blocks GitHub, allow access to it on the machine that builds the app. + +### Go Back to CocoaPods + +Run `npx react-native spm deinit` in the `ios` directory to remove what `spm add` added to your Xcode project. Then restore your `Podfile` from version control and run `pod install`. diff --git a/docs/platforms/react-native/guides/expo/index.mdx b/docs/platforms/react-native/guides/expo/index.mdx index 559425fa0c623..b53534bfc0901 100644 --- a/docs/platforms/react-native/guides/expo/index.mdx +++ b/docs/platforms/react-native/guides/expo/index.mdx @@ -194,7 +194,7 @@ To see Sentry issues and replays in the Expo dashboard, create an [EAS Update ch ### Build Notes -- Don't commit your auth token. Store it in `.env.local` as `SENTRY_AUTH_TOKEN` for local builds, and as an [EAS secret](https://docs.expo.dev/eas/environment-variables/) for EAS builds. +- Don't commit your auth token. Store it in `.env.local` as `SENTRY_AUTH_TOKEN` for local builds, and as an [EAS environment variable](https://docs.expo.dev/eas/environment-variables/manage/) for EAS builds. - Source maps for the `Release` version of your application are uploaded automatically during the native application build. - During development, the source code is resolved using the Metro Server and source maps aren't used. This currently doesn't work on web. diff --git a/docs/platforms/react-native/guides/expo/manual-setup/expo/eas-build-hooks.mdx b/docs/platforms/react-native/guides/expo/manual-setup/expo/eas-build-hooks.mdx index caf67a1121cb8..5ad34de23c70b 100644 --- a/docs/platforms/react-native/guides/expo/manual-setup/expo/eas-build-hooks.mdx +++ b/docs/platforms/react-native/guides/expo/manual-setup/expo/eas-build-hooks.mdx @@ -25,7 +25,7 @@ EAS Build automatically runs `package.json` scripts with these names at the corr Set your DSN as an EAS secret or environment variable so it's available during builds: ```bash -eas env:create --name SENTRY_DSN --value --visibility secret --scope project +eas env:set --name SENTRY_DSN --value --environment production --visibility secret --scope project ``` ## What Gets Captured diff --git a/docs/platforms/unity/configuration/event-debouncing/index.mdx b/docs/platforms/unity/configuration/event-debouncing/index.mdx index beab2938c5514..fa118cd7e28db 100644 --- a/docs/platforms/unity/configuration/event-debouncing/index.mdx +++ b/docs/platforms/unity/configuration/event-debouncing/index.mdx @@ -1,42 +1,96 @@ --- -title: Event Debouncing -description: "Learn how the SDK handles high frequencies of events." +title: Event Throttling +description: "Learn how to limit repeated errors, breadcrumbs, and logs from Unity's logging system." sidebar_order: 20 --- -Because gameplay updates at a very high frequency of 60 times a second or even higher, an optional debouncing mechanism is in place. Every type of log has its own time slot. If `EnableLogDebounce` is enabled and the game triggers too many events of the same type in quick succession, Sentry will only capture the first of its kind, then ignore (debounce) the other events of the same type. +A game can log the same error every frame. Throttling drops the repeats, so they don't use up your quota. -Event debouncing is `disabled` by default. +Throttling is off by default. -The time that needs to pass after an event has been triggered to be captured again: +## Configure Throttling in the Editor -- `LogType.Log` - one second -- `LogType.Warning` - one second -- `LogType.Error`, `LogType.Exception`, `LogType.Assert` and actual exceptions - one second +Open **Tools > Sentry > Logging** and turn on **Enable Error Event Throttling**. **Dedupe Window [ms]** sets how long the SDK waits before it captures the same error again. The default is `1000` milliseconds. +The built-in throttler handles errors from `Debug.LogError`, `Debug.LogException`, and, in the editor and development builds, `Debug.LogAssertion`. It treats two errors as the same when their message and stack trace match, and remembers the last 100 distinct errors. It doesn't throttle breadcrumbs or structured logs. + +## Configure Throttling in Code + +To throttle in code, implement `IThrottler` and set it as the [`Throttler`](/platforms/unity/configuration/options/#Throttler) option. A custom throttler can also throttle breadcrumbs and structured logs. If you set a throttler in code, the SDK uses it instead of the editor settings. + +This example drops any error, breadcrumb, or log that repeats within five seconds. The SDK can call the throttler from any thread, so make it thread-safe and don't call Unity APIs in it. ```csharp +using System; +using System.Collections.Generic; +using Sentry.Unity; using UnityEngine; -public class DebouncerTestMonoBehaviour : MonoBehaviour +public class RepeatThrottler : IThrottler { - void Start() + private static readonly TimeSpan Window = TimeSpan.FromSeconds(5); + private readonly Dictionary _lastSeen = new Dictionary(); + + public bool ShouldCaptureEvent(string message, string stackTrace, LogType logType) => + ShouldCapture("event:" + message + stackTrace); + + public bool ShouldCaptureException(Exception exception) => + ShouldCapture("exception:" + exception.GetType().FullName + exception.Message + exception.StackTrace); + + public bool ShouldCaptureBreadcrumb(string message, LogType logType) => + ShouldCapture("breadcrumb:" + message); + + public bool ShouldCaptureStructuredLog(string message, LogType logType) => + ShouldCapture("log:" + message); + + private bool ShouldCapture(string key) { - SentryUnity.Init(o => + lock (_lastSeen) { - o.Dsn = "___PUBLIC_DSN___"; - o.EnableLogDebouncing = true; - }); - - // The time between debug calls of the same type is less than 1s - // Every following call of the same type gets ignored until 1s has passed - - Debug.Log("Log"); // recorded - Debug.Log("Log 2"); // not recorded - Debug.LogWarning("Warning"); // recorded - Debug.LogWarning("Warning 2"); // not recorded - Debug.LogError("Error"); // recorded - Debug.LogError("Error 2"); // not recorded + var now = DateTime.UtcNow; + if (_lastSeen.TryGetValue(key, out var last) && now - last < Window) + { + return false; + } + + if (_lastSeen.Count >= 100) + { + // Forget entries whose window has passed. + var expired = new List(); + foreach (var entry in _lastSeen) + { + if (now - entry.Value >= Window) + { + expired.Add(entry.Key); + } + } + + foreach (var expiredKey in expired) + { + _lastSeen.Remove(expiredKey); + } + + if (_lastSeen.Count >= 100) + { + // Still full: capture without tracking. + return true; + } + } + + _lastSeen[key] = now; + return true; + } } } ``` + +Set it in your [options configuration script](/platforms/unity/configuration/options/programmatic-configuration/): + +```csharp +public override void Configure(SentryUnityOptions options) +{ + options.Throttler = new RepeatThrottler(); +} +``` + +`EnableLogDebouncing` and the `DebounceTime*` options are deprecated. Use `Throttler` instead. diff --git a/docs/platforms/unity/configuration/filtering.mdx b/docs/platforms/unity/configuration/filtering.mdx index 41c61d553738c..fa011738e01fa 100644 --- a/docs/platforms/unity/configuration/filtering.mdx +++ b/docs/platforms/unity/configuration/filtering.mdx @@ -12,19 +12,25 @@ We also offer [Inbound Filters](/concepts/data-management/filtering/) to filter ## Filtering Error Events -Configure your SDK to filter error events by using the callback method and configuring, enabling, or disabling integrations. +Configure your SDK to filter error events by using the callback method and configuring, enabling, or disabling integrations. -### Using +### Using -All Sentry SDKs support the callback method. Because it's called immediately before the event is sent to the server, this is your last chance to decide not to send data or to edit it. receives the event object as a parameter, which you can use to either modify the event’s data or drop it completely by returning `null`, based on custom logic and the data available on the event. +All Sentry SDKs support the callback method. Because it's called immediately before the event is sent to the server, this is your last chance to decide not to send data or to edit it. receives the event object as a parameter, which you can use to either modify the event’s data or drop it completely by returning `null`, based on custom logic and the data available on the event. + + +The callback runs in C# only. Native crashes are captured by the native SDKs and don't run it. + + + Note also that breadcrumbs can be filtered, as discussed in [our Breadcrumbs documentation](/product/issues/issue-details/breadcrumbs/). ## Filtering Transaction Events -To prevent certain transactions from being reported to Sentry, use the or configuration option, which allows you to provide a function to evaluate the current transaction and drop it if it's not one you want. +To prevent certain transactions from being reported to Sentry, use the or configuration option, which allows you to provide a function to evaluate the current transaction and drop it if it's not one you want. ### Using diff --git a/docs/platforms/unity/configuration/il2cpp/index.mdx b/docs/platforms/unity/configuration/il2cpp/index.mdx index 7a0b4a860e2ad..ac1676fc32ce5 100644 --- a/docs/platforms/unity/configuration/il2cpp/index.mdx +++ b/docs/platforms/unity/configuration/il2cpp/index.mdx @@ -4,23 +4,28 @@ description: "Learn how the SDK provides line numbers to issues from IL2CPP buil sidebar_order: 10 --- -Sentry can provide line numbers for thrown C# exceptions in **release and development builds** with IL2CPP on Unity `2020.3` or later. +Sentry can provide line numbers for thrown C# exceptions in IL2CPP builds on Unity 2021.3 or later. This works for release builds by default. For development builds, enable **Upload Dev Symbols** in the [debug symbol upload settings](/platforms/unity/configuration/options/cli-options/). Unity provides you the option to select [IL2CPP](https://docs.unity3d.com/Manual/IL2CPP.html) as your scripting backend. This leads to C++ code being generated from your compiled C# (IL) code, hence the name `IL to CPP`. The Sentry SDK provides line number support for IL2CPP builds for the following platforms: -- Windows (\*currently limited to Unity 2021.3 or newer) +- Windows - macOS - Linux - Android - iOS - Xbox +- PlayStation 5 + +WebGL and Nintendo Switch don't support line numbers for IL2CPP builds. When you build with IL2CPP, errors in your game will happen in the native code. Also, the mapping between your C# code and the generated C++ code is part of the build process and isn't shipped with your game. That means the event the Sentry SDK reports can only contain the native stack trace. To provide you with C# line numbers, the Sentry server needs to have access to that line mapping through [Debug Information Files](/platforms/unity/data-management/debug-files/). The support for line numbers in C# Exceptions with IL2CPP relies on the debug symbol upload. -With the automated debug symbol upload enabled, the [Sentry SDK will upload the line mapping automatically](/platforms/unity/native-support/#debug-symbols). +With the automated debug symbol upload enabled, the [Sentry SDK uploads the line mapping automatically](/platforms/unity/native-support/#debug-symbols). + +To create the line mapping, the SDK adds `--emit-source-mapping` to **Player Settings > Additional IL2CPP Arguments** before each IL2CPP build. On Unity 6.5 and later, it also adds `--link-symbols` to the UnityLinker arguments. If you turn the feature off, the SDK removes these arguments on the next build. This feature adds C# source lines to the stack trace of a thrown exception. To do this, the SDK reads native stack frames from the exception and Sentry uses the uploaded line mapping to find the matching C# source. diff --git a/docs/platforms/unity/configuration/options/cli-options/img/sentry-cli-option-configuration.png b/docs/platforms/unity/configuration/options/cli-options/img/sentry-cli-option-configuration.png index 827f4a98ca900..dadfba2f5743a 100644 Binary files a/docs/platforms/unity/configuration/options/cli-options/img/sentry-cli-option-configuration.png and b/docs/platforms/unity/configuration/options/cli-options/img/sentry-cli-option-configuration.png differ diff --git a/docs/platforms/unity/configuration/options/cli-options/index.mdx b/docs/platforms/unity/configuration/options/cli-options/index.mdx index 3e242744a3668..7e1972017c5a2 100644 --- a/docs/platforms/unity/configuration/options/cli-options/index.mdx +++ b/docs/platforms/unity/configuration/options/cli-options/index.mdx @@ -5,62 +5,94 @@ sidebar_order: 30 og_image: /og-images/platforms-unity-configuration-options-cli-options.png --- -The Unity SDK includes [Sentry CLI](/cli/) as a tool to upload debug symbols to Sentry. These debug symbols are used in processing events sent to Sentry to provide stacktraces and linenumbers. This page describes the options available to configure the Sentry CLI. +The Unity SDK includes [Sentry CLI](/cli/) as a tool to upload debug symbols to Sentry. Sentry uses these debug symbols to provide stack traces and line numbers for your events. This page describes the options available to configure Sentry CLI. You can set them in **Tools > Sentry**, on the **Debug Symbols** tab. ## Programmatic Configuration -Similar to the [programmatic configuration](/platforms/unity/configuration/options/programmatic-configuration/) of the SDK itself, the debug symbol upload via Sentry CLI also supports programmatic configuration. +Similar to the [programmatic configuration](/platforms/unity/configuration/options/programmatic-configuration/) of the SDK itself, the debug symbol upload with Sentry CLI also supports programmatic configuration. Create a class that inherits from `SentryCliOptionsConfiguration` and assign it to the **CLI Config Script** field on the **Debug Symbols** tab. ![Options Configuration](./img/sentry-cli-option-configuration.png) -The `Configure` callback gets invoked during the build process and allows you to modify the options used by Sentry CLI. +The SDK calls `Configure` during the build and passes it the options used by Sentry CLI, so you can change them. + +The SDK doesn't read environment variables such as `SENTRY_AUTH_TOKEN` itself. To pass credentials from your CI system, read them in `Configure`: + +```csharp +using System; +using Sentry.Unity; +using UnityEngine; + +public class SentryCliConfiguration : SentryCliOptionsConfiguration +{ + public override void Configure(SentryCliOptions cliOptions) + { + // Only set secrets for CI builds + if (!Application.isBatchMode) + { + return; + } + + var authToken = Environment.GetEnvironmentVariable("SENTRY_AUTH_TOKEN"); + if (!string.IsNullOrEmpty(authToken)) + { + cliOptions.Auth = authToken; + } + } +} +``` + +In CI, store the auth token as a secret and expose it to the Unity build as the `SENTRY_AUTH_TOKEN` environment variable. You can set `Organization` and `Project` the same way. + +The SDK runs `Configure` on a copy of the options, so values you set there aren't saved to `SentryCliOptions.asset`. + +Exported Xcode and Gradle projects contain the auth token in plain text. See the [warning about `sentry.properties`](/platforms/unity/native-support/#debug-symbols). ## Sentry CLI Options - + -Whether the SDK should automatically upload debug symbols to Sentry. This requires a valid auth token, organization, and project. +Whether the SDK should automatically upload debug symbols to Sentry. This requires a valid auth token and project, and the organization slug unless the auth token is an organization token. - + -Whether the SDK should automatically upload debug symbols to Sentry for development builds. +Whether the SDK should automatically upload debug symbols to Sentry for development builds. In the editor, this is **Upload Dev Symbols**. - + -Whether the SDK should automatically upload sources to Sentry; this enables Sentry to provide source-context on events. +Whether the SDK should automatically upload your source code to Sentry, so Sentry can show [source context](/platforms/unity/data-management/debug-files/source-context/) on events. When enabled, the SDK passes `--include-sources` to Sentry CLI. - + -This option allows you to override the default Sentry URL in case you are using a self-hosted Sentry instance or a custom domain. +The URL of your Sentry instance. Set this only if you use a self-hosted Sentry instance or a custom domain. If you don't set it and your DSN's host isn't `sentry.io` or one of its subdomains, the SDK uses the DSN's host. The **Debug Symbols** tab has no field for this option, so set it in [code](#programmatic-configuration). - + -The auth token to use when uploading symbols to Sentry. +The auth token to use when uploading symbols to Sentry. In the editor, this is **Auth Token**. - + -The organization to use when uploading symbols to Sentry. +The organization slug to use when uploading symbols to Sentry. It's required unless the auth token is an organization token. In the editor, this is **Org Slug**. - + -The project to use when uploading symbols to Sentry. +The project to use when uploading symbols to Sentry. In the editor, this is **Project Name**. - + -If set to true, the Sentry CLI will not exit with an error code if it encounters an error. **BE AWARE** you might have unminified/unsymbolicated crashes in production if the debug symbol upload fails. When using this flag, you should store built sourcemaps and debug files, to re-run the upload symbols command at a later point. +If set to `true`, a failed upload doesn't fail the build. The SDK passes `--allow-failure` to Sentry CLI. **Be aware** that you might get unsymbolicated crashes in production if the debug symbol upload fails. When you use this option, store the built debug files so you can upload them again later. diff --git a/docs/platforms/unity/configuration/options/index.mdx b/docs/platforms/unity/configuration/options/index.mdx index 6febe18215188..8834fdaaec8b7 100644 --- a/docs/platforms/unity/configuration/options/index.mdx +++ b/docs/platforms/unity/configuration/options/index.mdx @@ -12,19 +12,15 @@ The SDK provides a configuration window that allows you to set most of Sentry's -Options that can be read from an environment variable (`SENTRY_DSN`, `SENTRY_ENVIRONMENT`, `SENTRY_RELEASE`) are read automatically. + - - -The DSN tells the SDK where to send the events. If this value is not provided, the SDK will try to read it from the `SENTRY_DSN` environment variable. If that variable also does not exist, the SDK will just not send any events. - -In runtimes without a process environment (such as the browser) that fallback does not apply. +The DSN tells the SDK where to send the events. Without a DSN, the SDK is disabled and doesn't send any events. The SDK doesn't read the DSN from the environment variable. Learn more about [DSN utilization](/concepts/key-terms/dsn-explainer/#dsn-utilization). - + Sets the environment. This string is freeform and set by default. A release can be associated with more than one environment to separate them in the UI (think `staging` vs `prod` or similar). @@ -34,47 +30,141 @@ By default, the SDK reports `editor` when running inside the Unity Editor. Other -Sets the release. The SDKk will try to automatically configure a release out of the box. Release names are strings, but some formats are detected by Sentry and might be rendered differently. Learn more about how to send release data so Sentry can tell you about regressions between releases and identify the potential source in [the releases documentation](/product/releases/) or the sandbox. +Sets the release. The SDK will try to automatically configure a release out of the box. Release names are strings, but some formats are detected by Sentry and might be rendered differently. Learn more about how to send release data so Sentry can tell you about regressions between releases and identify the potential source in [the releases documentation](/product/releases/) or the sandbox. + +By default, the SDK creates the release from `Application.productName` and `Application.version`, in the format `{productName}@{version}`. In the product name, line breaks, tabs, `/`, `\`, `..` and `@` are each replaced with `_`. If the product name is empty, only whitespace, or only dots, the release is just `Application.version`. + + + + + +Turns debug mode on or off. If debug is enabled, the SDK prints useful debugging information if something goes wrong with sending the event. It's generally not recommended to turn it on in production, though turning `debug` mode on will not cause any safety concerns. + +In the editor window, **Enable Debug Output** is on and **Only In Editor** is checked, so the SDK prints its diagnostic logs in the Editor but not in builds. Uncheck **Only In Editor** to get them in builds too. + + + + + +Sets the minimum level of the SDK's diagnostic logs when `debug` mode is on. In the editor window, this is **Verbosity Level**. + +- `SentryLevel.Debug`: The most verbose mode +- `SentryLevel.Info`: Informational messages +- `SentryLevel.Warning`: Warning that something might not be right +- `SentryLevel.Error`: Only SDK internal errors are printed +- `SentryLevel.Fatal`: Only critical errors are printed + +To write the logs somewhere else, such as a file, customize the SDK's diagnostic logger. + + + + + +Turns the SDK on or off. When set to `false`, the SDK doesn't initialize. + + + + + +Controls whether the SDK initializes while the game runs in the Unity Editor. When set to `false`, the SDK sends nothing from Play Mode. + + + + + +Sets the logger for the SDK's own diagnostic messages. The SDK uses it only when is on. If you don't set one, the SDK writes to the Unity Console. There's no field for it in the configuration window. Learn more in Diagnostic Logger. + + + +## Filtering Options + + + +The sample rate for error events, greater than `0` and up to `1`. When `null`, the SDK sends every error event. In the configuration window, it's the **Event Sample Rate** field, which accepts `0.01` to `1`, where `1` means `null`. Native crashes on Android, iOS, and macOS with the Cocoa backend follow this rate too. On Windows, Linux, macOS with the Native backend, and game consoles, the native SDK always sends crashes. Learn more in Sampling. + + + + -By default the SDK will read from `Application.productName` and `Application.version` to create the release in the format `$"{Application.productName}@{Application.version}".` +Limits repeated errors, breadcrumbs, and structured logs that come from Unity logging. Turning on **Enable Error Event Throttling** in the configuration window sets a throttler that only limits error events, unless your options configuration script already set one. Implement `IThrottler` to also limit breadcrumbs and structured logs. - + + +Drops exceptions of type `System.Exception` whose message starts with `Error: HTTP/1.1 502 Bad Gateway`. + +Set it to `false` to keep these exceptions. This works in the window, in `Configure`, and when you initialize the SDK with `SentrySdk.Init`. -Turns debug mode on or off. If debug is enabled SDK will attempt to print out useful debugging information if something goes wrong with sending the event. The default is always `false`. It's generally not recommended to turn it on in production, though turning `debug` mode on will not cause any safety concerns. +On iOS with `BuildTime` native initialization, this option also makes the iOS SDK drop events for requests to `operate-sdk-telemetry.unity3d.com`. The iOS SDK takes this value from the window and `Configure` at build time, so setting it in `SentrySdk.Init` doesn't change it. - + -Enabling `debug` mode makes the SDK generate as much diagnostic data as possible. However, if you'd prefer to lower the verbosity of the Sentry SDK diagnostics logs, configure this option to set the appropriate level: +Removes the filter that drops Bad Gateway exceptions. It leaves set to `true`, so on iOS with `BuildTime` native initialization, the iOS SDK still drops events for requests to `operate-sdk-telemetry.unity3d.com`. To turn off both, set to `false` in the window or in `Configure` instead. + + + + + +Removes the filter that drops `System.Net.WebException` with the message `Error: ConnectFailure (The requested address is not valid in this context)`. In the configuration window, it's the **WebException** toggle. + + + + + +Removes the filter that drops `System.Net.Sockets.SocketException` with error code 10049 (`The requested address is not valid in this context`). In the configuration window, it's the **SocketException** toggle. + + + + + +Adds an `IExceptionFilter`. The SDK drops exceptions for which the filter returns `true`. To drop an exception type and the types derived from it, call `AddExceptionFilterForType()`. + + -- `debug`: **default** The most verbose mode -- `info`: Informational messages -- `warning`: Warning that something might not be right -- `error`: Only SDK internal errors are printed -- `fatal`: Only critical errors are printed + -For app models that don't have a console to print to, you can customize the SDK's diagnostic logger to write to a file or to Visual Studio's debug window. +Controls which duplicate events the SDK drops: the same event (`SameEvent`), the same exception instance (`SameExceptionInstance`), an already captured exception that's the inner exception of a new one (`InnerException`), or part of an `AggregateException` (`AggregateException`). By default, the SDK drops all of these except inner exceptions. There's no field for it in the configuration window. + + + +## Logging & Breadcrumbs Options + + + +Controls, for each Unity `LogType`, whether the SDK adds log messages as breadcrumbs. In the configuration window, these are the breadcrumb toggles on the **Logging** tab. Learn more in Breadcrumbs. + + + + + +Stops the SDK from capturing `Debug.Log`, `Debug.LogWarning`, `Debug.LogAssertion`, and `Debug.LogError` calls as events, breadcrumbs, and structured logs. + + + + + +Stops the SDK from capturing exceptions that reach Unity's log handler: uncaught exceptions and `Debug.LogException` calls. The .NET `AppDomain` and unobserved-task handlers keep capturing; turn them off with `DisableAppDomainUnhandledExceptionCapture()` and `DisableUnobservedTaskExceptionCapture()`. ## Data Enrichment & Attachments - + -A list of string prefixes of module names that belong to the app. This option takes precedence over `in-app-exclude`. +Adds a prefix of module names that belong to the app. Call `options.AddInAppInclude("MyCompany.")` with a string prefix, or pass a `Regex`, or use `options.AddInAppIncludeRegex(pattern)`. Includes take precedence over excludes. Sentry differentiates stack frames that are directly related to your game ("in application") from stack frames that come from other packages such as the standard library, third party plugins, or other dependencies. The game's code that is part of the 'Assembly-CSharp' is automatically marked as `inApp`. The difference is visible in [sentry.io](https://sentry.io), where only the "in application" frames are displayed by default. - + -A list of string prefixes of module names that do not belong to the app, but rather to third-party packages. Modules considered not part of the app will be hidden from stack traces by default. +Adds a prefix of module names that don't belong to the app, but to third-party packages. Call `options.AddInAppExclude("ThirdParty.")` with a string prefix, or pass a `Regex`, or use `options.AddInAppExcludeRegex(pattern)`. Modules considered not part of the app will be hidden from stack traces by default. -This option can be overridden using . +The Unity SDK excludes `UnityEngine`, `UnityEditor`, `Cysharp` and `DG.Tweening` by default. Use to override an exclude. @@ -84,7 +174,7 @@ This variable controls the total amount of breadcrumbs that should be captured. - + When enabled, stack traces are automatically attached to all messages logged. Stack traces are always attached to exceptions; however, when this option is set, stack traces are also sent with messages. This option, for instance, means that stack traces appear next to all log messages. @@ -94,7 +184,7 @@ Grouping in Sentry is different for events with stack traces and without. As a r -Attaches a screenshot of the game to events, such as errors and messages, and sends it in the same envelope as the event. Screenshots aren't attached in the Editor, in batch mode, or on WebGL. +Attaches a screenshot of the game to events, such as errors and messages, and sends it in the same envelope as the event. Screenshots aren't attached in the Editor, in batch mode, or on WebGL. On iOS and Windows, native crashes also get a screenshot, taken by the native SDK. Learn more about enriching events with screenshots in our Screenshots documentation. @@ -127,6 +217,20 @@ Set this boolean to `false` to disable sending of client reports. Client reports Once enabled, this feature automatically captures HTTP client errors, like bad response codes, as error events and reports them to Sentry. +It applies to requests sent with an `HttpClient` that uses `SentryHttpMessageHandler`, for example `new HttpClient(new SentryHttpMessageHandler())`. Requests sent with `UnityWebRequest` aren't captured. On iOS and macOS, the option is also passed to the native Cocoa SDK, unless the app initializes that SDK itself. The status codes that count as failed are set by `FailedRequestStatusCodes`, which defaults to 500–599. Both options can only be set in code. + + + + + +The response status codes that count as failed requests for . There's no field for it in the configuration window. + + + + + +The request URLs that applies to, as substrings or regular expressions. Adding an item removes the default `.*`. There's no field for it in the configuration window. + @@ -141,12 +245,32 @@ Sets the distribution of the application. Distributions are used to disambiguate + + +Controls whether events list the loaded assemblies, and which version they report: `None`, `Version`, or `InformationalVersion`. If an assembly has no informational version, `InformationalVersion` reports the assembly version. + + + + + +Tags the SDK adds to every event. If an event already has a tag with the same key, it keeps its own value. Add tags to the dictionary, for example `options.DefaultTags["level"] = "forest";`. There's no field for it in the configuration window. Learn more in Tags. + + + + + +Tag keys the SDK ignores, as substrings or regular expressions. Setting a tag whose key matches has no effect. There's no field for it in the configuration window. + + + ## Privacy & PII If this flag is enabled, certain personally identifiable information (PII) is added by active integrations. By default, no such data is sent. +In Unity, it adds the device name (`device.name`) and the device's unique identifier to events. Native crashes on Windows, Linux, macOS with the Native backend, and game consoles carry the device name only with this option, too. Native crashes on iOS, Android, and macOS with the Cocoa backend don't include the device name. With , it also adds the user name. Learn more in Data Collected. + If you are using Sentry in your mobile app, read our [frequently asked questions about mobile data privacy](/security-legal-pii/security/mobile-privacy/) to assist with Apple App Store and Google Play app privacy details. @@ -159,9 +283,14 @@ If you enable this option, be sure to manually remove what you don't want to sen - + + +Reports `Environment.UserName` as the user of each event. It applies only when is on and the event has no user set. + +The default depends on where the options come from: -This option can be used to supply a server name. When provided, the name of the server is sent along and persisted in the event. For many integrations, the server name actually corresponds to the device hostname, even in situations where the machine is not actually a server. +- Configuration window (**Auto Set UserName**): `false`. An options configuration script sees the window's value. +- `new SentryUnityOptions()` and `SentrySdk.Init`: `true` in Windows, macOS, and Linux players and dedicated servers, and `false` everywhere else, including the Unity Editor, Android, iOS, and consoles. @@ -197,13 +326,13 @@ By the time is executed, -A callback function that controls screenshot capture behavior. Return `false` to prevent a screenshot from being attached to a specific event. It can run on a background thread and runs before and sampling. Learn more in our Screenshots documentation. +A callback function that controls screenshot capture behavior. Return `false` to prevent a screenshot from being attached to a specific event. It can run on a background thread and runs before and sampling. Setting it turns off screenshots for native crashes on iOS, as it can't run during a crash. Learn more in our Screenshots documentation. -A callback function that receives the screenshot as a `Texture2D` before it gets compressed, along with the event it belongs to. Modify or replace the texture and return it, or return `null` to discard the screenshot. Setting it makes the SDK read and compress screenshots on the main thread. Learn more in our Screenshots documentation. +A callback function that receives the screenshot as a `Texture2D` before it gets compressed, along with the event it belongs to. Modify or replace the texture and return it, or return `null` to discard the screenshot. Setting it makes the SDK read and compress screenshots on the main thread, and turns off screenshots for native crashes on iOS, as it can't run during a crash. Learn more in our Screenshots documentation. @@ -213,13 +342,31 @@ A callback function that controls view hierarchy capture behavior. Return `false + + +A callback function that receives the captured view hierarchy before the SDK serializes it, along with the event it belongs to. Modify the hierarchy and return it, or return `null` to discard it. Learn more in View Hierarchy. + + + + + +A callback function that receives user feedback before the SDK sends it. Return the feedback event, modified or not, or return `null` to drop it. Learn more in User Feedback. + + + + + +Adds an `ISentryEventProcessor` that runs for every event. A processor can change the event, or return `null` to drop it. + + + ## Transport & Network Options Transports are used to send events to Sentry. Transports can be customized to some degree to better support highly specific deployments. - + -Switches out the transport used to send events. How this works depends on the SDK. It can, for instance, be used to capture events for unit-testing or to send it through some more complex setup that requires proxy authentication. +Switches out the transport used to send events. It can, for instance, be used to capture events for unit-testing or to send it through some more complex setup that requires proxy authentication. On WebGL and Nintendo Switch, this option has no effect: the SDK always sends events with `UnityWebRequest` there. @@ -229,23 +376,53 @@ The maximum number of [envelopes](https://develop.sentry.dev/sdk/data-model/enve - + -When set, a proxy can be configured that should be used for outbound requests. This is also used for HTTPS requests unless a separate `https-proxy` is configured. However, not all SDKs support a separate HTTPS proxy. SDKs will attempt to default to the system-wide configured proxy, if possible. For instance, on Unix systems, the `http_proxy` environment variable will be picked up. +Sets the proxy the SDK uses to send events to Sentry, for both HTTP and HTTPS. On WebGL and Nintendo Switch, this option has no effect. - + When caching is enabled (that is, is set), this option controls the timeout that limits how long the SDK will attempt to flush existing cache during initialization. Note that flushing the cache involves sending the payload to Sentry in a blocking operation. Setting this option to zero means that Sentry will **not** attempt to flush the cache during initialization, but instead will do so when the next payload is queued up. -The default is `1` (one) second. +The default is zero, so the SDK doesn't block during initialization to flush the cache. - + -Controls how many seconds to wait before shutting down. Sentry SDKs send events from a background queue. This queue is given a certain amount to drain pending events. The default is SDK specific but typically around two seconds. Setting this value too low may cause problems for sending events from command line applications. Setting the value too high will cause the application to block for a long time for users experiencing network connectivity problems. +Controls how long to wait before shutting down. Sentry SDKs send events from a background queue. This queue is given a certain amount of time to drain pending events. The default is two seconds. Setting this value too low may cause problems for sending events from command line applications. Setting the value too high will cause the application to block for a long time for users experiencing network connectivity problems. + + + + + +The directory where the SDK stores events before it sends them, so they survive restarts and network outages. Set it to `null` to turn offline caching off. Turning off **Enable Offline Caching** in the configuration window sets it to `null`. + + + + + +The maximum number of events the SDK keeps in memory while it sends them. Set it to at least `1`. + + + + + +How long `SentrySdk.Flush()` waits for queued events to be sent. There's no field for it in the configuration window. + + + + + +How the SDK compresses the requests it sends to Sentry: `NoCompression`, `Optimal`, `Fastest`, or `Auto`, which uses `NoCompression`. IL2CPP doesn't support `Optimal` and `Fastest`. There's no field for it in the configuration window. + + + + + +Lets the SDK lower the sample rate of events and transactions while the system is under load. There's no field for it in the configuration window. @@ -253,25 +430,61 @@ Controls how many seconds to wait before shutting down. Sentry SDKs send events -A number between `0` and `1`, controlling the percentage chance a given transaction will be sent to Sentry. (`0` represents 0% while `1` represents 100%.) Applies equally to all transactions created in the app. Either this or must be defined to enable tracing. +A number between `0` and `1`, controlling the percentage chance a given transaction will be sent to Sentry. (`0` represents 0% while `1` represents 100%.) Applies equally to all transactions created in the app. The automatic startup, scene-load and `Awake` instrumentation only runs when this is greater than `0`. -A function responsible for determining the percentage chance a given transaction will be sent to Sentry. It will automatically be passed information about the transaction and the context in which it's being created, and must return a number between `0` (0% chance of being sent) and `1` (100% chance of being sent). Can also be used for filtering transactions, by returning 0 for those that are unwanted. Either this or must be defined to enable tracing. +A function responsible for determining the percentage chance a given transaction will be sent to Sentry. It will automatically be passed information about the transaction and the context in which it's being created, and must return a number between `0` (0% chance of being sent) and `1` (100% chance of being sent). Can also be used for filtering transactions, by returning 0 for those that are unwanted. A `TracesSampler` on its own enables tracing for the transactions you create. The automatic instrumentation also needs to be greater than `0`. -Controls whether the SDK will automatically trace the app's startup. +Controls whether the SDK will automatically trace the app's startup. Requires to be greater than `0`. -Controls whether the SDK will automatically trace when loading scenes. +Controls whether the SDK will automatically trace when loading scenes. Requires to be greater than `0`. + + + + + +Adds spans for `Awake` calls during startup and scene loading. In the configuration window, it's the **Spans for Awake Calls** toggle. The SDK reads this option only during the build, when it instruments the game's code, and only if is greater than `0`. Setting it at runtime has no effect. Learn more in Automatic Instrumentation. + + + + + +Transaction names to drop, as substrings or regular expressions. The SDK drops matching transactions before runs. There's no field for it in the configuration window. + + + + + +The outgoing HTTP requests that get the `sentry-trace` and `baggage` headers, matched by URL as substrings or regular expressions. It applies to requests sent through `SentryHttpMessageHandler`. Adding an item removes the default `.*`, and an empty list turns propagation off. There's no field for it in the configuration window. Learn more in Trace Propagation. + + + + + +Also sends the W3C `traceparent` header with requests that match . There's no field for it in the configuration window. + + + + + +When set to `true`, the SDK continues an incoming trace only if it has the same org ID as yours. Otherwise, it starts a new trace. When set to `false`, the SDK also continues incoming traces that have no org ID. A trace with a different org ID always starts a new trace. There's no field for it in the configuration window. + + + + + +The org ID the SDK uses for trace propagation and . By default, the SDK reads it from the DSN. Set it when your DSN doesn't contain it, for example with self-hosted Sentry or a local Relay. There's no field for it in the configuration window. @@ -293,12 +506,16 @@ Sets how long the main thread must be unresponsive before the SDK captures an ap -Controls the managed Unity watchdog in the Sentry configuration window. To disable this detector programmatically, call `options.DisableAnrIntegration()`. +**Deprecated:** Use instead. + +Controls the managed C# watchdog. You can only set it in the editor window, under **Advanced > Automatic Behaviour > C# Watchdog (Deprecated)**. Programmatic initialization doesn't add the watchdog. +**Deprecated:** Use instead. + Sets how long the Unity main thread must be unresponsive before the managed watchdog reports an ANR event. @@ -320,3 +537,181 @@ Reports historical Android ANRs recorded by the operating system. This option re Attaches the Android operating system's thread dump to ANR events. This option requires . + +## Native Support Options + +These options control the native SDKs that the Unity SDK includes. Learn more in Native Support. + + + +Turns on native support on iOS through the [iOS SDK](/platforms/apple/guides/ios/). + + + + + +Turns on native support on Android through the [Android SDK](/platforms/android/). Android native support requires the IL2CPP scripting backend: with Mono, this option and the other Android options have no effect. + + + + + +Turns on the Android NDK integration, which captures native crashes in C and C++ code. Requires . + + + + + +Syncs the scope, such as breadcrumbs, tags, and the user, to the Android NDK layer, so native crashes include it. Requires . + + + + + +Turns on native support on Windows. + + + + + +Turns on native support on macOS. + + + + + +Turns on native support on Linux. + + + + + +Turns on native support on Xbox. Learn more in Game Consoles. + + + + + +Turns on native support on PlayStation. Learn more in Game Consoles. + + + + + +Syncs the scope to the native layer on Nintendo Switch and Switch 2. Learn more in Game Consoles. + + + + + +When the iOS SDK initializes: `Runtime`, `BuildTime`, or `External`. `External` is experimental and is for Unity as a Library. The SDK reads it during the build to set up the Xcode project, so set it in an options configuration script, which also runs during the build. + + + + + +When the Android SDK initializes: `Runtime`, `BuildTime`, or `External`. `External` is experimental and is for Unity as a Library. The SDK reads it during the build to set up the Gradle project, so set it in an options configuration script, which also runs during the build. + + + + + +Turns on [watchdog termination tracking](/platforms/apple/guides/ios/configuration/watchdog-terminations/) in the iOS SDK. There's no field for it in the configuration window. + + + + + +Reports native crashes that Android records as tombstones, which the Android SDK reads through `ApplicationExitInfo`. There's no field for it in the configuration window. + + + + + +Also reports tombstones that Android recorded in earlier runs. Requires . There's no field for it in the configuration window. + + + + + +The `callbackOrder` of the build step in which the SDK changes the generated Gradle project. Change it if another `IPostGenerateGradleAndroidProject` step must run before or after the SDK's. There's no field for it in the configuration window. + + + + + +The path to the out-of-process crash handler executable. By default, the SDK looks for it next to the player executable. It applies on Windows, Linux, and on macOS with the `Native` backend. There's no field for it in the configuration window. + + + + + +The native backend on Windows. `Crashpad` uses `crashpad_handler.exe`. `Native` is experimental and uses the out-of-process `sentry-crash.exe` handler, which uploads crashes right away. + + + + + +The native backend on macOS. `Cocoa` uses the [macOS SDK](/platforms/apple/guides/macos/) and requires IL2CPP. `Native` is experimental and uses the [Native SDK](/platforms/native/) with an out-of-process handler, which uploads crashes right away. It works with IL2CPP and Mono. + + + + + +The native backend on Linux. `Breakpad` captures crashes in process and uploads them on the next launch. `Native` is experimental and uses the out-of-process `sentry-crash` handler, which uploads crashes right away. + + + +When any of these backends is set to `Native`, the SDK raises to at least 10 seconds, so the handler has time to upload before the player exits. When you initialize the SDK with `SentrySdk.Init`, set `ShutdownTimeout` yourself. + +## Metrics Options + +These options are experimental. They make the SDK collect game metrics and send them to Sentry. Learn more in Metrics. + + + +Collects frame metrics, such as frame time, FPS, and CPU thread timings. + + + + + +How often the SDK samples frame metrics. The minimum is one second. + + + + + +Collects memory usage. + + + + + +How often the SDK samples memory metrics. The minimum is one second. + + + + + +Collects garbage collection counts for each generation. + + + + + +How often the SDK samples garbage collection metrics. The minimum is one second. + + + + + +Collects multiplayer network metrics: the round-trip time on clients and the number of connected clients on the server. Requires the Netcode for GameObjects package. + + + + + +How often the SDK samples network metrics. The minimum is one second. + + diff --git a/docs/platforms/unity/configuration/options/programmatic-configuration/img/initialization-flow.png b/docs/platforms/unity/configuration/options/programmatic-configuration/img/initialization-flow.png deleted file mode 100644 index 1e00fd707eabf..0000000000000 Binary files a/docs/platforms/unity/configuration/options/programmatic-configuration/img/initialization-flow.png and /dev/null differ diff --git a/docs/platforms/unity/configuration/options/programmatic-configuration/index.mdx b/docs/platforms/unity/configuration/options/programmatic-configuration/index.mdx index 4c5e2b9bb8420..0a98e7b59de26 100644 --- a/docs/platforms/unity/configuration/options/programmatic-configuration/index.mdx +++ b/docs/platforms/unity/configuration/options/programmatic-configuration/index.mdx @@ -6,7 +6,9 @@ og_image: >- /og-images/platforms-unity-configuration-options-programmatic-configuration.png --- -We've added `Sentry Options Configuration` to the `Options Config` tab in the Sentry editor window to provide a way to modify options programmatically. +To set options in code, use an options configuration script. In the Sentry configuration window (**Tools > Sentry**), open the **Options Config** tab and click **New** next to the **Option Config Script** field. The SDK asks where to save the script, starting in `Assets/Scripts`, and writes a class that inherits from `SentryOptionsConfiguration`. After Unity compiles the script, the SDK creates its asset in `Assets/Resources/Sentry/` and assigns it to the field, unless the field already has a script. + +The SDK calls the script's `Configure` method after it applies the values from the configuration window, so the values you set in `Configure` override the window. `Configure` also runs during player builds, where the SDK uses the options to set up the native SDKs and other build steps. During a build, `Environment` defaults to `production`. Don't rely on the game's runtime state in `Configure`, and wrap code that must only run in the game in `if (Application.isPlaying)`. ![Options Configuration](./img/unity-options-configuration.png) @@ -14,11 +16,21 @@ We've added `Sentry Options Configuration` to the `Options Config` tab in the Se The Sentry SDK for Unity includes [platform-specific (that is, Native)](/platforms/unity/native-support/) SDKs, such as [Android](/platforms/android/), [Apple](/platforms/apple/guides/ios/), and [Native](/platforms/native/) to provide native crash support. These SDKs share the options with which they get initialized. -The C# layer self-initializes through the use of the [SubsystemRegistration RuntimeInitializeOnLoadMethodAttribute](https://docs.unity3d.com/ScriptReference/RuntimeInitializeLoadType.SubsystemRegistration.html). - -![Flow of initialization](./img/initialization-flow.png) +The SDK initializes itself at [SubsystemRegistration](https://docs.unity3d.com/ScriptReference/RuntimeInitializeLoadType.SubsystemRegistration.html) through `RuntimeInitializeOnLoadMethod`. On WebGL, it initializes at [BeforeSceneLoad](https://docs.unity3d.com/ScriptReference/RuntimeInitializeLoadType.BeforeSceneLoad.html) instead, because the WebGL transport can't send requests earlier. The native steps only run in a player with native support: not in the Editor, on WebGL, on Android with Mono, or on macOS with Mono and the default `Cocoa` backend. With `BuildTime` initialization on iOS and Android, the native SDK starts before Unity, so the SDK skips that step. With `External`, it skips it when the app that embeds the game has already started the native SDK. Learn more in Unity as a Library. + +```mermaid +flowchart TD + Start["SubsystemRegistration
(BeforeSceneLoad on WebGL)"] --> Load[Load the options from the configuration window] + Load --> Configure["Call Configure in your options configuration script"] + Configure --> HasNative{"Native support
in this player?"} + HasNative -- Yes --> Native["Initialize the native SDK
(unless it's already running)"] + Native --> Sync[Set up scope sync with the native SDK] + Sync --> CSharp[Initialize the C# SDK] + HasNative -- No --> CSharp + CSharp --> Game[Load the first scene] +``` -If provided, the `Option Configuration Script` is executed on each app startup. The options are first used to initialize the native SDKs, then the managed (C#) SDK. This means that the options you set in your `Configure` callback will also apply on the native layer. For example: +The SDK initializes the native SDK with the same options before the C# SDK, so the options you set in `Configure` also apply to the native layer. With `BuildTime` initialization, the native SDK uses the options from the build instead, and with `External`, usually the options of the app that embeds the game. For example: ```csharp public override void Configure(SentryUnityOptions options) @@ -67,3 +79,37 @@ With runtime initialization, the native SDKs are initialized at runtime alongsid ### Build Time Initialization When using build time initialization, the native SDKs are configured during build time and initialize before the Unity engine starts. This means the options are baked into the outputted projects and cannot be modified at runtime via C# code. Changes to properties like `Release` and `Environment` will not apply to events generated by the native SDKs. + +## Manual Initialization + +To initialize the SDK yourself instead of letting it self-initialize, uncheck **Enable Sentry** in the editor window (**Tools > Sentry**) and call `SentrySdk.Init` as early as possible, for example from a `RuntimeInitializeOnLoadMethod`: + +```csharp +using Sentry.Unity; +using UnityEngine; + +public static class SentryInitializer +{ +#if UNITY_WEBGL + // On WebGL, the SDK sets itself up at BeforeSceneLoad, so initialize after it + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] +#else + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] +#endif + private static void Init() + { + SentrySdk.Init(options => + { + options.Dsn = "___PUBLIC_DSN___"; + }); + } +} +``` + +When you initialize manually, the options from the editor window and the option configuration script don't apply. Only the options you set in code are used. + + + +With **Enable Sentry** unchecked, the build doesn't set up native support or upload debug symbols, so the SDK only captures C# errors. To keep native crash support, leave **Enable Sentry** checked and use the option configuration script instead. + + diff --git a/docs/platforms/unity/configuration/releases.mdx b/docs/platforms/unity/configuration/releases.mdx index 0dcc8bbee05e8..013eb6b5b7f00 100644 --- a/docs/platforms/unity/configuration/releases.mdx +++ b/docs/platforms/unity/configuration/releases.mdx @@ -42,10 +42,3 @@ In order to monitor release health, the SDK sends session data. A session represents the interaction between the user and the application. Sessions contain a timestamp, a status (if the session was OK or if it crashed), and are always linked to a release. Most Sentry SDKs can manage sessions automatically. - - - -Release health support for .NET is currently limited to single-instance **client** applications only. This means it can be used with WPF, Xamarin, WinForms and similar app models. -Support for server frameworks such as ASP.NET is planned. - - diff --git a/docs/platforms/unity/configuration/sampling.mdx b/docs/platforms/unity/configuration/sampling.mdx index b5533d0a61fcb..f8aaad3c0d949 100644 --- a/docs/platforms/unity/configuration/sampling.mdx +++ b/docs/platforms/unity/configuration/sampling.mdx @@ -8,12 +8,14 @@ Adding Sentry to your app gives you a great deal of very valuable information ab ## Sampling Error Events -To send a representative sample of your errors to Sentry, set the option in your SDK configuration to a number between `0` (0% of errors sent) and `1` (100% of errors sent). This is a static rate, which will apply equally to all errors. For example, to sample 25% of your errors: +To send a representative sample of your errors to Sentry, set the option in your SDK configuration to a number greater than `0` and up to `1` (100% of errors sent). In the configuration window, the **Event Sample Rate** field accepts `0.01` to `1`. This is a static rate, which will apply equally to all errors. For example, to sample 25% of your errors: The error sample rate defaults to `1`, meaning all errors are sent to Sentry. +Native crashes on Android, iOS, and macOS with the Cocoa backend follow the error sample rate too. On Windows, Linux, macOS with the Native backend, and game consoles, the native SDK always sends crashes. + Changing the error sample rate requires re-deployment. In addition, setting an SDK sample rate limits visibility into the source of events. Setting a rate limit for your project (which only drops events when volume is high) may better suit your needs. diff --git a/docs/platforms/unity/data-management/data-collected.mdx b/docs/platforms/unity/data-management/data-collected.mdx index 8d209e8d7bbce..6dec5530aa7a5 100644 --- a/docs/platforms/unity/data-management/data-collected.mdx +++ b/docs/platforms/unity/data-management/data-collected.mdx @@ -6,79 +6,75 @@ sidebar_order: 1 Sentry takes data privacy very seriously and has default settings in place that prioritize data safety, especially when it comes to personally identifiable information (PII) data. When you add the Sentry SDK to your application, you allow it to collect data and send it to Sentry during the runtime of your application. -The category types and amount of data collected vary, depending on the integrations you've enabled in the Sentry SDK. Here's a list of data categories the Sentry .NET SDK collects: +The data the Sentry Unity SDK collects depends on the options and integrations you enable. Here's a list of data categories it collects: -## HTTP Headers +## Information About the User -By default, the Sentry SDK sends HTTP headers to Sentry but redacts any headers that may contain sensitive data. (See the [list of headers](https://github.com/getsentry/sentry-dotnet/blob/main/src/Sentry/Internal/RedactedHeaders.cs#L7) that are redacted). +The SDK always sends an installation ID as `user.id`. By default, it's a random ID that the SDK stores in a file on the device. On platforms where the SDK can't write files, such as UWP and visionOS, it uses the MAC address of the network adapter or a hash of the machine name instead. On iOS, Android, Nintendo Switch, and macOS with the Cocoa backend, it's the native SDK's installation ID, so C# events and native crashes share the same user. -## Cookies +With Unity as a Library, the game's events carry the user that the host app sets. -By default, the Sentry SDK doesn't send cookies. +To send your own user information, [identify the user](../../enriching-events/identify-user/). -If you want to send cookies, set the option `SendDefaultPii = true` when initializing the Sentry SDK. +## Data Sent With SendDefaultPii -A [data scrubber](/platforms/dotnet/data-management/sensitive-data/) can be used to filter information before sending data to Sentry. +If `SendDefaultPii` is set to `true`, the SDK also sends: -Any [sensitive cookies](https://github.com/getsentry/relay/blob/249971e1702991c64cf0f7f89773fb019ffb4a95/relay-pii/src/convert.rs#L235-L263) that the SDK does send will be stripped by Relay before Sentry stores these. +- The user's IP address. The SDK sets it to `{{auto}}`, and Sentry fills in the IP address the event came from. +- The device unique identifier (`SystemInfo.deviceUniqueIdentifier`). +- The device's name as `device.name`. On desktop, this is the computer name. Native crashes on Windows, Linux, macOS with the Native backend, and game consoles include it only with this option too. Native crashes on Android, iOS, and macOS with the Cocoa backend don't include a device name. +- The operating system's user name as `user.username`, if **Auto Set UserName** (`IsEnvironmentUser`) is also enabled. Learn more in [Options](/platforms/unity/configuration/options/#IsEnvironmentUser). -## Information About Logged-in User +Error events don't include a server name. -By default, the Sentry SDK doesn't send any information about the logged-in user, such as email address, user ID, or username. Even if enabled, the type of logged-in user information you'll be able to send depends on the integrations you enable in Sentry's SDK. Most integrations won't send any user information. Some will only set the user ID, but there are a few that will set the user ID, username, and email address. +You can [prevent Sentry from storing IP Addresses](../../enriching-events/identify-user/#ip_address) either by configuring this in the ["Security & Privacy"](https://sentry.io/orgredirect/organizations/:orgslug/settings/projects/:projectId/security-and-privacy/) settings of your Sentry project or using [server-side data scrubbing](/security-legal-pii/scrubbing/server-side-scrubbing/). -To start sending logged-in user information, set the option `SendDefaultPii = true` when initializing the Sentry SDK. +## Failed HTTP Requests -## Users' IP Address +On iOS and macOS with the Cocoa backend, the Cocoa SDK captures failed `NSURLSession` requests as native events, with the URL, query string, method, and sanitized headers. These events don't run the C# callbacks. To turn this off, set [`CaptureFailedRequests`](/platforms/unity/configuration/options/#CaptureFailedRequests) to `false`. -By default, the Sentry SDK doesn't send the user's IP address. +In C#, the SDK only records HTTP requests sent through `SentryHttpMessageHandler`. For these, it adds `http` breadcrumbs with the URL, and captures failed requests as events with the URL and query string. If `SendDefaultPii` is set to `true`, these events also include the full URL, the headers, and the cookies. -To enable sending the user's IP address, set the option `SendDefaultPii = true` when initializing the Sentry SDK. - -Even if enabled, whether you're able to send the user's IP address or not, will depend on the integrations you enable in Sentry's SDK. Most integrations won't set the user's IP address at all. - -You can [prevent Sentry from storing IP Addresses](/platforms/native/enriching-events/identify-user/#ip_address) either by configuring this in the ["Security & Privacy"](https://sentry.io/orgredirect/organizations/:orgslug/settings/projects/:projectId/security-and-privacy/) settings of your Sentry project or using [server-side data scrubbing](/security-legal-pii/scrubbing/server-side-scrubbing/). - -## Request URL - -By default, the [HttpRequestUrl](https://learn.microsoft.com/en-us/dotnet/api/System.UriComponents) of outgoing and incoming HTTP requests is **always sent to Sentry**. This includes the Scheme, Host, Port, LocalPath, and Query data. - -If `SendDefaultPii` is set to `true` then the [AbsoluteUri](https://learn.microsoft.com/en-us/dotnet/api/System.UriComponents) of outgoing and incoming HTTP requests will be sent to Sentry (including the Scheme, UserInfo, Host, Port, LocalPath, Query, and Fragment data). - -Depending on your application, this could contain PII data. - -## Request Query String - -The full request query string of outgoing and incoming HTTP requests is **always sent to Sentry**. Depending on your application, this could contain PII data. +## General Device Information -## SQL Queries +The SDK collects information about the app, the operating system, the device, the GPU, the runtime, and Unity, and sends it with every event: -While SQL queries are sent to Sentry, neither the full SQL query (`SELECT * FROM users WHERE email = 'joe@shmoe.com'`), nor the values of its parameters will ever be sent. A parameterized version of the query (`SELECT * FROM users WHERE email = @email`) is sent instead. +- `app`: the product name, the start time, and whether it's a debug or release build. +- `os`: the operating system description. On Xbox and PlayStation, it's the name of the console. +- `device`: the processor count, CPU, time zone, vibration support, device type, model, and system memory. In the Unity Editor, the device is marked as a simulator. +- `gpu`: the GPU's ID, name, vendor name and ID, memory, graphics API and version, maximum texture size, shader level, multithreaded rendering, and support for non-power-of-two textures, instancing, ray tracing, and compute and geometry shaders. +- `unity`: the Editor version, install mode, target frame rate, copy texture support, and rendering threading mode. +- `runtime`: the .NET runtime the game runs on. +- The current culture and UI culture, and the thread pool's thread counts. -## Device Unique Identifier +For events captured on the main thread, the SDK also adds: -The Sentry SDK does not set the `Device Unique Identifier` by default. +- The app's allocated memory (`app.memory`). +- The battery status and level, and the device orientation. +- The connection type, on iOS and Android. +- The name of the active scene, in the Unity Editor and in IL2CPP builds. -If `SendDefaultPii` is set to `true` then the SDK will capture `SystemInfo.deviceUniqueIdentifier` automatically and send this with any event. +Every event also records whether it was captured on the main thread (`unity.is_main_thread`). -## Machine Name +## Breadcrumbs -The Sentry SDK does not send the machine name by default. +The SDK records Unity log messages, scene changes, and app lifecycle events as breadcrumbs, and sends them with events. Log messages can contain PII, depending on what your game logs. Learn more in [Breadcrumbs](../../enriching-events/breadcrumbs/). -If you assign a value to the `ServerName` in the Sentry options then Sentry SDK will send this with any events. +## Logs -Otherwise, if `SendDefaultPii` is set to true then the Sentry SDK will capture the `Environment.MachineName` automatically and send this with any events. +Unity log messages that the SDK forwards to Sentry Logs can contain PII, depending on what your game logs. Each log carries the user from the scope as attributes. If `SendDefaultPii` is set to `true`, each log also carries the machine name as `server.address`. Learn more in [Logs](/platforms/unity/logs/). -## General Device Information +## Screenshots and View Hierarchy -The Sentry SDK collects information about the device, such as the version and build of your operating system, CPU and GPU details etc. This information is sent to Sentry by default. +Screenshots and the view hierarchy are opt-in. Both can contain PII, such as names shown on screen or in the names of GameObjects. Learn more in [Screenshots](../../enriching-events/screenshots/) and [View Hierarchy](../../enriching-events/view-hierarchy/). ## Data captured by Mobile SDKs -On mobile platforms, the Sentry SDK for .NET can also capture data indirectly via the Android and iOS SDKs. You should refer to the documentation for those SDKs for more information on what data is captured. +On mobile platforms, the Sentry SDK for Unity can also capture data through the Android and iOS SDKs. Refer to the documentation for those SDKs for more information on what data they capture. - [Android](/platforms/android/data-management/data-collected/) - [iOS](/platforms/apple/data-management/data-collected/) ## Data captured by the Native SDK -When compiling for Windows, Linux or other platforms that use Sentry Native, you should refer to [data captured by the Native SDK](/platforms/native/data-management/data-collected/) to understand what data is sent with those events. +When compiling for Windows, Linux or other platforms that use Sentry Native, refer to [data captured by the Native SDK](/platforms/native/data-management/data-collected/) to understand what data is sent with those events. diff --git a/docs/platforms/unity/data-management/debug-files/file-formats/index.mdx b/docs/platforms/unity/data-management/debug-files/file-formats/index.mdx index de46aa3938f39..870d8d49f03c8 100644 --- a/docs/platforms/unity/data-management/debug-files/file-formats/index.mdx +++ b/docs/platforms/unity/data-management/debug-files/file-formats/index.mdx @@ -186,3 +186,11 @@ while removing all debug information from the release binary. ProGuard mapping files allow Sentry to resolve obfuscated Java classpaths and method names into their original form. In that sense, they act as debug information files for Java and Android applications. + +## IL2CPP Line Mappings + +IL2CPP builds turn your C# code into C++ code, so crashes and exceptions happen in native code. To show C# file names and line numbers, Sentry needs a mapping from the generated C++ code back to your C# code. `sentry-cli` creates this mapping from the IL2CPP output in the `_BackUpThisFolder_ButDontShipItWithYourGame` folder, which Unity creates next to the build. The Unity SDK uploads it as part of the [automated debug symbol upload](/platforms/unity/native-support/#debug-symbols). To upload it yourself, see [Manual Upload Using sentry-cli](/platforms/unity/native-support/#manual-upload-using-sentry-cli). For more information, see [IL2CPP Line Numbers](/platforms/unity/configuration/il2cpp/). + +## Burst Debug Information + +Code compiled with Unity's Burst compiler is native code. Unity puts its debug information in the `_BurstDebugInformation_DoNotShip` folder next to the build. Upload this folder along with the rest of your build. The Unity SDK includes it in the [automated debug symbol upload](/platforms/unity/native-support/#debug-symbols). diff --git a/docs/platforms/unity/data-management/debug-files/index.mdx b/docs/platforms/unity/data-management/debug-files/index.mdx index 2f593dd825cdb..531dbe85ea971 100644 --- a/docs/platforms/unity/data-management/debug-files/index.mdx +++ b/docs/platforms/unity/data-management/debug-files/index.mdx @@ -23,11 +23,15 @@ the following formats: - [_WASM files_](./file-formats/#wasm) for WebAssembly - [_ProGuard mappings_](./file-formats/#proguard-mappings) for Java and Android +- [_IL2CPP line mappings_](./file-formats/#il2cpp-line-mappings) for C# line + numbers in IL2CPP builds +- [_Burst debug information_](./file-formats/#burst-debug-information) for code + compiled with Unity's Burst compiler Source maps, while also being debug information files, are handled -differently in Sentry. For more information see [Source Maps in sentry-cli](/cli/releases/#sentry-cli-sourcemaps). +differently in Sentry. For more information see [Upload Source Maps in sentry-cli](/cli/releases/#upload-source-maps). diff --git a/docs/platforms/unity/data-management/debug-files/source-context/index.mdx b/docs/platforms/unity/data-management/debug-files/source-context/index.mdx index b5a19b824ccd0..a9daf13b588c3 100644 --- a/docs/platforms/unity/data-management/debug-files/source-context/index.mdx +++ b/docs/platforms/unity/data-management/debug-files/source-context/index.mdx @@ -9,7 +9,7 @@ og_image: /og-images/platforms-unity-data-management-debug-files-source-context. If Sentry has access to your application's source code, it can show snippets of code (_source context_) around the location of stack frames, which helps to quickly pinpoint problematic code. -For example, here's a stack trace from a .NET application. The source context contains +For example, here's a stack trace with source context. The source context contains the original C# source code of the application, with the location of the frame highlighted. ![Screenshot of stack trace showing source context.](./img/source-context-screenshot.png) @@ -25,13 +25,7 @@ See [Creating Source Bundles](/cli/dif/#creating-source-bundles) for more inform -Alternatively, you can embedded source code directly into .NET Portable PDB files by using the -[`EmbedAllSources`](https://github.com/dotnet/sourcelink/blob/main/docs/README.md#embedallsources) -property in your project file. After the PDBs have been uploaded to Sentry, the sources will be -extracted from them automatically. - -Also note that the similar `EmbedUntrackedSources` option is not yet supported, but may be added -in the future. Referer to [this issue](https://github.com/getsentry/symbolic/issues/735) for details. +The Unity SDK can upload source bundles for you. Enable **Upload Sources** on the **Debug Symbols** tab in **Tools > Sentry**, or set [`UploadSources`](/platforms/unity/configuration/options/cli-options/#UploadSources) in code. The SDK then passes `--include-sources` to `sentry-cli` during the automated debug symbol upload. diff --git a/docs/platforms/unity/data-management/debug-files/upload/index.mdx b/docs/platforms/unity/data-management/debug-files/upload/index.mdx index 805192c96c51f..a29c09a5f756c 100644 --- a/docs/platforms/unity/data-management/debug-files/upload/index.mdx +++ b/docs/platforms/unity/data-management/debug-files/upload/index.mdx @@ -18,23 +18,6 @@ application: - - -Depending on application type, target platform, and build configuration, the -Sentry support for .NET may require uploading debug files in order to show a -complete stack trace including file names and line numbers. This is especially -true for mobile apps targeting Android or iOS, such as those developed with -.NET MAUI. - -To make this easier, the `Sentry` NuGet package (as of version 3.26.1) includes -the Sentry CLI as a bundled tool, and will invoke it when building -your project if the msbuild property `SentryUploadSymbols` is set to true (default to false). -Refer to [msbuild configuration](/platforms/dotnet/configuration/msbuild/) for details. - -The remaining information on this page describes invoking the Sentry CLI manually. - - - Files can be uploaded using the `debug-files upload` command. This command will scan a diff --git a/docs/platforms/unity/data-management/sensitive-data/index.mdx b/docs/platforms/unity/data-management/sensitive-data/index.mdx index 393cd2b10e6e2..e9574447d29a6 100644 --- a/docs/platforms/unity/data-management/sensitive-data/index.mdx +++ b/docs/platforms/unity/data-management/sensitive-data/index.mdx @@ -23,6 +23,23 @@ We offer the following options depending on your legal and operational needs: - [configuring server-side scrubbing](/security-legal-pii/scrubbing/server-side-scrubbing/) to ensure Sentry does _not store_ data. Configuration changes are done in the Sentry UI and apply immediately for new events. - [running a local Relay](/product/relay/) on your own server between the SDK and Sentry, so that data is _not sent to_ Sentry while configuration can still be applied without deploying. +## Scrubbing Data in the SDK + +To remove sensitive data before it leaves the device, use these callbacks: + +- [`SetBeforeSend`](/platforms/unity/configuration/options/#SetBeforeSend): edit or drop error events. +- [`SetBeforeBreadcrumb`](/platforms/unity/configuration/options/#SetBeforeBreadcrumb): edit or drop breadcrumbs. +- [`SetBeforeSendTransaction`](/platforms/unity/configuration/options/#SetBeforeSendTransaction): edit or drop transactions. +- `SetBeforeSendLog`: edit or drop logs. Learn more in [Logs](/platforms/unity/logs/#before-log-handler). +- [`SetBeforeCaptureScreenshot`](/platforms/unity/configuration/options/#SetBeforeCaptureScreenshot) and [`SetBeforeSendScreenshot`](/platforms/unity/configuration/options/#SetBeforeSendScreenshot): skip, edit, or drop screenshots. +- [`SetBeforeCaptureViewHierarchy`](/platforms/unity/configuration/options/#SetBeforeCaptureViewHierarchy) and [`SetBeforeSendViewHierarchy`](/platforms/unity/configuration/options/#SetBeforeSendViewHierarchy): skip, edit, or drop the view hierarchy. + + + +These callbacks run in C# only. Native crashes, from C and C++, Java and Kotlin, or Objective-C and Swift code, are captured by the native SDKs and don't run them. Breadcrumbs reach the native SDKs after `SetBeforeBreadcrumb` runs, so breadcrumbs you edit or drop there stay that way in native crashes. To remove other data from native crashes, use [server-side scrubbing](/security-legal-pii/scrubbing/server-side-scrubbing/). On iOS, setting `SetBeforeCaptureScreenshot` or `SetBeforeSendScreenshot` turns off screenshots for native crashes. On Windows, native crashes get a screenshot whenever `AttachScreenshot` is on. Learn more in [Screenshots](/platforms/unity/enriching-events/screenshots/#native-errors). + + + Ensure that your team is aware of your company's policy around what can and cannot be sent to Sentry. We recommend determining this policy early in your implementation and communicating it as well as enforcing it via code review. diff --git a/docs/platforms/unity/data-management/store-minidumps-as-attachments/index.mdx b/docs/platforms/unity/data-management/store-minidumps-as-attachments/index.mdx index 05a0db81eb930..04363fdd710a1 100644 --- a/docs/platforms/unity/data-management/store-minidumps-as-attachments/index.mdx +++ b/docs/platforms/unity/data-management/store-minidumps-as-attachments/index.mdx @@ -6,6 +6,9 @@ sidebar_order: 90 -☝ This feature is supported on Windows, Linux, and Android. + + ☝ This feature is supported on Windows, Linux, and macOS with the Native + backend. + diff --git a/docs/platforms/unity/enriching-events/attachments/index.mdx b/docs/platforms/unity/enriching-events/attachments/index.mdx index 6a982c9303b3d..4c015b0557b28 100644 --- a/docs/platforms/unity/enriching-events/attachments/index.mdx +++ b/docs/platforms/unity/enriching-events/attachments/index.mdx @@ -25,11 +25,7 @@ The filename is the name of the file to display in Sentry. When using bytes you `contentType` -The type of content stored in this attachment. Any [MIME type](https://www.iana.org/assignments/media-types/media-types.xhtml) may be used; the default is `application/octet-stream`. - -`mimetype` - -The specific media content type that determines how the attachment is rendered in the Sentry UI. We currently support and can render the following MIME types: +The type of content stored in this attachment. Any [MIME type](https://www.iana.org/assignments/media-types/media-types.xhtml) may be used; the default is `application/octet-stream`. The content type also determines how the attachment is rendered in the Sentry UI. Sentry can render the following MIME types: - `text/plain` - `text/css` @@ -49,6 +45,8 @@ The specific media content type that determines how the attachment is rendered i Unity features a global scope to which you add an attachment that will be sent with every event. +The SDK also syncs these attachments to the native SDK, so native crashes include them, except on iOS and on macOS with the default Cocoa backend. Learn more in Scope Sync. + @@ -65,7 +63,10 @@ Learn more about how attachments impact your [quota](/pricing/quotas/). -☝ This feature is supported on Windows, Linux, and Android. + + ☝ This feature is supported on Windows, Linux, and macOS with the Native + backend. + diff --git a/docs/platforms/unity/enriching-events/breadcrumbs/index.mdx b/docs/platforms/unity/enriching-events/breadcrumbs/index.mdx index df05624f6743d..892dd982c9bf2 100644 --- a/docs/platforms/unity/enriching-events/breadcrumbs/index.mdx +++ b/docs/platforms/unity/enriching-events/breadcrumbs/index.mdx @@ -27,7 +27,7 @@ Manually record a breadcrumb: ## Customize Breadcrumbs -SDKs allow you to customize breadcrumbs through the hook. +SDKs allow you to customize breadcrumbs through the hook. This hook is passed an already assembled breadcrumb and, in some SDKs, an optional hint. The function can modify the breadcrumb or decide to discard it entirely by returning `null`: diff --git a/docs/platforms/unity/enriching-events/context/index.mdx b/docs/platforms/unity/enriching-events/context/index.mdx index 69625e24f4f53..34146673896c4 100644 --- a/docs/platforms/unity/enriching-events/context/index.mdx +++ b/docs/platforms/unity/enriching-events/context/index.mdx @@ -27,8 +27,12 @@ The class must be serializable and only properties are included; fields are not. +Custom contexts are only added to C# events. Native crashes don't include them. Learn more in Scope Sync. + There are no restrictions on context name. In the context object, all keys are allowed except for `type`, which is used internally. +The SDK sets its own contexts, such as `app`, `os`, `device`, `gpu`, `runtime`, and `unity`. Don't use these names for your own contexts. Setting your own context under one of them replaces the SDK's context. For `app`, `device`, and `unity`, it also stops the SDK from adding its main-thread data, the active scene, and default tags to events. See the [list of data in these contexts](../../data-management/data-collected/#general-device-information). + Learn more about conventions for common contexts in the [contexts interface developer documentation](https://develop.sentry.dev/sdk/foundations/transport/event-payloads/contexts/). ## Size Limitations diff --git a/docs/platforms/unity/enriching-events/scopes/index.mdx b/docs/platforms/unity/enriching-events/scopes/index.mdx index c70db4f1f633c..5cdcab5fd46c3 100644 --- a/docs/platforms/unity/enriching-events/scopes/index.mdx +++ b/docs/platforms/unity/enriching-events/scopes/index.mdx @@ -1,44 +1,15 @@ --- -title: Scopes and Hubs -description: "SDKs will typically automatically manage the scopes for you in the framework integrations. Learn what a scope is and how you can use it to your advantage." +title: Scopes +description: "Learn what the scope is in the Sentry Unity SDK, and how to attach data to all events or to a single event." --- -When an event is captured and sent to Sentry, SDKs will merge that event data with extra -information from the current scope. SDKs will typically automatically manage the scopes -for you in the framework integrations and you don't need to think about them. However, -you should know what a scope is and how you can use it for your advantage. +When an event is captured and sent to Sentry, the SDK merges that event with the data stored on the scope, such as [tags](../tags/), [contexts](../context/), [breadcrumbs](../breadcrumbs/), and the [user](../identify-user/). -## What's a Scope, What's a Hub +## How the Scope Works -You can think of the hub as the central point that our SDKs use to route an -event to Sentry. When you call `init()` a hub is created and a client and a -blank scope are created on it. That hub is then associated with the current -thread and will internally hold a stack of scopes. +Unity runs in global mode, with one scope shared by every thread. Data you set on the scope stays there and is added to every event until you change or clear it. `PushScope` has no effect. -The scope will hold useful information that should be sent along with the -event. For instance [contexts](../context/) or -[breadcrumbs](../breadcrumbs/) are stored on -the scope. When a scope is pushed, it inherits all data from the parent scope -and when it pops all modifications are reverted. - -The default SDK integrations will push and pop scopes intelligently. For -instance web framework integrations will create and destroy scopes around your -routes or controllers. - -## How the Scope and Hub Work - -As you start using an SDK, a scope and hub are automatically created for you out -of the box. It's unlikely that you'll interact with the hub directly unless you're -writing an integration or you want to create or destroy scopes. Scopes, on the -other hand are more user facing. You can call at any point in -time to modify data stored on the scope. This is useful for doing things like -[modifying the context](../context/). - - - -When you call a global function such as internally Sentry -discovers the current hub and asks it to capture an event. Internally the hub will -then merge the event with the topmost scope's data. +Native crashes include most of this data too. Learn more in Scope Sync. ## Configuring the Scope @@ -52,14 +23,7 @@ You can also apply this configuration when unsetting a user at logout: -To learn what useful information can be associated with scopes see -[the context documentation](../context/). - -## Local Scopes - -We also support pushing and configuring a scope within a single call. This is typically -called , or implemented as a function parameter on the capture methods, depending on the SDK. It's very helpful if -you only want to send data for one specific event. +## Attaching Data to a Single Event ### Using Scope Callback Parameter diff --git a/docs/platforms/unity/enriching-events/screenshots/index.mdx b/docs/platforms/unity/enriching-events/screenshots/index.mdx index 514fba3fadf24..0d8eb18ef4bc5 100644 --- a/docs/platforms/unity/enriching-events/screenshots/index.mdx +++ b/docs/platforms/unity/enriching-events/screenshots/index.mdx @@ -16,9 +16,9 @@ Because screenshots may contain build time initialization | -| Windows | Captured by sentry-native when the game crashes | -| Android, macOS, Linux | None | +| Platform | Screenshot for native crashes | +| --------------------- | ----------------------------------------------- | +| iOS | Captured by sentry-cocoa when the game crashes | +| Windows | Captured by sentry-native when the game crashes | +| Android, macOS, Linux | None | + +Other events the native SDKs capture, such as failed HTTP requests captured by sentry-cocoa, don't get a screenshot. + +Native crash screenshots are taken by the native SDK in its crash handler, so they include overlays, and and can't run for them: -These screenshots are taken by the native SDK, so they include overlays, and and don't apply to them. +- On iOS, setting either callback turns native crash screenshots off, so a crash doesn't send a screenshot your callbacks would have skipped or masked. With build time initialization, the native SDK's options are fixed when you build, so only callbacks set in your [options configuration script](/platforms/unity/configuration/options/programmatic-configuration/) turn them off. +- On Windows, sentry-native attaches them whether or not these callbacks are set. diff --git a/docs/platforms/unity/enriching-events/tags/index.mdx b/docs/platforms/unity/enriching-events/tags/index.mdx index 9d4e08ef03bc7..ecb943f9064da 100644 --- a/docs/platforms/unity/enriching-events/tags/index.mdx +++ b/docs/platforms/unity/enriching-events/tags/index.mdx @@ -11,7 +11,7 @@ _Tag keys_ have a maximum length of 200 characters and can contain only letters _Tag values_ have a maximum length of 200 characters and they cannot contain the newline (`\n`) character. -Defining tags is easy, and will bind them to the [isolation scope](../scopes/) ensuring all future events within scope contain the same tags. +Tags are set on the [scope](../scopes/). In Unity, there's one scope shared by the whole game, so all future events contain the tags you set. Define the tag: diff --git a/docs/platforms/unity/enriching-events/view-hierarchy/index.mdx b/docs/platforms/unity/enriching-events/view-hierarchy/index.mdx index 239bd60ccbd47..65e020b3d24b4 100644 --- a/docs/platforms/unity/enriching-events/view-hierarchy/index.mdx +++ b/docs/platforms/unity/enriching-events/view-hierarchy/index.mdx @@ -9,7 +9,7 @@ og_image: /og-images/platforms-unity-enriching-events-view-hierarchy.png Sentry makes it possible to render a JSON representation of the scene of an error and includes it as an attachment. -This feature only applies to SDKs with a user interface, such as the ones for mobile and desktop applications. Capturing the scene and creating the view hierarchy requires the UI thread and in the event of a crash, that might not be available. Another example where the view hierarchy might not be available is when the event happens before the screen starts to load. So inherently, this feature is a best effort solution. +The SDK captures the view hierarchy of the active scene only, and only for events captured on the main thread. Events captured on background threads and native crashes don't get one. It works in the Unity Editor and on WebGL too. ## Enabling View Hierarchy Attachments @@ -17,29 +17,29 @@ View hierarchy debugging is an opt-in feature. You can enable attaching the view ![Options Screenshot Configuration](./img/editor-window.png) -Or, like so, if you're [configuring things programmatically](/platforms/unity/configuration/options/): +Or, like so, if you're [configuring things programmatically](/platforms/unity/configuration/options/programmatic-configuration/): -```csharp {tabTitle:ScriptableOptionsConfiguration} +```csharp options.AttachViewHierarchy = true; ``` -### Customize View Hierarchy Capturing +## Customize View Hierarchy Capturing Because capturing view hierarchy can be a resource-intensive operation as the SDK traverses the scene at the time of an error, there are several controls available to you. - + Allows you to limit the amount of gameobjects to be traversed and included in the view hierarchy. - + Allows you to limit the maximum depth of child-gameobject the SDK will attempt to traverse to include in the view hierarchy. - + Allows you to limit the maximum count of child-gameobjects per individual gameobject the SDK will attempt to include in the view hierarchy. @@ -53,6 +53,33 @@ options.MaxViewHierarchyRootObjects = 100; options.MaxViewHierarchyObjectChildCount = 20; ``` +To decide whether an event gets a view hierarchy, use . Return `false` to skip it: + +```csharp +options.SetBeforeCaptureViewHierarchy(sentryEvent => +{ + // Don't capture the view hierarchy for warnings + return sentryEvent.Level != SentryLevel.Warning; +}); +``` + +## Modifying or Discarding the View Hierarchy + +To edit the view hierarchy before it's sent, or to discard it, use . Return `null` to discard it: + +```csharp +options.SetBeforeSendViewHierarchy((viewHierarchy, sentryEvent) => +{ + // The root node is the scene, and its children are the root GameObjects + foreach (var scene in viewHierarchy.Windows) + { + scene.Children.RemoveAll(node => node.Type == "AccountScreen"); + } + + return viewHierarchy; +}); +``` + ## Viewing View Hierarchy Attachments View hierarchies appear in the "Attachments" tab, where you can view all attachments, as well as associated events. Click the event ID to open the [Issue Details](/product/issues/issue-details/) page of that specific event. @@ -61,12 +88,12 @@ View hierarchies appear in the "Attachments" tab, where you can view all attachm On the **Issue Details** page, you can interact with the view hierarchy attachment in a section called "View Hierarchy". This section represents the state of your scene at the time of an error event. There are two displays: a tree view, and detailed view for a selected node. You can select nodes in the tree to view the properties collected by the SDK. The SDK will report on the following keys for each node in the view: -- `Tag` The gameobject's tag -- `Position` The gameobject's position -- `Rotation` The gameobject's rotation in euler angles -- `Scale` The gameobject's scale -- `Active` Whether the gameobject was active -- `Extra` A list of names of all the attached MonoBehaviours on that gameobject +- `tag` The gameobject's tag +- `position` The gameobject's position +- `rotation` The gameobject's rotation in euler angles +- `scale` The gameobject's local scale +- `active` Whether the gameobject itself was active (`activeSelf`) +- `extras` The type names of all components attached to the gameobject This feature can be used as an exploratory tool to debug reference issues, or gain a better understanding of the relationship between gameobjects. diff --git a/docs/platforms/unity/game-consoles/index.mdx b/docs/platforms/unity/game-consoles/index.mdx index be9474806d23a..f31a56bd5cec9 100644 --- a/docs/platforms/unity/game-consoles/index.mdx +++ b/docs/platforms/unity/game-consoles/index.mdx @@ -34,14 +34,26 @@ Each console has a different crash capture model: Sentry supports [PlayStation](/platforms/playstation/), [Xbox](/platforms/xbox/) and [Nintendo Switch](/platforms/nintendo-switch/) via the Unity SDK. Once you submit the middleware verification process, we'll reach out and send you an invite to our private GitHub repositories with console-specific code. This allows your configuration and custom data set via C# to show up in C# exceptions as well as crash dumps on these console platforms. +The automated debug symbol upload covers console builds, too. + ## Nintendo Switch +On Nintendo Switch and Nintendo Switch 2, the SDK: + +- Sets `DisableFileWrite`, because file access is limited, so there's no offline caching +- Turns off automatic session tracking, for the same reason +- Turns off IL2CPP line numbers, which aren't available on Switch + +Set `TemporaryStorageSize` in your game's `.nmeta` file. The SDK needs temporary storage to start the native SDK. Without it, the SDK skips native initialization, and native crashes don't include the scope you set in C#. + ## Xbox +The SDK stores its data in Xbox Persistent Local Storage. Configure `PersistentLocalStorage` in your game's `MicrosoftGame.config`. Without it, the SDK runs without offline caching, session persistence, or native crash reporting. + ## PlayStation diff --git a/docs/platforms/unity/logs/index.mdx b/docs/platforms/unity/logs/index.mdx index ec81b6339cb44..2235ec75273ff 100644 --- a/docs/platforms/unity/logs/index.mdx +++ b/docs/platforms/unity/logs/index.mdx @@ -35,6 +35,6 @@ With Sentry Structured Logs, you can send text-based log information from your U ## Performance Considerations - Logs are sent asynchronously to avoid impacting game performance -- Consider disabling Debug level logs in production to avoid excessive log volume +- `Debug.Log` calls are sent at `Info` level and aren't forwarded by default. Keep them off in production to limit log volume - Each severity level can be individually controlled to fine-tune what gets sent to Sentry - Before-log handlers are executed synchronously, so keep processing lightweight diff --git a/docs/platforms/unity/metrics/index.mdx b/docs/platforms/unity/metrics/index.mdx index 2d7413d8daa05..364c45f5fc0ac 100644 --- a/docs/platforms/unity/metrics/index.mdx +++ b/docs/platforms/unity/metrics/index.mdx @@ -21,6 +21,43 @@ With Sentry's [Application Metrics](/product/metrics/), you can send counters, g +## Automatic Game Metrics + + + +Automatic game metrics are experimental. + + + +The SDK can collect common game performance metrics for you. Each kind is off by default. Turn it on in **Tools > Sentry > Advanced > Metrics**, or in code with the options below. + +| Option | Interval option | Metrics | +| ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | +| `AutoFrameMetrics` | `FrameMetricsInterval` | `game.perf.frame_time`, `game.perf.fps`, `game.perf.game_thread`, `game.perf.render_thread` | +| `AutoMemoryMetrics` | `MemoryMetricsInterval` | `game.perf.used_memory`, `game.perf.reserved_memory`, `game.perf.mono_used_memory` | +| `AutoGcMetrics` | `GcMetricsInterval` | `game.perf.gc_collections` | +| `AutoNetworkMetrics` | `NetworkMetricsInterval` | `game.perf.net.ping`, `game.perf.net.num_clients` | + +- `game.perf.game_thread` and `game.perf.render_thread` need Unity 2022 or later. +- Network metrics need the Netcode for GameObjects package. Clients send `game.perf.net.ping`, and the server sends `game.perf.net.num_clients`. + +```csharp +public override void Configure(SentryUnityOptions options) +{ + options.AutoFrameMetrics = true; + options.AutoMemoryMetrics = true; +} +``` + +Automatic metrics have these attributes. The SDK leaves out `gpu.name`, `cpu.cores`, and `ram.gb` when the value isn't available. + +- `gpu.name` +- `cpu.cores` +- `ram.gb` +- `res.x` and `res.y`, the screen resolution +- `platform` +- `map`, the name of the active scene + ## Options diff --git a/docs/platforms/unity/migration/index.mdx b/docs/platforms/unity/migration/index.mdx index 29a2481ec7fc6..cf2e63531c7bb 100644 --- a/docs/platforms/unity/migration/index.mdx +++ b/docs/platforms/unity/migration/index.mdx @@ -7,9 +7,34 @@ sidebar_section: configuration ## Migrating to 4.0.0 +### Static API moved to `Sentry.Unity` + +The SDK's static API has moved from `Sentry.Unity.SentryUnity` and `Sentry.SentrySdk` to `Sentry.Unity.SentrySdk`. The underlying .NET SDK's `SentrySdk` class is now internal, so code with only `using Sentry;` no longer compiles. + +Update your `using` directives and replace calls to `SentryUnity`: + +**Before:** +```csharp +using Sentry; +using Sentry.Unity; + +SentryUnity.Init(options => options.Dsn = "___PUBLIC_DSN___"); +SentrySdk.CaptureMessage("Test event"); +``` + +**After:** +```csharp +using Sentry.Unity; + +SentrySdk.Init(options => options.Dsn = "___PUBLIC_DSN___"); +SentrySdk.CaptureMessage("Test event"); +``` + +Calls such as `SentrySdk.CaptureException()` stay the same. Keep `using Sentry;` as well if you use types from that namespace, like `SentryId` or `SentryLevel`. + ### Minimum Unity version -Unity 2020 support has been removed as it reached End of Life in 2023. The minimum supported version is now Unity 2021. +Unity 2020 support has been removed as it reached End of Life in 2023. The minimum supported version is now Unity 2021.3. ### Ubuntu version requirement for Linux servers @@ -17,10 +42,12 @@ If you are running your game on a Linux server, note that `sentry-native` is now ### Programmatic configuration changes -The deprecated `RuntimeConfiguration` and `BuildtimeConfiguration` classes have been removed. You must now use the single `OptionsConfiguration` script for all programmatic configuration. Use preprocessor directives to set platform-specific options: +The deprecated `RuntimeConfiguration` and `BuildtimeConfiguration` classes have been removed. You must now use a single options configuration script, deriving from `SentryOptionsConfiguration`, for all programmatic configuration. Use preprocessor directives to set platform-specific options: ```csharp -public class SentryOptionsConfiguration : OptionsConfiguration +using Sentry.Unity; + +public class MyOptionsConfiguration : SentryOptionsConfiguration { public override void Configure(SentryUnityOptions options) { @@ -92,12 +119,8 @@ SentrySdk.CaptureUserFeedback(new UserFeedback(eventId, "user@example.com", "Use **After:** ```csharp -var feedbackResult = SentrySdk.CaptureFeedback(new UserFeedback -{ - Email = "user@example.com", - Message = "User comment", - Name = "User Name" -}, out var captureResult); +var feedback = new SentryFeedback("User comment", "user@example.com", "User Name", associatedEventId: eventId); +var feedbackId = SentrySdk.CaptureFeedback(feedback, out var captureResult); ``` Note that `CaptureFeedback` now returns a `SentryId` and provides a `CaptureFeedbackResult` out parameter to indicate capture success or failure reason. @@ -143,6 +166,10 @@ Backpressure handling is now enabled by default. The SDK will monitor system hea The SDK now always adds a breadcrumb when capturing an exception. The option to opt-out of this behavior has been removed. +### Renamed options + +The option `AttachBreadcrumbsToEvents` has been renamed to `AddBreadcrumbsWithStructuredLogs`. It controls whether logs that are sent as structured logs are also added as breadcrumbs. + ### Tag changes The SDK no longer sets tags automatically. Tag promotion from contexts now happens exclusively in Sentry. The following tags have been removed: @@ -167,7 +194,7 @@ To restore the previous behaviour, you can set the `IosNativeInitializationType` The Runtime- and BuildTime-Configuration have been merged into a single OptionsConfiguration script. This allows for programmatic configuration of the SDK in one place using preprocessor directives instead of having to duplicate setting options in two different files. -You can still use the old configuration classes, but they have been deprecated and will be removed in a future version. Going forward, you should use the new OptionsConfiguration script and make use of the preprocessor directives when setting options for different platforms. +The old configuration classes were deprecated in this version and removed in 4.0.0. Use a single options configuration script and preprocessor directives to set options for different platforms. ## Migrating to 0.28.0 @@ -184,20 +211,19 @@ If you make use of the programmatic configuration, you'll need to update your im ### Programmatic Configuration Changes -You no longer need to to call `SentryUnity.Init`. Instead, you can let the SDK self-initialize and modify the options taken from the Sentry Unity editor configuration window by providing a `ScriptableOptionsConfiguration` object. +You no longer need to call `SentryUnity.Init`. Instead, you can let the SDK self-initialize and modify the options taken from the Sentry Unity editor configuration window by providing a `ScriptableOptionsConfiguration` object. - Open the Sentry Unity editor configuration window. - Go to the `Options Config` tab. -- Click `Create options configuration`. - - This will prompt you to pick a location for your version of the scriptable options configuration script. - - It will also create an instance of the ScriptableOptionsConfiguration and set in it the configuration window. +- Click **New** next to **Option Config Script**. + - This creates a script deriving from `SentryOptionsConfiguration` and an instance of it, and sets it in the configuration window. - Add your code to the newly created script. Learn more in our [options documentation](/platforms/unity/configuration/options/). ## Migrating From 0.7.0 or Earlier -Starting from version 0.7.0, the SDK is [aliasing](https://blog.sentry.io/2022/02/24/alias-an-approach-to-net-assembly-conflict-resolution) its dependencies. We do this to avoid creating conflicts with other packages. This also means that if you were relying on our dependencies for certain types like `System.Text.Json`, then you'll have to import them into your project yourself going forward. +Starting from version 0.7.0, the SDK is [aliasing](https://blog.sentry.io/alias-an-approach-to-net-assembly-conflict-resolution/) its dependencies. We do this to avoid creating conflicts with other packages. This also means that if you were relying on our dependencies for certain types like `System.Text.Json`, then you'll have to import them into your project yourself going forward. ## Migrating From 0.3.0 or Earlier @@ -210,7 +236,7 @@ The Sentry SDK deprecated the use of JSON files to store options and now uses sc The Sentry Unity Lite SDK is deprecated for mobile, desktop, WebGL, and console players. Customers using Unity 5.x can still use the Sentry Unity Lite as it continues to be compatible with sentry.io. -The updated Sentry Unity SDK requires Unity version 2019.4 or higher with .NET Standard 2.0 scripting profile. +The updated Sentry Unity SDK requires Unity 2021.3 or higher. diff --git a/docs/platforms/unity/native-support/index.mdx b/docs/platforms/unity/native-support/index.mdx index db80c74fd259e..7e21336ef4ce6 100644 --- a/docs/platforms/unity/native-support/index.mdx +++ b/docs/platforms/unity/native-support/index.mdx @@ -5,13 +5,50 @@ sidebar_order: 100 sidebar_section: features --- -The Sentry SDK supports C# and Native crashes on Android, iOS, Windows, macOS and Linux. The support is set to `enabled` by default. -For Game Consoles, the SDK supports C# errors. While Sentry supports native crashes on consoles, support for that through the Unity SDK is a work in progress. Reach out via GitHub for the platform you're interested in: [PlayStation](https://github.com/getsentry/sentry-unity/issues/2050), [Switch](https://github.com/getsentry/sentry-unity/issues/2052) and [Xbox](https://github.com/getsentry/sentry-unity/issues/2051) +The Unity SDK captures C# errors on every platform it supports. On most platforms, it also includes a native SDK that captures native crashes, such as crashes in the Unity engine or in native plugins. Native support is on by default. + +## Supported Platforms + +| Platform | Native crashes | Native SDK | Requirements | +| ---------------------------------- | -------------- | ------------------------------------------------------------------- | ----------------------- | +| Android | Yes | sentry-java with the NDK integration | IL2CPP | +| iOS | Yes | sentry-cocoa | | +| Windows (x64, x86) | Yes | sentry-native with Crashpad, or the experimental Native backend | | +| macOS | Yes | sentry-cocoa, or sentry-native with the experimental Native backend | IL2CPP for sentry-cocoa | +| Linux (x86_64, ARM64) | Yes | sentry-native with Breakpad, or the experimental Native backend | | +| Xbox, PlayStation, Nintendo Switch | Yes | See Game Consoles | | +| WebGL | No | | | +| visionOS, UWP | No | | | + +On visionOS and UWP, the SDK runs on a best-effort basis, without offline caching or session tracking. The SDK supports Unity 2021.3 and later. Dedicated server builds for Windows, macOS, and Linux get the same native support as players. On consoles, the SDK supports Xbox with the GDK, PlayStation 5, Nintendo Switch, and Nintendo Switch 2. The SDK doesn't support PlayStation 4, Xbox One without the GDK, tvOS, Embedded Linux, or Cloud Rendering. + +## Scope Sync + +The SDK syncs the scope you set in C# to the native SDK, so native crashes include it. It syncs: + +- Breadcrumbs +- Tags +- Extras +- User +- Environment +- Trace +- Attachments + +Some scope data doesn't reach native crashes: + +- Custom contexts you set through `scope.Contexts`. The SDK only syncs the contexts it collects itself, such as device and app data. +- Attachments on iOS, and on macOS with the default Cocoa backend. +- With Unity as a Library, the app's own SDK owns part of the scope. On iOS, that's the user, environment, and trace. On Android, it's the trace, and the user when the game runs in the app's process. +- On Android, setting `NdkScopeSyncEnabled` to `false` turns off scope sync for NDK crashes. ## Mobile The native crash support for Android and iOS is provided by adding platform-specific SDKs to the generated Xcode and Gradle projects at build time. +Android native support requires the IL2CPP scripting backend. With Mono, the SDK captures C# errors only. + +On Android, `NdkIntegrationEnabled`, `NdkScopeSyncEnabled`, `AndroidTombstoneEnabled`, and `AndroidReportHistoricalTombstones` control the NDK integration and tombstone reporting. On iOS, `IosWatchdogTerminationIntegrationEnabled` controls watchdog termination reporting. Learn more in Options. + ### Initialization of the Native SDKs The [iOS SDK](/platforms/apple/guides/ios/) and [Android SDK](/platforms/android/) are capable of self-initializing before the Unity engine itself is started. This allows us to capture bugs/crashes happening within the engine itself. @@ -21,6 +58,8 @@ There are three initialization types: - `NativeInitializationType.BuildTime`: Native SDKs initialize before Unity engine starts - `NativeInitializationType.External`: The app that embeds the game provides and initializes the native SDKs, when using Unity as a Library +Set the type with the `AndroidNativeInitializationType` and `IosNativeInitializationType` options in an [options configuration script](/platforms/unity/configuration/options/programmatic-configuration/). Both default to `Runtime`. + ### Runtime Initialization (Default) With runtime initialization, the native SDKs are initialized at runtime alongside the C# SDK. This allows all options to be dynamically configured through C# code during execution. @@ -31,7 +70,7 @@ At build time, the SDK modifies the generated Gradle project to include the Andr #### iOS -At built time, the SDK modifies the generated Xcode project to include the iOS SDK but will not modify the `main.m` file or write the options to file. The Unity SDK will then initialize the iOS SDK when it initializes itself. +At build time, the SDK modifies the generated Xcode project to include the iOS SDK but will not modify the `main.mm` file or write the options to file. The Unity SDK will then initialize the iOS SDK when it initializes itself. ### Build Time Initialization @@ -43,7 +82,7 @@ The SDK modifies the generated Gradle project to include the Android SDK. At bui #### iOS -The SDK modifies the generated Xcode project to include the iOS SDK. It adds the initialization code to the `main.m` and generates the options provided by the editor configuration window as `SentryOptions.m`. The SDK also copies the `SentryNativeBridge` that enables the C# layer to communicate with the iOS SDK. This means that there's no need to use the Unity [built-in crash reporting](https://docs.unity3d.com/ScriptReference/CrashReport.html) functionality. +The SDK modifies the generated Xcode project to include the iOS SDK. It adds the initialization code to the `main.mm` and generates the options provided by the editor configuration window as `SentryOptions.m`. The SDK also copies the `SentryNativeBridge` that enables the C# layer to communicate with the iOS SDK. This means that there's no need to use the Unity [built-in crash reporting](https://docs.unity3d.com/ScriptReference/CrashReport.html) functionality. The [iOS SDK](/platforms/apple/guides/ios/) supports capturing Objective-C exceptions which are disabled in the generated Xcode project by default. Consider enabling them in the "Build Settings" tab by setting `GCC_ENABLE_OBJC_EXCEPTIONS` to true. @@ -55,13 +94,21 @@ When your game runs inside an iOS or Android app with Unity as a Library, the ap The native support is configured and enabled as early as possible by the C# layer, right after the Unity engine starts. This is slightly different from on mobile where we inject native initialization code that runs before the Unity engine runs. +Native support on Windows, Linux, and macOS with the Native backend writes files to disk. If you set `DisableFileWrite`, the SDK turns native support off on these platforms. + +With an out-of-process crash handler (Crashpad on Windows, or the Native backend), `NativeHandlerPath` sets where the SDK looks for the handler executable. By default, it's next to the player executable. Learn more in Options. + ### Windows -On Windows, the Unity SDK includes the [Native SDK](/platforms/native/) with the crashpad backend. Windows native crashes are automatically captured through minidumps. To upload these to Sentry, the SDK copies the `crashpad_handler.exe` to the build output directory at the end of the build process. This executable must be included when shipping your game. +On Windows, the Unity SDK includes the [Native SDK](/platforms/native/) with the Crashpad backend, for both 64-bit (x64) and 32-bit (x86) players. Windows native crashes are captured through minidumps. At the end of the build, the SDK copies `crashpad_handler.exe`, `crashpad_wer.dll`, and `sentry-native.dll` next to the player. Include all three files when you ship your game. + +With the Native backend, which you can select with `options.Experimental.WindowsBackend = WindowsBackend.Native`, the SDK uploads crashes right away through the out-of-process `sentry-crash.exe` handler. The build copies `sentry-crash.exe`, `sentry-wer.dll`, and `sentry-native.dll` next to the player instead. Include all three files when you ship your game. ### macOS -The Native Support on macOS relies on the [macOS SDK](/platforms/apple/guides/macos/). Stackwalking happens in process. +By default, native support on macOS relies on the [macOS SDK](/platforms/apple/guides/macos/). Stackwalking happens in process. This Cocoa backend needs IL2CPP. With Mono, the SDK captures C# errors only. + +With the Native backend, which you can select with `options.Experimental.MacosBackend = MacosBackend.Native`, the SDK uses the [Native SDK](/platforms/native/) instead. It uploads crashes right away through the out-of-process `sentry-crash` handler, which the build copies next to the player, and it works with both IL2CPP and Mono. ### Linux @@ -71,35 +118,70 @@ The Native SDK ships for `x86_64` and `ARM64`, and the build picks the one that ## Debug Symbols -Sentry requires [debug information files](/platforms/unity/data-management/debug-files/) to symbolicate your crashes. The Unity SDK provides an automated upload functionality for those symbol files that rely on the [sentry-cli](/cli/). This is done transparently so you're not required to run `sentry-cli` manually. The symbol upload happens during Unity build in the editor. We've included the executables for Windows, macOS, and Linux as part of the Unity SDK package. +Sentry requires [debug information files](/platforms/unity/data-management/debug-files/) to symbolicate your crashes. The Unity SDK uploads them for you with [sentry-cli](/cli/), so you don't need to run `sentry-cli` yourself. The SDK package includes `sentry-cli` for Windows, macOS, and Linux. -The automated debug symbols upload is enabled by default but requires configuration. Go to **Tools > Sentry > Editor** to enter the [Auth Token](https://sentry.io/orgredirect/organizations/:orgslug/settings/auth-tokens/), Organization Slug, and the Project Name. Note that the Unity SDK creates a file at `Assets/Plugins/Sentry/SentryCliOptions.asset` to store the configuration, that should **not** be made publicly available. +The automated upload is on by default, but it needs your credentials. Go to **Tools > Sentry**, open the **Debug Symbols** tab, and enter your [Auth Token](https://sentry.io/orgredirect/organizations/:orgslug/settings/auth-tokens/) and the Project Name. Enter the Org Slug too, unless the auth token is an organization token. The SDK stores this configuration in `Assets/Plugins/Sentry/SentryCliOptions.asset`. Don't make this file publicly available. To set the auth token from code instead, for example from an environment variable in CI, see [Sentry CLI Options](/platforms/unity/configuration/options/cli-options/#programmatic-configuration). -### iOS - dSYM +The SDK uploads debug symbols for release builds. To also upload them for development builds, enable **Upload Dev Symbols**. + +Where the upload runs depends on the platform: + +| Platform | Where the upload runs | Condition | Log | +| -------------------------------------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| Windows, macOS, Linux, Xbox, PlayStation 5, Switch | In the Unity Editor, after the build | Sentry enabled with a DSN | Unity Console | +| Android | In the Gradle build | Sentry enabled, IL2CPP, and Android native support enabled | `Logs/sentry-symbols-upload.log` in your Unity project, and `Logs/sentry-mapping-upload.log` with minification enabled | +| iOS | In an Xcode build phase | Sentry configured in **Tools > Sentry**, also when Sentry or iOS native support is disabled | `sentry-symbols-upload.log` in the root of the Xcode project | +| WebGL | No upload | | | + +If you export a Gradle or Xcode project instead of building the app in Unity, the upload runs when you build the exported project. For exported Gradle projects, the SDK doesn't write the log files; the upload output is in the Gradle build output. The exported Gradle project contains the `sentry-cli` for the operating system you exported it from, so build it on that operating system. The exported Xcode project contains the macOS `sentry-cli`. + + + +Exported Xcode and Gradle projects contain a `sentry.properties` file with your auth token in plain text. Don't commit this file to version control. The file is in the root of the Xcode project and in the `launcher` module of the Gradle project, or in the `unityLibrary` module for [Unity as a Library](/platforms/unity/native-support/unity-as-a-library/). + + -Debug information files on the iOS platform are called dSYM. +### iOS - dSYM -For Sentry to symbolicate your crash logs we need two types of files: +Debug information files on Apple platforms are called dSYMs. The SDK adds a build phase to the Xcode project that uploads the dSYMs from the build output when Xcode builds the app. You don't need to do anything else. -1. `dSYM` that the automated symbols upload will pick up at the end of the build process without further action required. -2. `BCSymbolMap` files that are created during the archiving process +### Android - ProGuard and R8 -The automated symbol upload will take care of the `BCSymbolMap` files by processing them during the archiving process. +The SDK adds its ProGuard rules, `proguard-sentry-unity.pro`, to the Gradle project. If you enable **Minify** in **Player Settings > Publishing Settings**, the Gradle build also uploads the ProGuard mapping file, so Sentry can deobfuscate Java stack traces. With [Unity as a Library](/platforms/unity/native-support/unity-as-a-library/), the app that embeds the game minifies the code, so upload the mapping file from that app's build. ### Manual Upload Using sentry-cli -If you don't want to rely on the automated symbol upload, you can run `sentry-cli` through the commandline. For that, you can use the provided executables from within the package or follow the [sentry-cli documentation](/cli/installation/) to make it available globally. To upload debug symbols, run it with: +If you don't want to rely on the automated upload for desktop and console builds, you can run `sentry-cli` from the command line. Use the executables in the SDK package, or follow the [sentry-cli documentation](/cli/installation/) to install it globally. To upload your game's debug symbols, run: ```bash -sentry-cli --auth-token ___ORG_AUTH_TOKEN___ debug-files upload --org ___ORG_SLUG___ --project ___PROJECT_SLUG___ PATH_TO_SYMBOLS +sentry-cli --auth-token ___ORG_AUTH_TOKEN___ debug-files upload --il2cpp-mapping --org ___ORG_SLUG___ --project ___PROJECT_SLUG___ PATH_TO_BUILD_OUTPUT ``` +`sentry-cli` scans `PATH_TO_BUILD_OUTPUT` recursively. Point it at the folder that contains your build and the `_BackUpThisFolder_ButDontShipItWithYourGame` and `_BurstDebugInformation_DoNotShip` folders that Unity creates next to it. These folders hold the IL2CPP output and the Burst debug information. + +- `--il2cpp-mapping` uploads the line mapping that Sentry needs for [C# line numbers in IL2CPP builds](/platforms/unity/configuration/il2cpp/). Leave it out for Mono builds. +- `--include-sources` is optional. It uploads your source code so Sentry can show [source context](/platforms/unity/data-management/debug-files/source-context/). + +The build folder doesn't contain the symbols of the Sentry native SDK. The automated upload also uploads them from the SDK package, so upload them too if you want symbolicated frames from the Sentry native SDK: + +- Windows: the `.pdb` files in `Plugins/Windows/Sentry~/` or `Plugins/Windows/SentryNative~/`, in the `x64` or `x86` subfolder +- Linux: the `.dbg` and `.dbg.so` files in `Plugins/Linux/Sentry~/` or `Plugins/Linux/SentryNative~/`, in the `x86_64` or `ARM64` subfolder +- macOS: the `.dSYM` folders in `Plugins/macOS/Sentry~/` or `Plugins/macOS/SentryNative~/` +- Consoles: your project's `Assets/Plugins/Sentry/` folder, and for a Nintendo Switch NSP build, `Library/Bee/artifacts/PlayerBuildProgram`, because the NSP packs the assemblies + +These paths are relative to the SDK package. If you installed the SDK with UPM, the package is in `Library/PackageCache/` in your Unity project. + +For Android and iOS, rely on the automated upload. On Android, it uploads the symbols from `Library/Bee/` in your Unity project. On iOS, it uploads them from the Xcode build output. + ## Store Minidumps as Attachments -☝ This feature is supported on Windows, Linux, and Android. + + ☝ This feature is supported on Windows, Linux, and macOS with the Native + backend. + diff --git a/docs/platforms/unity/tracing/index.mdx b/docs/platforms/unity/tracing/index.mdx index 2cd21794a53df..a29b48de1602d 100644 --- a/docs/platforms/unity/tracing/index.mdx +++ b/docs/platforms/unity/tracing/index.mdx @@ -6,7 +6,7 @@ sidebar_order: 4000 sidebar_section: features --- -With [tracing](/product/dashboards/sentry-dashboards/), Sentry is able to [connect events coming from different parts of your game](/platforms/unity/usage/automatic-error-capture/#connecting-errors-captured-on-different-layers), whether it's native plugins or a backend. It helps you debug hard problems that involve C# scripts as well as the native layer on all platforms. It also allows you to monitor your game's performance, measuring metrics like initialization time, time spent on scene loading, and ANRs. Besides connecting different errors together, Sentry captures distributed traces consisting of transactions and spans, which measure individual services and individual operations within those services. Learn more about our model in [Distributed Tracing](/concepts/key-terms/tracing/distributed-tracing/). +With [tracing](/product/dashboards/sentry-dashboards/), Sentry is able to [connect events coming from different parts of your game](/platforms/unity/usage/automatic-error-capture/#connecting-errors-captured-on-different-layers), whether it's native plugins or a backend. It helps you debug hard problems that involve C# scripts as well as the native layer on all platforms. It also allows you to monitor your game's performance, measuring metrics like initialization time and time spent on scene loading. Besides connecting different errors together, Sentry captures distributed traces consisting of transactions and spans, which measure individual services and individual operations within those services. Learn more about our model in [Distributed Tracing](/concepts/key-terms/tracing/distributed-tracing/). @@ -23,6 +23,8 @@ First, enable tracing and configure the sample rate for transactions. Set the sa The two options are meant to be mutually exclusive. If you set both, will take precedence. +If you only set a , the SDK doesn't create the automatic transactions. + Learn more about tracing options, how to use the TracesSampler function, or how to sample transactions. diff --git a/docs/platforms/unity/tracing/instrumentation/automatic-instrumentation.mdx b/docs/platforms/unity/tracing/instrumentation/automatic-instrumentation.mdx index 96c62099fa68e..9c7b6ab804655 100644 --- a/docs/platforms/unity/tracing/instrumentation/automatic-instrumentation.mdx +++ b/docs/platforms/unity/tracing/instrumentation/automatic-instrumentation.mdx @@ -8,20 +8,33 @@ og_image: >- ## Automatically Captured Transactions -The Unity SDK automatically creates transactions for the game's startup and scene loading. +The Unity SDK can automatically instrument: -If you want the SDK to also generate spans for all `Awake` calls during startup and scene operations, you can enable the following settings through the Editor Config Window or programmatically. +| What | Option | Default | +| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| The game's startup | `AutoStartupTraces` | `true` | +| Scene loading | `AutoSceneLoadTraces` | `true` | +| Spans for `Awake` calls during startup and scene loading | `PerformanceAutoInstrumentationEnabled` | `false` | + +All three need to be greater than `0`. The SDK doesn't create startup transactions in the editor, on WebGL, or when you initialize the SDK yourself after the first scene has loaded. + +Set these options under **Auto Instrumentation** on the **Core** tab of **Tools > Sentry**, or in your options configuration script: ![Select automatically generated transactions.](./auto-transaction-config.png) ```csharp public override void Configure(SentryUnityOptions options) { - options.AutoSceneLoadTraces = true; - options.AutoStartupTraces = true; + options.PerformanceAutoInstrumentationEnabled = true; } ``` +The SDK adds the `Awake` spans when you build the game, by modifying the compiled code. It only instruments classes in `Assembly-CSharp` that inherit directly from `MonoBehaviour`. Because the SDK reads `PerformanceAutoInstrumentationEnabled` during the build, set it in the editor or in your options configuration script. Setting it in `SentrySdk.Init` has no effect. + After you've configured your instrumentation, the Unity SDK will generate traces as shown in the image below. ![Sample startup transaction.](./startup-transaction.png) + +## Scene Loading and `SceneManagerAPI` + +To trace scene loading, the SDK sets `SceneManagerAPI.overrideAPI` and replaces any override you set before. If your game uses its own `SceneManagerAPI` override, set `AutoSceneLoadTraces` to `false`. diff --git a/docs/platforms/unity/troubleshooting/index.mdx b/docs/platforms/unity/troubleshooting/index.mdx index 57557090d8f44..cf4906d992d86 100644 --- a/docs/platforms/unity/troubleshooting/index.mdx +++ b/docs/platforms/unity/troubleshooting/index.mdx @@ -34,6 +34,21 @@ You can resolve this issue by creating a clean build or choosing "Replace" when This happens if you've copied some of the SDK files directly to the Assets folder. You can resolve this issue by installing the SDK with UPM. +## Debug Symbol Upload + +If stack traces in Sentry are missing function names or line numbers, check the output of the debug symbol upload. The [Debug Symbols table](/platforms/unity/native-support/#debug-symbols) lists where the upload runs on each platform and where to find its log. + +If the upload doesn't run at all, check that: + +- Sentry is enabled and the DSN is set. Desktop and console builds skip the upload otherwise, and Android builds skip it if Sentry is disabled. +- **Upload Symbols** is enabled on the **Debug Symbols** tab in **Tools > Sentry**. +- The **Auth Token** and **Project Name** are set. +- For development builds, **Upload Dev Symbols** is enabled. + +If the upload runs but fails, check that the **Org Slug** is set, unless the auth token is an organization token. + +If you enable **Ignore CLI Errors**, the SDK passes `--allow-failure` to `sentry-cli`, so upload errors don't fail the build. Check the log to make sure the upload worked. On iOS, `sentry-symbols-upload.log` then only contains what `sentry-cli` writes to stderr, and the rest of the upload output is in the Xcode build output, so check both. + ## Runtime issues ### Android: Initialization fails - APK+OBB @@ -45,7 +60,8 @@ When exporting your Unity project as APK+OBB, the `ScriptableSentryOptions` conf Instead of relying on the ScriptableObject configuration and auto-initialization, you can manually initialize the SDK from your code: ```csharp -using Sentry; +using Sentry.Unity; +using UnityEngine; public class GameInitializer : MonoBehaviour { @@ -53,7 +69,7 @@ public class GameInitializer : MonoBehaviour { SentrySdk.Init(options => { - options.Dsn = "YOUR_DSN_HERE"; + options.Dsn = "___PUBLIC_DSN___"; options.Debug = true; // Add other configuration options as needed }); @@ -61,20 +77,19 @@ public class GameInitializer : MonoBehaviour } ``` -Since this way the options are embedded in code, the reliance on the `/Resources` being available at the time of initialization falls away. -Prior to version `4.0.0`, native support is limited when programmatically initializing the SDK. +Since this way the options are embedded in code, the reliance on the `/Resources` being available at the time of initialization falls away. Unlike regular [manual initialization](/platforms/unity/configuration/options/programmatic-configuration/#manual-initialization), keep **Enable Sentry** checked in the editor window: the SDK can't load its options from the OBB, so your `SentrySdk.Init` call is the only one, and the build still sets up native support. -### Library not loaded: @rpath/Sentry.framework/Sentry +### Library not loaded: @rpath/SentryObjC.framework/SentryObjC If you encounter the following error: ``` -2021-10-29 15:21:40.011452-0400 MyApp[2180:186329] Error loading /var/containers/Bundle/Application/88CC4619-7C5D-4BB1-9F4B-5AAD7EC4BF9C/MyApp.app/Frameworks/UnityFramework.framework/UnityFramework: dlopen(/var/containers/Bundle/Application/88CC4619-7C5D-4BB1-9F4B-5AAD7EC4BF9C/MyApp.app/Frameworks/UnityFramework.framework/UnityFramework, 265): Library not loaded: @rpath/Sentry.framework/Sentry +2021-10-29 15:21:40.011452-0400 MyApp[2180:186329] Error loading /var/containers/Bundle/Application/88CC4619-7C5D-4BB1-9F4B-5AAD7EC4BF9C/MyApp.app/Frameworks/UnityFramework.framework/UnityFramework: dlopen(/var/containers/Bundle/Application/88CC4619-7C5D-4BB1-9F4B-5AAD7EC4BF9C/MyApp.app/Frameworks/UnityFramework.framework/UnityFramework, 265): Library not loaded: @rpath/SentryObjC.framework/SentryObjC Referenced from: /private/var/containers/Bundle/Application/88CC4619-7C5D-4BB1-9F4B-5AAD7EC4BF9C/MyApp.app/Frameworks/UnityFramework.framework/UnityFramework Reason: image not found ``` -This can happen if you've copied some of the SDK files directly to the Assets folder and the `Sentry.Unity.Editor.iOS.dll` which runs when you build an iOS player wasn't able to copy the `Sentry.framework` to the final app. Enabling debug mode in the Sentry editor window would display more information in the Unity console. +This can happen if you've copied some of the SDK files directly to the Assets folder and the `Sentry.Unity.Editor.iOS.dll` which runs when you build an iOS player wasn't able to copy the `SentryObjC.xcframework` to the final app. Enabling debug mode in the Sentry editor window would display more information in the Unity console. You can resolve this issue by installing the SDK with UPM. diff --git a/docs/platforms/unity/troubleshooting/known-limitations.mdx b/docs/platforms/unity/troubleshooting/known-limitations.mdx index d7670df9a3110..9ca48672c0c36 100644 --- a/docs/platforms/unity/troubleshooting/known-limitations.mdx +++ b/docs/platforms/unity/troubleshooting/known-limitations.mdx @@ -125,7 +125,7 @@ When targeting WebGL, you have the option of setting the `PlayerSettings.WebGL.e - Setting it to `WebGLExceptionSupport.None` is not supported by the SDK. - For the SDK to be able provide stack traces, the support needs to be set to `WebGLExceptionSupport.FullWithStacktrace`. -- The SDK is currently not able to provide line numbers due to the IL2CPP backend not being available. +- The SDK turns off IL2CPP line numbers on WebGL, because Unity's WebGL build doesn't provide the API it needs. - **Native crash detection is not available on WebGL.** The SDK cannot determine if the browser or tab crashed, which affects session tracking: - Sessions with captured exceptions are marked as `Unhandled` - Sessions where the tab/browser closes without a clean shutdown are marked as `Abnormal` diff --git a/docs/platforms/unity/usage/automatic-error-capture/index.mdx b/docs/platforms/unity/usage/automatic-error-capture/index.mdx index 95e4fcc358a01..2d37074121ce9 100644 --- a/docs/platforms/unity/usage/automatic-error-capture/index.mdx +++ b/docs/platforms/unity/usage/automatic-error-capture/index.mdx @@ -13,9 +13,9 @@ The Sentry SDK for Unity provides both automatic and manual error capturing capa The Unity SDK automatically captures errors reported through Unity's logging system. How an event is captured depends on the logging method you use. -### `Debug.LogError` +### `Debug.LogError` and `Debug.LogAssertion` -`Debug.LogError` is captured as an error-level message event. Disable automatic capture in **Tools -> Sentry -> Logging**, or set `CaptureLogErrorEvents` to `false` in the [configure callback](/platforms/unity/configuration/options/programmatic-configuration/). +`Debug.LogError` and `Debug.LogAssertion` are captured as error-level message events. A failed `Debug.Assert` is captured the same way. Unity only runs `Debug.Assert` and `Debug.LogAssertion` in the editor and in development builds, so release builds don't send them. Disable automatic capture in **Tools -> Sentry -> Logging**, or set `CaptureLogErrorEvents` to `false` in the [configure callback](/platforms/unity/configuration/options/programmatic-configuration/). Enable `AttachStacktrace` to include and parse the stack trace Unity provides with the log. On platforms other than WebGL, Unity 6 or later can include source lines in that stack trace when you enable source code line numbers in [Player Settings](https://docs.unity3d.com/6000.0/Documentation/Manual/il2cpp-managed-stack-traces.html). @@ -47,6 +47,28 @@ catch (Exception e) For IL2CPP line-number requirements, see [IL2CPP Line Numbers](/platforms/unity/configuration/il2cpp/). +### Limit Repeated Errors + +A game can log the same error every frame. To drop the repeats, turn on event throttling. + +### Disable Automatic Capture + +To stop capturing errors from Unity's logging system, call these in your [options configuration script](/platforms/unity/configuration/options/programmatic-configuration/): + +- [`DisableUnityLoggingIntegration()`](/platforms/unity/configuration/options/#DisableUnityLoggingIntegration) stops capturing `Debug.LogError` and `Debug.LogAssertion` calls, along with + log breadcrumbs and structured logs. +- [`DisableUnhandledExceptionCapture()`](/platforms/unity/configuration/options/#DisableUnhandledExceptionCapture) stops capturing exceptions that reach Unity's log handler: uncaught exceptions and `Debug.LogException` calls, on every platform including WebGL. + +```csharp +public override void Configure(SentryUnityOptions options) +{ + options.DisableUnityLoggingIntegration(); + options.DisableUnhandledExceptionCapture(); +} +``` + +The SDK still captures unhandled exceptions from .NET's `AppDomain` and unobserved tasks. To stop those, call `options.DisableAppDomainUnhandledExceptionCapture()` and `options.DisableUnobservedTaskExceptionCapture()`. + ## Automatic Error Capture on the Native Layer The Unity SDK also supports automatic error capture on the native layer. This is enabled by default and works through the respective native SDKs for each platform. @@ -63,4 +85,4 @@ On the issues details page, you will see this as errors being connected within t ![Trace Preview](./img/trace-preview.png) -The Sentry SDK regenerates the trace ID whenever the game gains focus or the active scene changes. This creates smaller, more focused trace groups rather than one continuous trace from startup to shutdown, helping you identify truly related errors. +Without tracing, the SDK creates one trace at startup, and every error in the session shares it. With tracing enabled, each transaction (startup, scene load, or one you start yourself and set on the scope) has its own trace, and errors that happen while it runs join that trace. When a transaction finishes, the SDK starts a new trace. diff --git a/docs/platforms/unity/usage/sdk-fingerprinting/index.mdx b/docs/platforms/unity/usage/sdk-fingerprinting/index.mdx index aad876bd72c0b..4c44214d11f39 100644 --- a/docs/platforms/unity/usage/sdk-fingerprinting/index.mdx +++ b/docs/platforms/unity/usage/sdk-fingerprinting/index.mdx @@ -13,6 +13,12 @@ By default, Sentry will run one of our built-in grouping algorithms to generate In supported SDKs, you can override Sentry's default grouping that passes the fingerprint attribute as an array of strings. The length of a fingerprint's array is not restricted. This works similarly to the [fingerprint rules functionality](/concepts/data-management/event-grouping/fingerprint-rules/), which is always available and can achieve similar results. + + +Fingerprints you set in the SDK only apply to events captured in C#. Native crashes keep the default grouping. To group them, use [Fingerprint Rules](/concepts/data-management/event-grouping/fingerprint-rules/). + + + ## Basic Example In the most basic case, values are passed directly: diff --git a/docs/platforms/unity/user-feedback/index.mdx b/docs/platforms/unity/user-feedback/index.mdx index ecb9177e7eba7..664f27855e6e9 100644 --- a/docs/platforms/unity/user-feedback/index.mdx +++ b/docs/platforms/unity/user-feedback/index.mdx @@ -10,12 +10,6 @@ sidebar_section: features og_image: /og-images/platforms-unity-user-feedback.png --- - - -The User Feedback Prefab is available in version `4.0.0` of the Sentry SDK for Unity, which is currently in beta. - - - When a user experiences an error, Sentry provides the ability to collect additional feedback. The Unity SDK provides both a simple prefab-based solution and a programmatic API for collecting user feedback. ## Use the User Feedback Prefab @@ -31,6 +25,8 @@ The Unity SDK includes a ready-to-use prefab that provides a complete user feedb ### Adding the Prefab to Your Scene +The prefab needs the uGUI package (`com.unity.ugui`). + To add the prefab, drag and drop the User Feedback prefab from the Unity SDK package into any scene. The prefab is ready to use immediately without any additional configuration, and includes a scaling canvas that works across different screen sizes and resolutions. ### Default Appearance @@ -54,12 +50,28 @@ You can customize the feedback form by: - Missing optional fields are highlighted in yellow - Missing required fields are highlighted in red -## Use the .NET SDK API +## Use the API If you prefer to create your own feedback form or need programmatic control, you can use the SDK's API to send feedback to Sentry: +```csharp {tabTitle:C#} +SentrySdk.CaptureFeedback("It broke.", "user@example.com", "The User", addScreenshot: true); +``` + +The SDK attaches a screenshot only when `addScreenshot` is `true`. + +To link the feedback to an event, pass the event's ID: + ```csharp {tabTitle:C#} var eventId = SentrySdk.CaptureMessage("An event that will receive user feedback."); SentrySdk.CaptureFeedback("It broke.", "user@example.com", "The User", associatedEventId: eventId); ``` + +To link the feedback to the last event the SDK captured, including errors it captures automatically, such as from `Debug.LogError`, use `SentrySdk.LastEventId`. It's `SentryId.Empty` when no event was captured or the last one was dropped, and native crashes don't set it: + +```csharp {tabTitle:C#} +var lastEventId = SentrySdk.LastEventId; + +SentrySdk.CaptureFeedback("It broke.", "user@example.com", "The User", associatedEventId: lastEventId != SentryId.Empty ? lastEventId : null); +``` diff --git a/docs/product/ai-in-sentry/seer/index.mdx b/docs/product/ai-in-sentry/seer/index.mdx index 51a585c0afe03..a1def5ffbbad5 100644 --- a/docs/product/ai-in-sentry/seer/index.mdx +++ b/docs/product/ai-in-sentry/seer/index.mdx @@ -132,6 +132,10 @@ The [Google Cloud Platform for Seer](/integrations/debugging/gcp-seer/) integrat The [Grafana for Seer](/integrations/debugging/grafana-seer/) integration gives [Seer Agent](#seer-agent) access to metrics and logs through your Grafana Cloud data sources. Seer can then use Grafana data to enhance or supplement Sentry telemetry in issue analysis or investigations. +### Linear for Seer Integration + +The [Linear for Seer](/integrations/debugging/linear-seer/) integration gives [Seer Agent](#seer-agent) read-only access to issues, projects, and comments in your Linear workspace. Seer can then use Linear data to enhance or supplement Sentry telemetry in issue analysis or investigations. + ## Privacy and security Sentry includes strong guarantees for privacy and security of your data. At a glance: diff --git a/docs/product/explore/dropped-data.mdx b/docs/product/explore/dropped-data.mdx index 93623f10b9f5e..88a2a5cc36adc 100644 --- a/docs/product/explore/dropped-data.mdx +++ b/docs/product/explore/dropped-data.mdx @@ -158,7 +158,7 @@ The request failed without a response. Ad blockers and browser extensions are a - **Browser:** A CORS misconfiguration, the user being offline, or the page unloading before the request completes. - **Server:** No outbound network access from the host or container, an egress firewall, a DNS failure, TLS errors from an intercepting proxy, or proxy settings the SDK is not using. - **Actions:** - - For ad blockers, route events through your own domain with the [`tunnel` option](/platforms/javascript/troubleshooting/#using-the-tunnel-option). + - For ad blockers, route events through your own domain with the [`tunnel` option](/platforms/javascript/configuration/tunneling/). - For browsers, confirm in devtools that requests to your ingest domain are not blocked, and check your CORS configuration. - For servers, verify outbound connectivity to your ingest domain from the host or container. diff --git a/docs/product/issues/index.mdx b/docs/product/issues/index.mdx index 98e617b157469..16099fab95e8d 100644 --- a/docs/product/issues/index.mdx +++ b/docs/product/issues/index.mdx @@ -34,8 +34,7 @@ For error issues, to see the stack trace of the latest event, you can hover over ![Error level icon](./img/error_level.png) -{/* TODO(msun): Update this when issue views are GA'd */} -You can save your issue queries and access them later by clicking the "Saved Searches" button in the header. Learn more in [Saved Searches](/concepts/search/saved-searches/). You can also add issues data to your [custom dashboards](/product/dashboards/custom-dashboards/) as widgets using the [dataset selector](/product/dashboards/widget-builder/#choose-your-dataset). +You can save your issue queries as [Issue Views](/product/issues/issue-views/) and open them later from the **Issues** sidebar. You can also add issues data to your [custom dashboards](/product/dashboards/custom-dashboards/) as widgets using the [dataset selector](/product/dashboards/widget-builder/#choose-your-dataset). When you click on an issue on the main **Issues** page, the **Issue Details** page for that issue is displayed. Learn more in [Issue Details](/product/issues/issue-details/). @@ -51,13 +50,14 @@ Sentry creates issues for more than just errors. The **Issues** page sidebar gro ## Issue Triage -From the **Issues** page, you can begin to triage. The page is organized into tabs, each corresponding to a filtered list of issues, and these different lists help you with triaging: +From the **Issues** page, you can begin to triage. The **Feed** shows all unresolved issues (`is:unresolved`) by default. Use the sidebar categories to narrow it to one kind of problem, or search with one of these filters: -- All Unresolved (`is:unresolved`): All unresolved issues, including issues that need review. -- For Review (`is:unresolved is:for_review`). Also called **Review List**, for-review issues are a subset of all unresolved issues and can include new issues or regressions that haven't been reviewed yet. -- Regressed (`is:regressed`): All regressed issues; resolved issues that have come up again. -- Archived (`is:archived`): All archived issues. -- Escalating (`is:escalating`): All escalating issues; previously archived issues that have exceeded their forecasted event volume. +- `is:for_review`: Also called **Review List**, for-review issues are a subset of all unresolved issues and can include new issues or regressions that haven't been reviewed yet. +- `is:regressed`: All regressed issues; resolved issues that have come up again. +- `is:archived`: All archived issues. +- `is:escalating`: All escalating issues; previously archived issues that have exceeded their forecasted event volume. + +To keep a list you use often, save it as an [Issue View](/product/issues/issue-views/). Learn more about triaging issues and their different states in [Issue States and Triage](/product/issues/states-triage/). @@ -71,7 +71,7 @@ Change how issues are sorted in the issues stream by selecting from the sort dro - **Recommended**: The issues most relevant to you are shown first. Sentry combines a variety of signals to determine which issues are most likely to need your attention. - **Last Seen**: The most recent events are shown first. -- **First Seen**: The newest issues are shown first. +- **Age**: The newest issues are shown first. - **Trends**: New issues and escalating issues (with event volumes trending upward) are shown first. Older issues and issues with fewer recent events are sorted lower. The ranking currently relies on three primary factors: - Relative volume: Escalating issues that have a higher recent volume (relative to their baseline) are ranked higher. - Absolute volume: Issues with more event volume are weighted more highly. Recent events are weighted more than old events. diff --git a/docs/product/issues/issue-details/performance-issues/endpoint-regressions/index.mdx b/docs/product/issues/issue-details/performance-issues/endpoint-regressions/index.mdx index 31877e5531f79..b6bd14be2339f 100644 --- a/docs/product/issues/issue-details/performance-issues/endpoint-regressions/index.mdx +++ b/docs/product/issues/issue-details/performance-issues/endpoint-regressions/index.mdx @@ -6,6 +6,12 @@ og_image: >- /og-images/product-issues-issue-details-performance-issues-endpoint-regressions.png --- + + +Sentry no longer creates new Endpoint Regression issues. This page describes issues that were created before detection stopped. + + + Endpoint Regression issues are a generic class of problems where the duration of a transaction increases over time and degrades application performance. Sentry proactively monitors common endpoints out of the box and reports any possible regressions, grouping them as Endpoint Regression issue types. Filter performance regressions with `issue.category:metric` in **Issues** and **Dashboards**. diff --git a/docs/product/issues/issue-details/performance-issues/web-vitals/index.mdx b/docs/product/issues/issue-details/performance-issues/web-vitals/index.mdx index d2b22541df28c..47a55dddbaa27 100644 --- a/docs/product/issues/issue-details/performance-issues/web-vitals/index.mdx +++ b/docs/product/issues/issue-details/performance-issues/web-vitals/index.mdx @@ -24,7 +24,7 @@ The detector for this performance issue runs on a schedule and checks the 7 day The following additional criteria must hold true: - You must have [Seer](/product/ai-in-sentry/seer/) enabled on your Sentry account. -- You must have a [GitHub code mapping](/integrations/source-code-mgmt/code-mappings/) configured for your project. +- You must have a [code mapping](/integrations/source-code-mgmt/code-mappings/) configured for your project that points to a GitHub, GitHub Enterprise, GitLab, or [Cursor Origin](/integrations/source-code-mgmt/cursor-origin/) repository. - There must be at least `10` sample spans for the given vital (_this value is [configurable](/product/issues/issue-details/performance-issues/#configuration)_). - There must be no issues currently open for the same Web Vitals metrics on the page being evaluated. @@ -33,9 +33,9 @@ The following additional criteria must hold true: You can view the [Web Vitals](/product/dashboards/sentry-dashboards/frontend/web-vitals/) dashboard to get an understanding of what pages will trigger the Web Vitals performance issue: -* A _loading / render performance issue_ will be opened, if [Time to First Byte](https://web.dev/articles/ttfb#what_is_ttfb) (TTFB), [Largest Contentful Paint](https://web.dev/articles/lcp#what-is-lcp) (LCP), or [First Contentful Paint](https://web.dev/articles/fcp#what-is-fcp) (FCP) falls into or below the `Meh` threshold. -* A _page stability issue_ will be opened, if [Cumulative Layout Shift](https://web.dev/articles/cls#what-is-cls) (CLS) falls below the `Meh` threshold. -* An _interaction performance issue_ will be opened, if [Interaction to Next Paint](https://web.dev/articles/inp#what-is-inp) (INP) falls below the `Meh` threshold. +- A _loading / render performance issue_ will be opened, if [Time to First Byte](https://web.dev/articles/ttfb#what_is_ttfb) (TTFB), [Largest Contentful Paint](https://web.dev/articles/lcp#what-is-lcp) (LCP), or [First Contentful Paint](https://web.dev/articles/fcp#what-is-fcp) (FCP) falls into or below the `Meh` threshold. +- A _page stability issue_ will be opened, if [Cumulative Layout Shift](https://web.dev/articles/cls#what-is-cls) (CLS) falls below the `Meh` threshold. +- An _interaction performance issue_ will be opened, if [Interaction to Next Paint](https://web.dev/articles/inp#what-is-inp) (INP) falls below the `Meh` threshold. ![Web Vitals evidence](./img/web-vitals-evidence.png) @@ -43,6 +43,6 @@ to get an understanding of what pages will trigger the Web Vitals performance is We highly recommend using [Seer's Autofix](/product/ai-in-sentry/seer/#autofix) functionality to diagnose and fix the Web Vitals Issues we've opened. Alternatively, there is lots of great documentation online about how to improve specific web vitals metrics, see: -* [Optimize Largest Contentful Paint](https://web.dev/articles/optimize-lcp). -* [Optimize Cumulative Layout Shift](https://web.dev/articles/optimize-cls). -* [Optimize Interaction to Next Paint](https://web.dev/articles/optimize-inp). +- [Optimize Largest Contentful Paint](https://web.dev/articles/optimize-lcp). +- [Optimize Cumulative Layout Shift](https://web.dev/articles/optimize-cls). +- [Optimize Interaction to Next Paint](https://web.dev/articles/optimize-inp). diff --git a/docs/product/issues/issue-details/replay-issues/hydration-error.mdx b/docs/product/issues/issue-details/replay-issues/hydration-error.mdx index 2bfa537a93e31..3ffcec4c0a502 100644 --- a/docs/product/issues/issue-details/replay-issues/hydration-error.mdx +++ b/docs/product/issues/issue-details/replay-issues/hydration-error.mdx @@ -26,21 +26,21 @@ In the example below we'll look at a hydration error and see how each tool helps The problem is that the left and right sidebars have some dynamic content that is inserted on the client, but not rendered on the server. -### Image Slider +### Slider Diff The image slider tool allows for comparing the two page states by overlaying the images on top of each other. Click and drag the purple line to reveal one image or the other. ![image slider tool](./img/hydration-error-image-slider-tool.gif) -### Side-by-Side Image +### Side By Side Diff View images side-by-side to see large chunks of the page that may differ. ![side by side image tool](./img/hydration-error-side-by-side-image-tool.png) -### Tree Compare +### Mutations -Use the tree compare tool to list specifically which DOM nodes were added, removed, or had attributes changed. +Use the **Mutations** tab to list specifically which DOM nodes were added, removed, or had attributes changed. You can see each change to the page, and when it happened within the context of the hydration error. In this case one mutation happened at the timestamp `1732089574790` which was at time offset `1790`, or 1.7 seconds since the start of the captured replay. Within this mutation 39 nodes were added, 2 nodes had some attributes changed, and 4 nodes were removed. diff --git a/docs/product/issues/issue-details/replay-issues/index.mdx b/docs/product/issues/issue-details/replay-issues/index.mdx index 3daf1f2d48e29..4b0fa5019446b 100644 --- a/docs/product/issues/issue-details/replay-issues/index.mdx +++ b/docs/product/issues/issue-details/replay-issues/index.mdx @@ -8,9 +8,7 @@ If you've enabled [Session Replay](/product/session-replay/), you'll be able to ## Quota Consumption - -Replay issues do not consume error quota. - +Replay issues do not consume error quota. When a replay is created it consumes [replay quota](/pricing/quotas/manage-replay-quota/) (not to be confused with [error quota](/pricing/quotas/manage-event-stream-guide/)). As the replay is being processed by the server Sentry detects the replay issue types listed below and groups those into issues. These errors are created on the backend after ingest and do not consume error quota. They will not appear on your [stats](https://sentry.io/orgredirect/organizations/:orgslug/stats/) page under the "Total Errors" or "Accepted Errors" graphs. You are not billed for their volume. @@ -22,4 +20,4 @@ When a replay is created it consumes [replay quota](/pricing/quotas/manage-repla ## Searching for Replay Issues -If you use the term `issue.category:replay` in Issue Details search, you'll be able to filter for rage click and hydration error issues. +To filter for rage click and hydration error issues, search the **Issues** page for `issue.type:[replay_click_rage,replay_hydration_error]`. diff --git a/docs/product/issues/issue-details/replay-issues/rage-clicks.mdx b/docs/product/issues/issue-details/replay-issues/rage-clicks.mdx index b6b6efbc6e583..078526505344b 100644 --- a/docs/product/issues/issue-details/replay-issues/rage-clicks.mdx +++ b/docs/product/issues/issue-details/replay-issues/rage-clicks.mdx @@ -15,8 +15,9 @@ In order to see rage clicks in your issue stream on the **Issues** page, your or - Enable the JavaScript SDK (or framework-specific bundle), version 7.60.1 or higher - While you can enable **Session Replay** with JavaScript SDK version 7.27.0, or higher, you'll need - to have version 7.60.1 or higher in order to be able to see **rage click issues**. + While you can enable **Session Replay** with JavaScript SDK version 7.27.0, or + higher, you'll need to have version 7.60.1 or higher in order to be able to + see **rage click issues**. ## Detection Criteria @@ -29,12 +30,13 @@ You can configure Replay to ignore specific selectors if you are seeing [too man To set up alerts and get notified when a rage click occurs, follow these steps: -1. Create a new [Alert](https://sentry.io/orgredirect/organizations/:orgslug/alerts/new/issue/) in Sentry. -2. In the "Set conditions" section, set the "IF" filter to "The issue's category is equal to", then choose "Replay" from the dropdown. -3. Add an optional filter if you like. -4. Choose the action to be performed in the "THEN" dropdown. -5. Decide how often you'd like Sentry to look for rage click issues. -6. Lastly, name your alert and add an owner. +1. Go to **Monitors > [Alerts](https://sentry.io/monitors/alerts)** and click **Create Alert**. +2. Select the projects you want to alert on. +3. Under **If**, add the **Issue type** filter and set it to "Issue type is equal to Rage Click Detected". +4. Under **Then**, choose the action to perform. +5. Name your alert and click **Create Alert**. + +See [Create Alerts](/product/monitors-and-alerts/alerts/create-alerts/) for all options. ## Turn Off Rage Click Issues diff --git a/docs/product/issues/issue-details/uptime-issues/index.mdx b/docs/product/issues/issue-details/uptime-issues/index.mdx index 3d8c9da68f4c7..edcc294a9e911 100644 --- a/docs/product/issues/issue-details/uptime-issues/index.mdx +++ b/docs/product/issues/issue-details/uptime-issues/index.mdx @@ -7,8 +7,8 @@ description: >- og_image: /og-images/product-issues-issue-details-uptime-issues.png --- -An uptime issue is a grouping of detected downtime events for a specific URL. A downtime event is generated by -active uptime alerts when HTTP requests fail to meet our +An uptime issue is a grouping of detected downtime events for a specific uptime monitor. A downtime event is generated by +active uptime monitors when HTTP requests fail to meet our [uptime check criteria](/product/monitors-and-alerts/monitors/uptime-monitoring/#uptime-check-criteria). ![Uptime issue details](./img/uptime-issue-details.png) @@ -20,4 +20,4 @@ Uptime checks made against web services configured with one of Sentry's supporte ## Issue Lifecycle -Uptime issues are grouped by the monitored URL and created upon the first detected downtime. Sentry automatically resolves an ongoing uptime issue when the monitored URL returns to a healthy status and meets our [uptime check criteria](/product/monitors-and-alerts/monitors/uptime-monitoring/#uptime-check-criteria). If the URL experiences subsequent downtime, the issue's status will change to regressed. +Each uptime monitor has one uptime issue. Sentry creates it once the number of consecutive failed checks reaches the monitor's failure tolerance (3 by default), and resolves it once the number of consecutive successful checks reaches the recovery tolerance (1 by default). See [Thresholds](/product/monitors-and-alerts/monitors/uptime-monitoring/#thresholds). If the monitor detects downtime again, the issue's status changes to regressed. diff --git a/docs/product/logs/getting-started/index.mdx b/docs/product/logs/getting-started/index.mdx index abe253815930a..b25a5ef051684 100644 --- a/docs/product/logs/getting-started/index.mdx +++ b/docs/product/logs/getting-started/index.mdx @@ -68,13 +68,13 @@ To set up Sentry Logs, use the links below for supported SDKs. After it's been s - - - - - +- - - - - - +- - +{ + options.Dsn = "___PUBLIC_DSN___"; + options.MinimumBreadcrumbLevel = LogLevel.None; + options.MinimumEventLevel = LogLevel.None; +}); +``` diff --git a/includes/dotnet-usesentry-logging/nlog.mdx b/includes/dotnet-usesentry-logging/nlog.mdx new file mode 100644 index 0000000000000..e7c41c47356b0 --- /dev/null +++ b/includes/dotnet-usesentry-logging/nlog.mdx @@ -0,0 +1,19 @@ +In an app that calls `UseSentry`, add NLog with `AddNLog` from the `NLog.Extensions.Logging` package, and set `ReplaceLoggerFactory`: + +```csharp {filename:Program.cs} +using NLog; +using NLog.Config; +using NLog.Extensions.Logging; + +var config = new LoggingConfiguration(); +config.AddSentry(); +LogManager.Configuration = config; + +builder.Logging.AddNLog(new NLogProviderOptions { ReplaceLoggerFactory = true }); +builder.UseSentry(options => +{ + options.Dsn = "___PUBLIC_DSN___"; +}); +``` + +`ReplaceLoggerFactory` replaces the app's `ILogger` factory with NLog's, so each `ILogger` entry reaches Sentry once, through the target. Without it, NLog runs alongside the `ILogger` integration that `UseSentry` adds, and Sentry receives every entry twice. NLog's rules then decide which entries are logged, instead of the `Logging` section of your configuration. The target sends entries at `Info` or higher to Sentry as logs. To change that level, set [`MinimumLogLevel`](/platforms/dotnet/guides/nlog/#minimumloglevel). In ASP.NET Core, `UseNLog` from the `NLog.Web.AspNetCore` package takes the same option. diff --git a/includes/dotnet-usesentry-logging/serilog.mdx b/includes/dotnet-usesentry-logging/serilog.mdx new file mode 100644 index 0000000000000..7d6e2dbc49f93 --- /dev/null +++ b/includes/dotnet-usesentry-logging/serilog.mdx @@ -0,0 +1,15 @@ +In an app that calls `UseSentry`, add Serilog to the builder's services with `AddSerilog` from the `Serilog.Extensions.Hosting` package, and add the sink there: + +```csharp {filename:Program.cs} +using Sentry.Serilog; +using Serilog; + +builder.Services.AddSerilog(config => config.WriteTo.Sentry()); +builder.UseSentry(options => +{ + options.Dsn = "___PUBLIC_DSN___"; + options.UseSerilog(); +}); +``` + +`AddSerilog` replaces the app's `ILogger` factory with Serilog's, so each `ILogger` entry reaches Sentry once, through the sink. Don't use `builder.Logging.AddSerilog()` or `writeToProviders: true` instead. Both also send each entry through the `ILogger` integration that `UseSentry` adds, so Sentry receives it twice. diff --git a/includes/dotnet-v7-migration-overview.mdx b/includes/dotnet-v7-migration-overview.mdx index bca3081b0df20..646214196aba1 100644 --- a/includes/dotnet-v7-migration-overview.mdx +++ b/includes/dotnet-v7-migration-overview.mdx @@ -1,15 +1,7 @@ - - -There is no stable 7.0 release of the Sentry SDK for .NET yet. Until 7.0.0 ships, use the latest 7.0.0 release candidate from [NuGet](https://www.nuget.org/packages/Sentry/#versions-body-tab) wherever this guide says `7.0.0`. The rest of the .NET docs still describe 6.x until then, so where they differ from this guide, follow this guide. If you run into problems, [open an issue on GitHub](https://github.com/getsentry/sentry-dotnet/issues). - -The release candidate's `net11.0` builds depend on the .NET 11 versions of `Microsoft.Extensions.Http`, `Microsoft.Extensions.Logging.Configuration` and `Microsoft.Extensions.Configuration.Binder`. `Sentry.AspNetCore.Blazor.WebAssembly` also depends on the .NET 11 version of `Microsoft.AspNetCore.Components.WebAssembly`. A .NET 11 app that directly references an older version of one of these packages, such as 10.0.x, fails to restore with error NU1605. The error message shows the version the Sentry package needs. Update the reference to that version, or remove it. - - - Version 7 of the Sentry SDK for .NET adds support for .NET 11 and moves SDK initialization out of the logging integrations. The biggest changes are: - **One place to initialize Sentry.** The Serilog, NLog, log4net and `Microsoft.Extensions.Logging` integrations no longer start the SDK. Call `UseSentry` or `SentrySdk.Init` first, and move the DSN and other SDK settings there. -- **`UseSentry` for generic host apps.** Worker services, Azure Functions isolated worker apps and other apps on the .NET Generic Host can now call `UseSentry` from the new `Sentry.Extensions.Hosting` package. +- **`UseSentry` for generic host apps.** Worker services, Azure Functions isolated worker apps and other apps on the .NET Generic Host can now call `UseSentry` from the new [`Sentry.Extensions.Hosting`](/platforms/dotnet/guides/extensions-hosting/) package. - **Logs.** Version 7 removes `SentryOptions.EnableLogs`. Structured logs are now enabled automatically if you add the Serilog, NLog or log4net integrations, or call `Logging.AddSentry()` after `SentrySdk.Init`, so check the volume and content of your logs after upgrading if you use any of these integrations. - **Platforms.** Android, iOS, Mac Catalyst and MAUI apps need .NET 10 or later. - **Defaults.** The SDK traces fewer incoming requests, and more apps report the host environment instead of `production`. diff --git a/includes/migration/dotnet-v7/call-usesentry-on-webapplicationbuilder.mdx b/includes/migration/dotnet-v7/call-usesentry-on-webapplicationbuilder.mdx index 76e76106fe8e4..47fcc2716c432 100644 --- a/includes/migration/dotnet-v7/call-usesentry-on-webapplicationbuilder.mdx +++ b/includes/migration/dotnet-v7/call-usesentry-on-webapplicationbuilder.mdx @@ -11,7 +11,7 @@ order: 10 ASP.NET Core apps can now call `UseSentry` on `WebApplicationBuilder` and keep chaining. `builder.WebHost.UseSentry()` still works, so this change is optional. -In 6.x, `UseSentry` was only available on the web host: +In version 6.12.1 and earlier, `UseSentry` was only available on the web host: ```csharp {filename:Program.cs} var builder = WebApplication.CreateBuilder(args); @@ -51,4 +51,4 @@ public static class Extensions } ``` -When `UseSentry` from `Sentry.Extensions.Hosting` runs in an ASP.NET Core app, the SDK logs a warning through `ILogger` when the host starts. +When `UseSentry` from `Sentry.Extensions.Hosting` runs in an ASP.NET Core app, the SDK logs a warning through `ILogger` when the host starts. For the same call in a MAUI app, see [.NET Aspire Service Defaults](/platforms/dotnet/guides/extensions-hosting/#net-aspire-service-defaults) in the Generic Host guide. diff --git a/includes/migration/dotnet-v7/category-log-levels-no-longer-filter-breadcrumbs-and-events.mdx b/includes/migration/dotnet-v7/category-log-levels-no-longer-filter-breadcrumbs-and-events.mdx new file mode 100644 index 0000000000000..9c6bb48375330 --- /dev/null +++ b/includes/migration/dotnet-v7/category-log-levels-no-longer-filter-breadcrumbs-and-events.mdx @@ -0,0 +1,44 @@ +--- +id: category-log-levels-no-longer-filter-breadcrumbs-and-events +title: "Category Log Levels No Longer Filter Breadcrumbs and Events" +phase: verify +category: behavior +severity: behavior-change +frameworks: all +platformCategory: all +order: 15 +--- + +In version 7, category entries under `Logging:Sentry:LogLevel` filter only the `ILogger` entries that Sentry sends as logs. In version 6.12.1 and earlier, these entries also filtered breadcrumbs and events from the same category. The `Default` entry is unchanged: it has always applied only to logs. + +For example, this entry keeps `Microsoft.EntityFrameworkCore` entries below `Error` out of the logs: + +```json {filename:appsettings.json} +{ + "Logging": { + "Sentry": { + "LogLevel": { + "Microsoft.EntityFrameworkCore": "Error" + } + } + } +} +``` + +In 6.x, it kept them out of the breadcrumbs too. In 7.x, they show up as breadcrumbs. + +To keep filtering breadcrumbs and events by category, add a log entry filter where you initialize Sentry. The SDK drops an entry from breadcrumbs and events when the filter returns `true`: + +```csharp {filename:Program.cs} +using Sentry.Extensions.Logging; + +var builder = WebApplication.CreateBuilder(args); +builder.UseSentry(options => +{ + options.Dsn = "___PUBLIC_DSN___"; + options.AddLogEntryFilter((category, level, eventId, exception) => + category.StartsWith("Microsoft.EntityFrameworkCore") && level < LogLevel.Error); +}); +``` + +If the app calls `Logging.AddSentry()` after `SentrySdk.Init`, call `AddLogEntryFilter` on the options of `Logging.AddSentry()` instead. diff --git a/includes/migration/dotnet-v7/enablelogs-is-removed-from-sentryoptions.mdx b/includes/migration/dotnet-v7/enablelogs-is-removed-from-sentryoptions.mdx index 84290d1012a22..5772557c4f264 100644 --- a/includes/migration/dotnet-v7/enablelogs-is-removed-from-sentryoptions.mdx +++ b/includes/migration/dotnet-v7/enablelogs-is-removed-from-sentryoptions.mdx @@ -49,4 +49,4 @@ builder.UseSentry(options => A generic host app that set `EnableLogs` on `Logging.AddSentry` in 6.x sets it on `UseSentry` now. -The Serilog sink no longer takes an `enableLogs` argument. NLog's `enableLogs` setting no longer turns logs off, and setting it to `false` writes a warning to standard error. To drop logs and keep errors and breadcrumbs, use `SetBeforeSendLog`, as shown in [Logging Integrations Send Logs](#logging-integrations-send-logs). +The Serilog sink no longer takes an `enableLogs` argument. NLog's `enableLogs` setting is obsolete. `enableLogs="false"` still turns the target's logs off, and `enableLogs="true"` has no effect. Set `minimumLogLevel` to `Off` instead. To drop logs from any integration and keep errors and breadcrumbs, use `SetBeforeSendLog`, as shown in [Logging Integrations Send Logs](#logging-integrations-send-logs). diff --git a/includes/migration/dotnet-v7/generic-host-apps-call-usesentry.mdx b/includes/migration/dotnet-v7/generic-host-apps-call-usesentry.mdx index fe0bb345b47aa..0da4925c66f4b 100644 --- a/includes/migration/dotnet-v7/generic-host-apps-call-usesentry.mdx +++ b/includes/migration/dotnet-v7/generic-host-apps-call-usesentry.mdx @@ -9,7 +9,7 @@ platformCategory: all order: 20 --- -Worker services, Azure Functions isolated worker apps, Windows services and console apps on `Host.CreateApplicationBuilder` often started Sentry with `Logging.AddSentry`. Install `Sentry.Extensions.Hosting` and call `UseSentry` on the host builder instead. +Worker services, Azure Functions isolated worker apps, Windows services and console apps on `Host.CreateApplicationBuilder` often started Sentry with `Logging.AddSentry`. Install `Sentry.Extensions.Hosting` and call `UseSentry` on the host builder instead. The [Generic Host](/platforms/dotnet/guides/extensions-hosting/) guide shows the full setup. ```shell dotnet add package Sentry.Extensions.Hosting @@ -85,7 +85,7 @@ builder.Services.AddHostedService(); builder.Build().Run(); ``` -`UseSentry` also registers `IHub` for dependency injection and sets the environment from the host environment. It works on `IHostApplicationBuilder` types such as `Host.CreateApplicationBuilder` on .NET 8 and later. It also works on `IHostBuilder` types such as `Host.CreateDefaultBuilder` on every target, including .NET Framework. +`UseSentry` also registers `IHub` for dependency injection and sets the environment from the host environment. It works on `IHostApplicationBuilder` types such as `Host.CreateApplicationBuilder` on .NET 8 and later. It also works on `IHostBuilder` types such as `Host.CreateDefaultBuilder` on every target, including .NET Framework. The [Generic Host](/platforms/dotnet/guides/extensions-hosting/) guide shows the full setup. If the app calls `builder.Logging.ClearProviders()`, call `UseSentry` after it. `ClearProviders` removes every logger provider registered before it, including Sentry's, and the app then sends no errors from `ILogger`. If the app has to clear providers after `UseSentry`, call `builder.Logging.AddSentry()` after `ClearProviders` to add Sentry's providers back. Skip that if Serilog, NLog or log4net already sends the app's `ILogger` entries to Sentry, because each entry would then arrive twice. diff --git a/includes/migration/dotnet-v7/logging-integrations-no-longer-initialize-sentry.mdx b/includes/migration/dotnet-v7/logging-integrations-no-longer-initialize-sentry.mdx index df5887f87d5e5..b91827aed9bc2 100644 --- a/includes/migration/dotnet-v7/logging-integrations-no-longer-initialize-sentry.mdx +++ b/includes/migration/dotnet-v7/logging-integrations-no-longer-initialize-sentry.mdx @@ -18,7 +18,7 @@ Initialize Sentry with the call that matches your app: | ASP.NET Core | `UseSentry` from `Sentry.AspNetCore` | | MAUI | `UseSentry` from `Sentry.Maui` | | Blazor WebAssembly | `UseSentry` from `Sentry.AspNetCore.Blazor.WebAssembly` | -| Worker services, Azure Functions isolated worker apps and other apps on the .NET Generic Host | `UseSentry` from `Sentry.Extensions.Hosting` | +| Worker services, Azure Functions isolated worker apps and other apps on the .NET Generic Host | `UseSentry` from `Sentry.Extensions.Hosting`. See [Generic Host](/platforms/dotnet/guides/extensions-hosting/) | | Console apps that build their own `ServiceCollection` without a host | `SentrySdk.Init`, then `Logging.AddSentry()`. If the app injects `IHub`, see [IHub Is Registered Only by UseSentry](#ihub-is-registered-only-by-usesentry) | | Other console apps, ASP.NET on .NET Framework and any other app | `SentrySdk.Init` | diff --git a/includes/migration/dotnet-v7/logging-integrations-send-logs.mdx b/includes/migration/dotnet-v7/logging-integrations-send-logs.mdx index e8a636d93cd61..ba6bf246ed2b8 100644 --- a/includes/migration/dotnet-v7/logging-integrations-send-logs.mdx +++ b/includes/migration/dotnet-v7/logging-integrations-send-logs.mdx @@ -9,14 +9,14 @@ platformCategory: all order: 10 --- -The Serilog sink, the NLog target, the log4net appender and `Logging.AddSentry()` after `SentrySdk.Init` send every entry they receive to Sentry as a log. In 6.x, they sent logs only with `EnableLogs` on, so an upgraded app can send many more logs. +The Serilog sink, the NLog target, the log4net appender and `Logging.AddSentry()` after `SentrySdk.Init` send the entries they receive to Sentry as logs. In 6.x, they sent logs only with `EnableLogs` on, so an upgraded app can send many more logs. Adding one of these integrations is now the opt-in for its logs, in every kind of app. `EnableLogs` on the options of `UseSentry` doesn't change this. See [EnableLogs Is Removed from SentryOptions](#enablelogs-is-removed-from-sentryoptions). Each integration sends the entries its logging framework passes to it: - The Serilog sink gets entries at the logger's minimum level, which is `Information` unless you change it. -- The NLog target gets the levels of the rules that write to it. +- The NLog target gets the levels of the rules that write to it, and sends those at `Info` or higher. Set `MinimumLogLevel` on the target to change that level. - The log4net appender gets entries at its `threshold`. - `Logging.AddSentry()` gets the levels from the `Logging` configuration, which default to `Information`. diff --git a/includes/migration/dotnet-v7/move-sdk-settings-out-of-the-nlog-target.mdx b/includes/migration/dotnet-v7/move-sdk-settings-out-of-the-nlog-target.mdx index 07c534b76613a..3a765e5b4d20a 100644 --- a/includes/migration/dotnet-v7/move-sdk-settings-out-of-the-nlog-target.mdx +++ b/includes/migration/dotnet-v7/move-sdk-settings-out-of-the-nlog-target.mdx @@ -115,4 +115,4 @@ LogManager.Configuration = new LoggingConfiguration() .AddSentry(options => options.MinimumEventLevel = LogLevel.Error); ``` -NLog's `enableLogs` setting is obsolete and has no effect, because the target now sends logs once you add it. See [Logging Integrations Send Logs](#logging-integrations-send-logs). The target now flushes with `SentryOptions.FlushTimeout`, which defaults to 2 seconds instead of 15. See [Logging Frameworks No Longer Close Sentry](#logging-frameworks-no-longer-close-sentry). +The target now sends logs once you add it, so its `enableLogs` setting is obsolete. `enableLogs="false"` still turns logs off, and `enableLogs="true"` has no effect. In 6.x, once logs were on, the target sent every entry it received as a log. In 7.x, it sends entries at `Info` or higher, so set `minimumLogLevel` to keep sending `Trace` or `Debug` entries. See [Logging Integrations Send Logs](#logging-integrations-send-logs). The target now flushes with `SentryOptions.FlushTimeout`, which defaults to 2 seconds instead of 15. See [Logging Frameworks No Longer Close Sentry](#logging-frameworks-no-longer-close-sentry). diff --git a/includes/migration/dotnet-v7/other-removed-and-internal-apis.mdx b/includes/migration/dotnet-v7/other-removed-and-internal-apis.mdx index f9422e5e10e14..757ccd5ef9890 100644 --- a/includes/migration/dotnet-v7/other-removed-and-internal-apis.mdx +++ b/includes/migration/dotnet-v7/other-removed-and-internal-apis.mdx @@ -11,12 +11,13 @@ order: 130 Version 7 removes a few APIs that most apps don't use, makes others internal and reorders some parameters. Update any code that uses them: -| API | Migration | -| ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | -| `Envelope.FromEvent`, `Envelope.FromFeedback`, `Envelope.FromTransaction` | The `IDiagnosticLogger` parameter moves to the end. Reorder the arguments or pass them by name. | -| `options.Native.EnableAppHangTrackingV2` on iOS and Mac Catalyst | Use `options.Native.EnableAppHangTracking`. App hang tracking V2 is already the default. | -| `options.Native.AddInAppExclude(string)` on iOS and Mac Catalyst | Remove the call. It had no effect. | -| `SentryOptions.ScopeObserver`, `SentryOptions.EnableScopeSync`, `SentryOptions.CrashedLastRun` | These are internal now, because only the SDK's native integrations set them. Remove references to them. | +| API | Migration | +| ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Envelope.FromEvent`, `Envelope.FromFeedback`, `Envelope.FromTransaction` | The `IDiagnosticLogger` parameter moves to the end. Reorder the arguments or pass them by name. | +| `options.Native.EnableAppHangTrackingV2` on iOS and Mac Catalyst | Use `options.Native.EnableAppHangTracking`. App hang tracking V2 is already the default. | +| `options.Native.AddInAppExclude(string)` on iOS and Mac Catalyst | Remove the call. It had no effect. | +| `SentryOptions.ScopeObserver`, `SentryOptions.EnableScopeSync`, `SentryOptions.CrashedLastRun` | These are internal now, because only the SDK's native integrations set them. Remove references to them. | +| `GetInternalSentryOptions()` on `ISentryClient` and `IHub` | Use `GetDiagnosticLogger()` on `IHub`, in the `Sentry.Extensibility` namespace, to get the SDK's diagnostic logger. The removed method was only meant for Sentry's own integrations. | The SDK ignores an `EnableScopeSync` key in the `Sentry` section of `appsettings.json`. diff --git a/includes/migration/dotnet-v7/supported-net-versions-and-platforms.mdx b/includes/migration/dotnet-v7/supported-net-versions-and-platforms.mdx index e14568a96c5f4..62d9324fc033a 100644 --- a/includes/migration/dotnet-v7/supported-net-versions-and-platforms.mdx +++ b/includes/migration/dotnet-v7/supported-net-versions-and-platforms.mdx @@ -28,6 +28,8 @@ Each package keeps the .NET Standard and .NET Framework targets it had in 6.x. ` | Mac Catalyst | 15.0 | 17.0 | | iOS | 15.0 | 15.0 | +The [Supported Versions](/platforms/dotnet/guides/maui/#supported-versions) section of the MAUI guide also lists the minimum Windows version. + Move each mobile or MAUI project to .NET 10 or .NET 11 before you update the Sentry packages: ```xml {filename:MyApp.csproj} @@ -48,3 +50,5 @@ An app that targets .NET 11 also needs the higher platform minimums: If a project still targets `net9.0-android`, `net9.0-ios` or `net9.0-maccatalyst`, NuGet gives it the plain `net9.0` build of `Sentry` 7. That build has no native SDK, so the app loses native crash reporting. Stay on 6.x until you move the app to .NET 10. A .NET 9 MAUI project can't use `Sentry.Maui` 7 at all. The package has no .NET 9 target, so NuGet fails the restore with error NU1202. + +The `net11.0` builds of the Sentry packages depend on the .NET 11 versions of `Microsoft.Extensions.Http`, `Microsoft.Extensions.Logging.Configuration` and `Microsoft.Extensions.Configuration.Binder`. `Sentry.AspNetCore.Blazor.WebAssembly` also depends on the .NET 11 version of `Microsoft.AspNetCore.Components.WebAssembly`. A .NET 11 app that directly references an older version of one of these packages, such as 10.0.x, fails to restore with error NU1605. The error message shows the version the Sentry package needs. Update the reference to that version, or remove it. diff --git a/includes/nestjs-sentry-cron-decorator.mdx b/includes/nestjs-sentry-cron-decorator.mdx index d76734fbd7c86..fe6080f036d5a 100644 --- a/includes/nestjs-sentry-cron-decorator.mdx +++ b/includes/nestjs-sentry-cron-decorator.mdx @@ -29,3 +29,30 @@ export class MyCronService { } ``` + +### Monitor Config From `@Cron` + + + +If you don't pass a monitor config with a `schedule`, `@SentryCron` sends the schedule and time zone of the `@Cron` decorator on the same method with each check-in, so Sentry creates the monitor on the first run. You can still pass other monitor options, such as `checkinMargin` and `maxRuntime`: + +```typescript +import { Cron } from '@nestjs/schedule'; +import { SentryCron } from '@sentry/nestjs'; + +export class MyCronService { + @Cron('0 * * * *', { timeZone: 'America/Los_Angeles' }) + @SentryCron('my-monitor-slug', { checkinMargin: 2 }) + handleCron() { + // Your cron job logic here + } +} +``` + +If `@Cron` has neither `timeZone` nor `utcOffset`, the job runs in your server's local time zone, so that time zone is sent. If your servers run in different time zones, set `timeZone` on `@Cron`, so every server sends the same one. + +The monitor is created, and billed, on the first run. Each check-in overwrites the monitor's schedule and time zone with the ones from `@Cron`, so change them in your code rather than in Sentry. + +A six-field expression is sent without its seconds field if that field is a single number, such as `0 30 9 * * *`. Presets such as `@daily` and `@weekly` are sent too. Sub-minute schedules, `Date` values, `utcOffset`, month numbers with `@nestjs/schedule` 3 and earlier (use names such as `MAY`; steps such as `*/3` work), a `*/n` or full-range day field (such as `1-31` or `sun-sat`) combined with the other day field, and time zones that aren't IANA names send no monitor config, including any other options you pass. In those cases, pass a full monitor config to `@SentryCron` or create the monitor in Sentry first. + +To send check-ins without a monitor config, pass `{ fromCronDecorator: false }`. diff --git a/includes/platforms/configuration/options/thread-locality.mdx b/includes/platforms/configuration/options/thread-locality.mdx index 0a8a95b053582..7f1b716e004f0 100644 --- a/includes/platforms/configuration/options/thread-locality.mdx +++ b/includes/platforms/configuration/options/thread-locality.mdx @@ -1,7 +1,7 @@ Read on if you're curious to know how thread locality works for scope data. In .NET, there -are two modes for managing ambient data (which is data that's available in different parts of an application and doesn't need to be passed explicitly through method arguments): a disabled global mode and an enabled global mode. Usually, Sentry will automatically choose the most appropriate mode for your application type. However, this can be overridden by setting [`SentryOptions.IsGlobalModeEnabled`](../../configuration/options/#is-global-mode-enabled) manually. +are two modes for managing ambient data (which is data that's available in different parts of an application and doesn't need to be passed explicitly through method arguments): a disabled global mode and an enabled global mode. Usually, Sentry will automatically choose the most appropriate mode for your application type. However, this can be overridden by setting [`SentryOptions.IsGlobalModeEnabled`](../../configuration/options/#IsGlobalModeEnabled) manually. If global mode is disabled (appropriate for most server-based applications), the ambient scope data will be stored as an `AsyncLocal` and will flow with the execution diff --git a/includes/python-stream-mode-general-callout.mdx b/includes/python-stream-mode-general-callout.mdx index efea2455faa83..7e8b029a52b27 100644 --- a/includes/python-stream-mode-general-callout.mdx +++ b/includes/python-stream-mode-general-callout.mdx @@ -1,5 +1,5 @@ -If you're using stream mode, this page's references to "transaction" should be applied to service spans instead. See Streamed Spans for more information. +In SDK `3.x`, and in stream mode in SDK `2.x`, this page's references to "transaction" apply to service spans instead. See Streamed Spans for more information. diff --git a/includes/python-stream-mode-integration-option-callout.mdx b/includes/python-stream-mode-integration-option-callout.mdx index f4b8df9ac58c5..7a16ee26d41e5 100644 --- a/includes/python-stream-mode-integration-option-callout.mdx +++ b/includes/python-stream-mode-integration-option-callout.mdx @@ -1,5 +1,5 @@ -In stream mode, these options still work as described, but apply to service spans instead of transactions. +In SDK `3.x`, and in stream mode in SDK `2.x`, these options still work as described, but apply to service spans instead of transactions. diff --git a/includes/quick-start-features-expandable.mdx b/includes/quick-start-features-expandable.mdx index a5f564a5cb467..5a5698e0cdae6 100644 --- a/includes/quick-start-features-expandable.mdx +++ b/includes/quick-start-features-expandable.mdx @@ -97,6 +97,11 @@ import { FeatureInfo } from "sentry-docs/components/featureInfo"; @@ -106,6 +111,15 @@ import { FeatureInfo } from "sentry-docs/components/featureInfo"; diff --git a/includes/react-native-expo-plugin-code-snippet.mdx b/includes/react-native-expo-plugin-code-snippet.mdx index 9bbaf7da75fef..86e8f2428f0e9 100644 --- a/includes/react-native-expo-plugin-code-snippet.mdx +++ b/includes/react-native-expo-plugin-code-snippet.mdx @@ -64,6 +64,16 @@ SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ -Do not commit your auth token. Add `.env.local` to your `.gitignore`. For EAS builds, add `SENTRY_AUTH_TOKEN` as an [EAS secret](https://docs.expo.dev/eas/environment-variables/) instead of using a `.env.local` file. +Do not commit your auth token. Add `.env.local` to your `.gitignore`. + +For EAS Build, store the token as an [EAS environment variable](https://docs.expo.dev/eas/environment-variables/manage/) instead of a `.env.local` file. Set it for each environment you build. You can pass `--environment` more than once: + +```bash +eas env:set --name SENTRY_AUTH_TOKEN --value ___ORG_AUTH_TOKEN___ --environment production --environment preview --visibility sensitive +``` + +Each EAS build uses the environment set by the [`environment`](https://docs.expo.dev/eas/environment-variables/usage/#using-environment-variables-with-expo-build) field of its build profile in `eas.json`. If a profile doesn't set `environment`, EAS uses `production` for store builds (`distribution: "store"`), `development` for development builds (`developmentClient: true`), and `preview` for everything else. Set the token for every environment your profiles use, or source maps won't upload for those builds. + +Use `sensitive` visibility if you also upload source maps from your machine, for example after `eas update`. The upload command reads the token from your local environment or `.env` files, not from EAS. Pull it with `eas env:pull --environment production`, or run the upload through `eas env:exec production 'npx @sentry/expo-upload-sourcemaps dist'`. Values with `secret` visibility never leave Expo servers, so they work for EAS Build but can't be pulled for local uploads. diff --git a/includes/react-router/client-setup.mdx b/includes/react-router/client-setup.mdx new file mode 100644 index 0000000000000..05c8cf2e2b1c7 --- /dev/null +++ b/includes/react-router/client-setup.mdx @@ -0,0 +1,70 @@ +### Expose Entry Point Files + +Before configuring Sentry, you need to make React Router's entry files (`entry.client.tsx` and `entry.server.tsx`) visible in your project. Run this command to expose them: + +```bash +npx react-router reveal +``` + +### Configure Client-Side Sentry + +Initialize Sentry in your `entry.client.tsx` file. This code runs in the browser, so it's the same on every server runtime. + +The snippet also turns on: + +- Tracing: via `tracesSampleRate` and `reactRouterTracingIntegration()` +- Session Replay: via `replayIntegration()`, sampled with `replaysSessionSampleRate` and `replaysOnErrorSampleRate` +- User Feedback: via `feedbackIntegration()` + +Don't need a feature? Remove its integration and options from the snippet. + +The `sentryOnError` handler integrates with React Router's [`onError` hook](https://reactrouter.com/how-to/error-reporting) to automatically capture and report client-side errors to Sentry. + +```tsx {filename: entry.client.tsx} +import * as Sentry from "@sentry/react-router"; +import { startTransition, StrictMode } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { HydratedRouter } from "react-router/dom"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + + integrations: [ + // Registers and configures the Tracing integration, + // which automatically instruments your application to monitor its + // performance, including custom React Router routing instrumentation + Sentry.reactRouterTracingIntegration(), + // Registers the Replay integration, + // which automatically captures Session Replays + Sentry.replayIntegration(), + // Registers the User Feedback integration + Sentry.feedbackIntegration({ + // Additional SDK configuration goes in here, for example: + colorScheme: "system", + }), + ], + + // Enables Tracing. + // Set to 1.0 to capture 100% of spans for tracing. + // We recommend reducing this value in production. + tracesSampleRate: 1.0, + + // Set `tracePropagationTargets` to declare which URL(s) should have trace propagation enabled + tracePropagationTargets: [/^\//, /^https:\/\/yourserver\.io\/api/], + + // Capture replays for 10% of all sessions, + // plus for 100% of sessions with an error + // Requires Sentry.replayIntegration() + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1.0, +}); + +startTransition(() => { + hydrateRoot( + document, + + + + ); +}); +``` diff --git a/includes/react-router/logs-metrics-verify.mdx b/includes/react-router/logs-metrics-verify.mdx new file mode 100644 index 0000000000000..f3aecd5acbb81 --- /dev/null +++ b/includes/react-router/logs-metrics-verify.mdx @@ -0,0 +1,55 @@ +## Send Logs + + + +## Send Application Metrics + + + +## Verify Your Setup + +To confirm that Sentry captures errors on the server, add a route whose loader throws an error: + +```tsx {filename: app/routes/sentry-example.tsx} +export function loader() { + throw new Error("Sentry Example Server Error"); +} + +export default function SentryExample() { + return
This page throws an error on the server.
; +} +``` + +Add the route to your `app/routes.ts`: + +```typescript {filename: app/routes.ts} {diff} +import { type RouteConfig, index, route } from "@react-router/dev/routes"; + +export default [ + index("routes/home.tsx"), ++ route("sentry-example", "routes/sentry-example.tsx"), +] satisfies RouteConfig; +``` + +Build and start your app, then open `/sentry-example` in your browser. Sentry receives the error and a trace of the request. Sentry names both after the route, for example `GET /sentry-example`. + +To test the client side too, add a button to one of your pages and click it: + +```tsx + +``` + + + +### View Captured Data in Sentry + +Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). + + diff --git a/includes/react-router/server-entry.mdx b/includes/react-router/server-entry.mdx new file mode 100644 index 0000000000000..63bf036a113bc --- /dev/null +++ b/includes/react-router/server-entry.mdx @@ -0,0 +1,26 @@ +Next, replace the default `handleRequest` and `handleError` functions in your `entry.server.tsx` file with Sentry's versions, and export `instrumentations`. + +`handleError` sends server errors to Sentry. `instrumentations` uses React Router's [instrumentation API](https://reactrouter.com/how-to/instrumentation) to create spans for all loaders, actions, middleware, and request handlers, and names each request after its route, for example `GET /users/:id`. + +```tsx {diff} {filename: entry.server.tsx} ++import * as Sentry from "@sentry/react-router"; + import { createReadableStreamFromReadable } from "@react-router/node"; + import { renderToPipeableStream } from "react-dom/server"; + import { ServerRouter, type HandleErrorFunction } from "react-router"; + ++const handleRequest = Sentry.createSentryHandleRequest({ ++ ServerRouter, ++ renderToPipeableStream, ++ createReadableStreamFromReadable, ++}); + + export default handleRequest; + ++export const handleError: HandleErrorFunction = Sentry.createSentryHandleError({ ++ logErrors: false, ++}); + ++export const instrumentations = [Sentry.createSentryServerInstrumentation()]; + + // ... rest of your server entry +``` diff --git a/includes/react-router/source-maps-upload.mdx b/includes/react-router/source-maps-upload.mdx new file mode 100644 index 0000000000000..78537cc821dc9 --- /dev/null +++ b/includes/react-router/source-maps-upload.mdx @@ -0,0 +1,25 @@ +To keep your auth token secure, always store it in an environment variable instead of directly in your files: + + + +```bash {filename:.env} +SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ +``` + + + +Next, call `sentryOnBuildEnd` in the `buildEnd` hook of your `react-router.config.ts`. It adds debug IDs to your build output and uploads the source maps: + +```typescript {filename: react-router.config.ts} {diff} +import type { Config } from "@react-router/dev/config"; ++import { sentryOnBuildEnd } from "@sentry/react-router/vite"; + +export default { + ssr: true, ++ buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => { ++ // ... ++ // Call this at the end of the hook ++ await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest }); ++ }, +} satisfies Config; +``` diff --git a/includes/react-router/source-maps.mdx b/includes/react-router/source-maps.mdx new file mode 100644 index 0000000000000..798c9fe91bcf9 --- /dev/null +++ b/includes/react-router/source-maps.mdx @@ -0,0 +1,32 @@ +### Add Readable Stack Traces With Source Maps + +The `sentryReactRouter` Vite plugin uploads your source maps, so stack traces in Sentry show your original code. It also instruments supported packages that your server code imports, such as database clients, when Vite builds your app. + +Add the plugin to your `vite.config.ts`, and pass both the Sentry options and the Vite configuration to it: + +```typescript {filename: vite.config.ts} {diff} +import { reactRouter } from "@react-router/dev/vite"; ++import { ++ sentryReactRouter, ++ type SentryReactRouterBuildOptions, ++} from "@sentry/react-router/vite"; +import { defineConfig } from "vite"; + ++const sentryConfig: SentryReactRouterBuildOptions = { ++ org: "___ORG_SLUG___", ++ project: "___PROJECT_SLUG___", ++ ++ // An auth token is required for uploading source maps; ++ // store it in an environment variable to keep it secure. ++ authToken: process.env.SENTRY_AUTH_TOKEN, ++}; + +export default defineConfig((config) => { + return { +- plugins: [reactRouter()], ++ plugins: [reactRouter(), sentryReactRouter(sentryConfig, config)], + }; +}); +``` + + diff --git a/includes/tracing/ai-agents-module/ai-client-span.mdx b/includes/tracing/ai-agents-module/ai-client-span.mdx index 8673fa63fd0cf..400d68d54b6e5 100644 --- a/includes/tracing/ai-agents-module/ai-client-span.mdx +++ b/includes/tracing/ai-agents-module/ai-client-span.mdx @@ -1,10 +1,10 @@ -In transaction mode, the [@sentry_sdk.trace()](/platforms/python/tracing/instrumentation/custom-instrumentation/#span-templates) decorator can also be used to create this span using its `template` parameter. The stream-mode decorator doesn't have a `template` option. +In SDK versions prior to `3.0`, the [@sentry_sdk.trace()](/platforms/python/tracing/instrumentation/custom-instrumentation/#span-templates) decorator can also be used to create this span using its `template` parameter. In SDK `3.x`, the decorator doesn't have a `template` option. -- The span `op` (transaction mode) or the span's `sentry.op` attribute (stream mode) MUST be `"gen_ai.{gen_ai.operation.name}"`. (e.g. `"gen_ai.chat"`) +- The span's `sentry.op` attribute (the span `op` in SDK `2.x` transaction mode) MUST be `"gen_ai.{gen_ai.operation.name}"`. (e.g. `"gen_ai.chat"`) - The span `name` SHOULD be `"{gen_ai.operation.name} {gen_ai.request.model}"`. (e.g. `"chat o3-mini"`) - The `gen_ai.operation.name` attribute MUST be `"chat"`, `"embeddings"`, `"generate_content"` or `"text_completion"`. - The `gen_ai.provider.name` attribute MUST be the Generative AI product as identified by the client or server instrumentation. (e.g. `"openai"`) diff --git a/includes/tracing/ai-agents-module/execute-tool-span.mdx b/includes/tracing/ai-agents-module/execute-tool-span.mdx index a05e304e0e5d1..b58a91092142f 100644 --- a/includes/tracing/ai-agents-module/execute-tool-span.mdx +++ b/includes/tracing/ai-agents-module/execute-tool-span.mdx @@ -2,11 +2,11 @@ Describes a tool execution. -In transaction mode, the [@sentry_sdk.trace()](/platforms/python/tracing/instrumentation/custom-instrumentation/#span-templates) decorator can also be used to create this span using its `template` parameter. The stream-mode decorator doesn't have a `template` option. +In SDK versions prior to `3.0`, the [@sentry_sdk.trace()](/platforms/python/tracing/instrumentation/custom-instrumentation/#span-templates) decorator can also be used to create this span using its `template` parameter. In SDK `3.x`, the decorator doesn't have a `template` option. -- The span `op` (transaction mode) or the span's `sentry.op` attribute (stream mode) MUST be `"gen_ai.execute_tool"`. +- The span's `sentry.op` attribute (the span `op` in SDK `2.x` transaction mode) MUST be `"gen_ai.execute_tool"`. - The span `name` SHOULD be `"execute_tool {gen_ai.tool.name}"`. (e.g. `"execute_tool query_database"`) - The `gen_ai.operation.name` attribute MUST be `"execute_tool"`. - The `gen_ai.tool.name` attribute SHOULD be set to the name of the tool. (e.g. `"query_database"`) diff --git a/includes/tracing/ai-agents-module/invoke-agent-span.mdx b/includes/tracing/ai-agents-module/invoke-agent-span.mdx index d470e1750c8dd..4f609c49c0262 100644 --- a/includes/tracing/ai-agents-module/invoke-agent-span.mdx +++ b/includes/tracing/ai-agents-module/invoke-agent-span.mdx @@ -2,11 +2,11 @@ Describes AI agent invocation. -In transaction mode, the [@sentry_sdk.trace()](/platforms/python/tracing/instrumentation/custom-instrumentation/#span-templates) decorator can also be used to create this span using its `template` parameter. The stream-mode decorator doesn't have a `template` option. +In SDK versions prior to `3.0`, the [@sentry_sdk.trace()](/platforms/python/tracing/instrumentation/custom-instrumentation/#span-templates) decorator can also be used to create this span using its `template` parameter. In SDK `3.x`, the decorator doesn't have a `template` option. -- The span `op` (transaction mode) or the span's `sentry.op` attribute (stream mode) MUST be `"gen_ai.invoke_agent"`. +- The span's `sentry.op` attribute (the span `op` in SDK `2.x` transaction mode) MUST be `"gen_ai.invoke_agent"`. - The span `name` SHOULD be `"invoke_agent {gen_ai.agent.name}"`. - The `gen_ai.operation.name` attribute MUST be `"invoke_agent"`. - The `gen_ai.agent.name` attribute SHOULD be set to the agent's name. (e.g. `"Weather Agent"`) diff --git a/includes/tracing/dart-quick-start-verify-tracing-splitlayout.mdx b/includes/tracing/dart-quick-start-verify-tracing-splitlayout.mdx deleted file mode 100644 index 3ca0aee8a780e..0000000000000 --- a/includes/tracing/dart-quick-start-verify-tracing-splitlayout.mdx +++ /dev/null @@ -1,10 +0,0 @@ -### Tracing - -To test your tracing configuration, create a custom transaction and span: - -```dart -final transaction = Sentry.startTransaction('test-transaction', 'task'); -final span = transaction.startChild('test-span'); -await span.finish(); -await transaction.finish(); -``` diff --git a/includes/tracing/python-quick-start-verify-tracing-splitlayout.mdx b/includes/tracing/python-quick-start-verify-tracing-splitlayout.mdx deleted file mode 100644 index ecda5df7f65d7..0000000000000 --- a/includes/tracing/python-quick-start-verify-tracing-splitlayout.mdx +++ /dev/null @@ -1,20 +0,0 @@ -### Tracing - -To test your tracing configuration, create a custom transaction and span: - -```py {tabTitle: Transaction Mode (Default)} -import sentry_sdk - -with sentry_sdk.start_transaction(op="task", name="Transaction Name"): - span = sentry_sdk.start_span(name="Custom Span Name") - span.finish() - -``` -```py {tabTitle: Stream Mode} -import sentry_sdk - -with sentry_sdk.traces.start_span(name="Service Span Name", attributes={"sentry.op": "task"}, parent_span=None): - span = sentry_sdk.traces.start_span(name="Custom Span Name") - span.end() - -``` diff --git a/next.config.ts b/next.config.ts index a3250e3ff8fa5..875ffec912d81 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,4 +1,3 @@ -import {codecovNextJSWebpackPlugin} from '@codecov/nextjs-webpack-plugin'; import {withSentryConfig} from '@sentry/nextjs/config'; import {redirects} from './redirects.js'; @@ -125,18 +124,6 @@ const nextConfig = { contentDispositionType: 'inline', // "open image in new tab" instead of downloading remotePatterns: REMOTE_IMAGE_PATTERNS, }, - webpack: (config, options) => { - config.plugins.push( - codecovNextJSWebpackPlugin({ - enableBundleAnalysis: typeof process.env.CODECOV_TOKEN === 'string', - bundleName: 'sentry-docs', - uploadToken: process.env.CODECOV_TOKEN, - webpack: options.webpack, - }) - ); - - return config; - }, env: { // Inline this per-deployment value into the edge middleware at build time. // The edge runtime can't read server env vars at request time. diff --git a/package.json b/package.json index e077145a96ce0..5152461370e8d 100644 --- a/package.json +++ b/package.json @@ -65,8 +65,10 @@ "@radix-ui/react-tooltip": "^1.1.4", "@radix-ui/themes": "^3.1.3", "@sentry-internal/global-search": "^1.3.0", - "@sentry/browser": "11.6.0", - "@sentry/nextjs": "11.6.0", + "@sentry/api": "2.7.0", + "@sentry/browser": "11.12.0", + "@sentry/conventions": "^0.33.0", + "@sentry/nextjs": "11.12.0", "@types/mdx": "^2.0.9", "algoliasearch": "^4.23.3", "classnames": "^2.5.1", @@ -132,7 +134,6 @@ }, "devDependencies": { "@babel/preset-typescript": "^7.15.0", - "@codecov/nextjs-webpack-plugin": "^1.9.0", "@eslint/js": "^9.26.0", "@next/eslint-plugin-next": "^15.3.3", "@tailwindcss/forms": "^0.5.7", diff --git a/platform-includes/configuration/auto-session-tracking/unity.mdx b/platform-includes/configuration/auto-session-tracking/unity.mdx index d36f3b60555e3..92a6be56bd92e 100644 --- a/platform-includes/configuration/auto-session-tracking/unity.mdx +++ b/platform-includes/configuration/auto-session-tracking/unity.mdx @@ -1,8 +1,23 @@ - +The SDK tracks sessions by default. It marks each session as: -Sentry SDK subscribes to `OnApplicationPause` and `OnApplicationFocus` events to track if the application has focus or if it has been put in the background. On resume within `AutoSessionTrackingInterval` the session will be continued. The default value is `30 seconds`. Otherwise, the previous session will be ended and we create a new one. +- Healthy +- Abnormal +- Errored: if the SDK captures a handled exception, for example through `SentrySdk.CaptureException`. +- Unhandled: if the SDK captures an uncaught exception or a `Debug.LogException` call, and the game keeps running. +- Crashed -```csharp {tabTitle:C#} +The SDK starts a session when the game starts. When the game quits, the SDK pauses the session and closes it at the next start. This way, the SDK can tell whether the previous run crashed. Closing the paused session and detecting the crash need a [`CacheDirectoryPath`](/platforms/unity/configuration/options/#CacheDirectoryPath), so they don't work when offline caching is off, or on Xbox, where the SDK doesn't set one. On Nintendo Switch, the SDK doesn't track sessions. + +The SDK pauses the session when the game loses focus or goes into the background. If the game comes back within `AutoSessionTrackingInterval`, the session continues. Otherwise, the SDK ends it and starts a new one. The default is 30 seconds. In the editor, these settings are under **Auto Session Tracking** in **Tools > Sentry > Advanced**, where **Timeout [ms]** sets the interval. + +```csharp // Add this to the SDK initialization callback options.AutoSessionTrackingInterval = TimeSpan.FromSeconds(30); ``` + +To turn off session tracking: + +```csharp +// Add this to the SDK initialization callback +options.AutoSessionTracking = false; +``` diff --git a/platform-includes/configuration/config-intro/dotnet.aspnetcore.mdx b/platform-includes/configuration/config-intro/dotnet.aspnetcore.mdx index d7721835d85d4..7ec0853392e81 100644 --- a/platform-includes/configuration/config-intro/dotnet.aspnetcore.mdx +++ b/platform-includes/configuration/config-intro/dotnet.aspnetcore.mdx @@ -1,8 +1,6 @@ Options can be set by passing a callback to the `UseSentry()` method which will pass the option object along for modifications: -### ASP.NET Core 6.0+: - ```csharp var builder = WebApplication.CreateBuilder(args); @@ -25,35 +23,6 @@ builder.WebHost.UseSentry(fun o -> ) |> ignore ``` -### ASP.NET Core 2.3 on .NET Framework: - -Although ASP.NET Core 2 is no longer supported for .NET Core, Microsoft maintain ASP.NET Core 2.3 to make it easier for people using .NET Framework to transition to ASP.NET Core. If you are using [ASP.NET Core 2.3 on .NET Framework](https://dotnet.microsoft.com/platform/support/policy/aspnet#dotnet-core) then you can configure Sentry using the `WebHostBuilder`: - -```csharp -public static IWebHost BuildWebHost(string[] args) => - WebHost.CreateDefaultBuilder(args) - // Add the following line: - .UseSentry(o => - { - o.Dsn = "___PUBLIC_DSN___"; - o.MaxBreadcrumbs = 50; - o.Debug = true; - o.SendDefaultPii = true; - }); -``` - -```fsharp -let BuildWebHost args = - WebHost.CreateDefaultBuilder(args) - // Add the following line: - .UseSentry(fun o -> - o.Dsn <- "___PUBLIC_DSN___" - o.MaxBreadcrumbs <- 50 - o.Debug <- true - o.SendDefaultPii <- true - ) -``` - Additionally, you can set your options on `appsettings.json` when using `UseSentry()`: diff --git a/platform-includes/configuration/config-intro/dotnet.azure-functions-worker.mdx b/platform-includes/configuration/config-intro/dotnet.azure-functions-worker.mdx new file mode 100644 index 0000000000000..008c73a85c5b8 --- /dev/null +++ b/platform-includes/configuration/config-intro/dotnet.azure-functions-worker.mdx @@ -0,0 +1,26 @@ +Pass the options to `UseSentry` in a callback: + +```csharp {filename:Program.cs} +using Microsoft.Extensions.Hosting; + +var host = new HostBuilder() + .ConfigureFunctionsWorkerDefaults() + .UseSentry(options => + { + options.Dsn = "___PUBLIC_DSN___"; + options.MaxBreadcrumbs = 50; + options.Debug = true; + options.SendDefaultPii = true; + }) + .Build(); +``` + +`UseSentry` also reads the `Sentry` section of your app's configuration. It applies the configuration first and then runs the callback, so a value set in the callback wins. + + + +After you have configured Sentry in your code, you can also configure the +[MSBuild setup](/platforms/dotnet/configuration/msbuild/) for your project. While this step is optional, +it can greatly improve your Sentry experience. + + diff --git a/platform-includes/configuration/config-intro/dotnet.extensions-hosting.mdx b/platform-includes/configuration/config-intro/dotnet.extensions-hosting.mdx new file mode 100644 index 0000000000000..8077b5ee80311 --- /dev/null +++ b/platform-includes/configuration/config-intro/dotnet.extensions-hosting.mdx @@ -0,0 +1,35 @@ +Pass the options to `UseSentry` in a callback: + +```csharp {filename:Program.cs} +var builder = Host.CreateApplicationBuilder(args); +builder.UseSentry(options => +{ + options.Dsn = "___PUBLIC_DSN___"; + options.MaxBreadcrumbs = 50; + options.Debug = true; + options.SendDefaultPii = true; +}); +``` + +You can also set them in the `Sentry` section of `appsettings.json`: + +```json {filename:appsettings.json} +{ + "Sentry": { + "Dsn": "___PUBLIC_DSN___", + "MaxBreadcrumbs": 50, + "Debug": true, + "SendDefaultPii": true + } +} +``` + +`UseSentry` applies the configuration first and then runs the callback, so a value set in the callback wins. + + + +After you have configured Sentry in your code, you can also configure the +[MSBuild setup](/platforms/dotnet/configuration/msbuild/) for your project. While this step is optional, +it can greatly improve your Sentry experience. + + diff --git a/platform-includes/configuration/config-intro/dotnet.nlog.mdx b/platform-includes/configuration/config-intro/dotnet.nlog.mdx deleted file mode 100644 index fcde9145aad18..0000000000000 --- a/platform-includes/configuration/config-intro/dotnet.nlog.mdx +++ /dev/null @@ -1,87 +0,0 @@ - - -For more information on how to dynamically set event data via `NLog.config`, see NLog's [layout renderer documentation](https://nlog-project.org/config/?tab=layout-renderers). - - - -You can configure the Sentry NLog target via `NLog.config` or by code as follows: - - -```xml {tabTitle:NLog.config} - - - - - - - - - - - - - - - - - - - -``` - -```csharp -using NLog; -using Sentry.NLog; - -LogManager.Configuration.AddSentry(o => -{ - // Optionally specify a separate format for message - o.Layout = "${message}"; - // Optionally specify a separate format for breadcrumbs - o.BreadcrumbLayout = "${logger}: ${message}"; - - // Debug and higher are stored as breadcrumbs (default is Info) - o.MinimumBreadcrumbLevel = LogLevel.Debug; - - // Error and higher is sent as event (default is Error) - o.MinimumEventLevel = LogLevel.Error; - - // Send the logger name as a tag - o.AddTag("logger", "${logger}"); - - // All Sentry Options are accessible here. -}); -``` - -```fsharp -open NLog -open Sentry.NLog - -LogManager.Configuration.AddSentry( - fun o -> - // Optionally specify a separate format for message - o.Layout <- "${message}" - // Optionally specify a separate format for breadcrumbs - o.BreadcrumbLayout <- "${logger}: ${message}" - - // Debug and higher are stored as breadcrumbs (default is Info) - o.MinimumBreadcrumbLevel <- LogLevel.Debug - - // Error and higher is sent as event (default is Error) - o.MinimumEventLevel <- LogLevel.Error - - // Send the logger name as a tag - o.AddTag("logger", "${logger}") - - // All Sentry Options are accessible here. -) -``` diff --git a/platform-includes/configuration/diagnostic-logger/unity.mdx b/platform-includes/configuration/diagnostic-logger/unity.mdx new file mode 100644 index 0000000000000..d5a85b4e16e50 --- /dev/null +++ b/platform-includes/configuration/diagnostic-logger/unity.mdx @@ -0,0 +1,58 @@ +Sentry's SDK includes its own internal logger to report diagnostics that may be useful when troubleshooting your Sentry configuration. + +In the editor window (**Tools > Sentry**), the diagnostic logs are controlled by **Enable Debug Output**, **Only In Editor** and **Verbosity Level**. By default, debug output is on and limited to the Editor, at the `Warning` level. Uncheck **Only In Editor** to also get the logs in builds. + +To set the same options in code, use an option configuration script or a manual `SentrySdk.Init`: + +```csharp +using Sentry; +using Sentry.Unity; + +public class SentryOptionConfiguration : SentryOptionsConfiguration +{ + public override void Configure(SentryUnityOptions options) + { + // Enable debug mode to write diagnostic messages + options.Debug = true; + + // Log everything, from the most verbose level up + options.DiagnosticLevel = SentryLevel.Debug; + } +} +``` + +The SDK writes its diagnostic logs to Unity's log, tagged `Sentry`. They show up in the Editor's Console window, in the Player log of a build, and in logcat or the Xcode console on mobile. They aren't sent to Sentry. + +## Customize Implementation + +To write the logs somewhere else, set the `DiagnosticLogger` option. The SDK only uses a custom logger while `Debug` is on. + +For example, `FileDiagnosticLogger` writes diagnostic messages to a file at the path you specify: + +```csharp +using Sentry.Infrastructure; +using UnityEngine; + +// ... +options.Debug = true; +#if !UNITY_EDITOR +// The option configuration script also runs in the Editor during builds, +// so only create the file logger in the game itself. +options.DiagnosticLogger = new FileDiagnosticLogger( + System.IO.Path.Combine(Application.persistentDataPath, "sentry-log.txt")); +#endif +``` + + + +The `FileDiagnosticLogger` implementation will overwrite any existing file, and will grow indefinitely. You should avoid using it long-term in a production environment. + +`FileDiagnosticLogger` keeps its file open until the process exits, and creating a second logger for the same file can throw. If several instances of the game can run at once, give each its own file name. Don't use it with `Application.persistentDataPath` on Nintendo Switch or Xbox, where the SDK itself doesn't write to that path. + + + + + +You can also create your own diagnostic logger class, either by implementing the `IDiagnosticLogger` interface, or inheriting from the `DiagnosticLogger` abstract class and overriding the `LogMessage` method. + + diff --git a/platform-includes/configuration/integrations/javascript.astro.mdx b/platform-includes/configuration/integrations/javascript.astro.mdx index 66fba29ecf1f8..7466a54771c5d 100644 --- a/platform-includes/configuration/integrations/javascript.astro.mdx +++ b/platform-includes/configuration/integrations/javascript.astro.mdx @@ -8,8 +8,8 @@ Depending on whether an integration enhances the functionality of a particular r ### Common Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`dedupeIntegration`](./dedupe/) | ✓ | ✓ | | | | [`eventFiltersIntegration`](./eventfilters/) | ✓ | ✓ | | | | [`functionToStringIntegration`](./functiontostring/) | ✓ | | | | @@ -20,37 +20,37 @@ Depending on whether an integration enhances the functionality of a particular r ### Browser Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | -| ----------------------------------------------------- | :--------------: | :--------: | :---------: | :--------: | :--------------------: | -| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | -| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | -| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | -| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | -| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | -| [`interactionsIntegration`](./interactions/) | | | ✓ | | | -| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | -| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | -| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | -| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | -| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | -| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | -| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | -| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | -| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | -| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | -| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | -| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | -| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | -| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | -| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | -| [`statsigIntegration`](./statsig/) | | | | | ✓ | -| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | -| [`unleashIntegration`](./unleash/) | | | | | ✓ | +| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | +| ---------------------------------------------------------------- | :-----------------: | :--------: | :---------: | :--------: | :--------------------: | +| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | +| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | +| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | +| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | +| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | +| [`interactionsIntegration`](./interactions/) | | | ✓ | | | +| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | +| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | +| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | +| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | +| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | +| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | +| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | +| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | +| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | +| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | +| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | +| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | +| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | +| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | +| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | +| [`statsigIntegration`](./statsig/) | | | | | ✓ | +| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | +| [`unleashIntegration`](./unleash/) | | | | | ✓ | ### Node.js Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`amqplibIntegration`](./amqplib/) | ✓ | | ✓ | | | [`awsLambdaWebIntegration`](./awslambdaweb/) | ✓ | | | ✓ | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | @@ -98,3 +98,4 @@ Depending on whether an integration enhances the functionality of a particular r | [`firebaseIntegration`](./firebase/) | ✓ | | ✓ | | | [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | | [`pinoIntegration`](./pino/) | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | diff --git a/platform-includes/configuration/integrations/javascript.aws-lambda.mdx b/platform-includes/configuration/integrations/javascript.aws-lambda.mdx index ac3543690d0d9..016c450488ece 100644 --- a/platform-includes/configuration/integrations/javascript.aws-lambda.mdx +++ b/platform-includes/configuration/integrations/javascript.aws-lambda.mdx @@ -1,7 +1,7 @@ ### Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`awsIntegration`](./aws/) | ✓ | | ✓ | | | [`awsLambdaIntegration`](./awslambda/) | ✓ | | ✓ | | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | @@ -55,3 +55,4 @@ | [`trpcMiddleware`](./trpc/) | | ✓ | ✓ | ✓ | | [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | | [`pinoIntegration`](./pino/) | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | diff --git a/platform-includes/configuration/integrations/javascript.bun.mdx b/platform-includes/configuration/integrations/javascript.bun.mdx index 8dc423f3b61c6..f0fc5778ce959 100644 --- a/platform-includes/configuration/integrations/javascript.bun.mdx +++ b/platform-includes/configuration/integrations/javascript.bun.mdx @@ -1,7 +1,7 @@ ### Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`amqplibIntegration`](./amqplib/) | ✓ | | ✓ | | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | | [`contextLinesIntegration`](./contextlines/) | ✓ | ✓ | | | @@ -47,14 +47,15 @@ | [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | [`trpcMiddleware`](./trpc/) | | ✓ | ✓ | ✓ | | [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | ### Bun Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | -| [`bunServerIntegration`](./bunserver/) | ✓ | ✓ | ✓ | | -| [`bunRuntimeMetricsIntegration`](./bunruntimemetrics/) | | | | ✓ | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ------------------------------------------------------ | :--------------: | :--------: | :---------: | :--------------------: | +| [`bunServerIntegration`](./bunserver/) | ✓ | ✓ | ✓ | | +| [`bunRuntimeMetricsIntegration`](./bunruntimemetrics/) | | | | ✓ | diff --git a/platform-includes/configuration/integrations/javascript.cloudflare.mdx b/platform-includes/configuration/integrations/javascript.cloudflare.mdx index 99a2952b3905b..03a90fa3226b7 100644 --- a/platform-includes/configuration/integrations/javascript.cloudflare.mdx +++ b/platform-includes/configuration/integrations/javascript.cloudflare.mdx @@ -1,7 +1,7 @@ ### Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Cron** | **Additional Context** | -| --------------------------------------------------- | :--------------: | :--------: | :---------: | :------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Cron** | **Additional Context** | +| ---------------------------------------------------- | :--------------: | :--------: | :---------: | :------: | :--------------------: | | [`dedupeIntegration`](./dedupe/) | ✓ | ✓ | | | | | [`eventFiltersIntegration`](./eventfilters/) | ✓ | ✓ | | | | | [`fetchIntegration`](./fetchIntegration/) | ✓ | ✓ | ✓ | | | @@ -14,6 +14,7 @@ | [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | | [`instrumentPostgresJsSql`](./postgresjs/) | | | ✓ | | | | [`prismaIntegration`](./prisma/) | | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | | [Mistral AI](./mistral/) is automatically instrumented when built with the Sentry Cloudflare Vite plugin. Without the plugin, use `instrumentMistralAiClient`. diff --git a/platform-includes/configuration/integrations/javascript.deno.mdx b/platform-includes/configuration/integrations/javascript.deno.mdx index 187f4353e9937..e7b056b608096 100644 --- a/platform-includes/configuration/integrations/javascript.deno.mdx +++ b/platform-includes/configuration/integrations/javascript.deno.mdx @@ -1,24 +1,25 @@ ### Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Cron** | **Additional Context** | -| --------------------------------------------------- | :--------------: | :--------: | :---------: | :------: | :--------------------: | -| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | -| [`consoleIntegration`](./console/) | ✓ | | | | ✓ | -| [`contextLinesIntegration`](./contextlines/) | ✓ | ✓ | | | | -| [`dedupeIntegration`](./dedupe/) | ✓ | ✓ | | | | -| [`denoContextIntegration`](./denocontext/) | ✓ | | | | ✓ | -| [`eventFiltersIntegration`](./eventfilters/) | ✓ | ✓ | | | | -| [`functionToStringIntegration`](./functiontostring/) | ✓ | | | | | -| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | -| [`linkedErrorsIntegration`](./linkederrors/) | ✓ | ✓ | | | | -| [`captureConsoleIntegration`](./captureconsole/) | | | | | ✓ | -| [`denoCronIntegration`](./denocron/) | | | | ✓ | | -| [`denoRuntimeMetricsIntegration`](./denoruntimemetrics/) | | | | | ✓ | -| [`extraErrorDataIntegration`](./extraerrordata/) | | | | | ✓ | -| [`rewriteFramesIntegration`](./rewriteframes/) | | ✓ | | | | -| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | -| [`instrumentPostgresJsSql`](./postgresjs/) | | | ✓ | | | -| [`trpcMiddleware`](./trpc/) | | ✓ | ✓ | | ✓ | -| [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | -| [`mistralAIIntegration`](./mistral/) | ✓ | | ✓ | | | -| [`typesafeIntegration`](./typesafe/) | ✓ | | ✓ | | | +| | **Auto Enabled** | **Errors** | **Tracing** | **Cron** | **Additional Context** | +| -------------------------------------------------------- | :--------------: | :--------: | :---------: | :------: | :--------------------: | +| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | +| [`consoleIntegration`](./console/) | ✓ | | | | ✓ | +| [`contextLinesIntegration`](./contextlines/) | ✓ | ✓ | | | | +| [`dedupeIntegration`](./dedupe/) | ✓ | ✓ | | | | +| [`denoContextIntegration`](./denocontext/) | ✓ | | | | ✓ | +| [`eventFiltersIntegration`](./eventfilters/) | ✓ | ✓ | | | | +| [`functionToStringIntegration`](./functiontostring/) | ✓ | | | | | +| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | +| [`linkedErrorsIntegration`](./linkederrors/) | ✓ | ✓ | | | | +| [`captureConsoleIntegration`](./captureconsole/) | | | | | ✓ | +| [`denoCronIntegration`](./denocron/) | | | | ✓ | | +| [`denoRuntimeMetricsIntegration`](./denoruntimemetrics/) | | | | | ✓ | +| [`extraErrorDataIntegration`](./extraerrordata/) | | | | | ✓ | +| [`rewriteFramesIntegration`](./rewriteframes/) | | ✓ | | | | +| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | +| [`instrumentPostgresJsSql`](./postgresjs/) | | | ✓ | | | +| [`trpcMiddleware`](./trpc/) | | ✓ | ✓ | | ✓ | +| [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | +| [`mistralAIIntegration`](./mistral/) | ✓ | | ✓ | | | +| [`typesafeIntegration`](./typesafe/) | ✓ | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | | diff --git a/platform-includes/configuration/integrations/javascript.fastify.mdx b/platform-includes/configuration/integrations/javascript.fastify.mdx index 8392ee505ad66..954b7d37a6a4e 100644 --- a/platform-includes/configuration/integrations/javascript.fastify.mdx +++ b/platform-includes/configuration/integrations/javascript.fastify.mdx @@ -1,7 +1,7 @@ ### Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`amqplibIntegration`](./amqplib/) | ✓ | | ✓ | | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | | [`dedupeIntegration`](./dedupe/) | ✓ | ✓ | | | @@ -55,3 +55,4 @@ | [`trpcMiddleware`](./trpc/) | | ✓ | ✓ | ✓ | | [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | | [`pinoIntegration`](./pino/) | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | diff --git a/platform-includes/configuration/integrations/javascript.gcp-functions.mdx b/platform-includes/configuration/integrations/javascript.gcp-functions.mdx index 461d95cdd4ff5..f58776e8a9ba9 100644 --- a/platform-includes/configuration/integrations/javascript.gcp-functions.mdx +++ b/platform-includes/configuration/integrations/javascript.gcp-functions.mdx @@ -1,7 +1,7 @@ ### Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | | [`contextLinesIntegration`](./contextlines/) | ✓ | ✓ | | | | [`dedupeIntegration`](./dedupe/) | ✓ | ✓ | | | @@ -56,3 +56,4 @@ | [`trpcMiddleware`](./trpc/) | | ✓ | ✓ | ✓ | | [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | | [`pinoIntegration`](./pino/) | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | diff --git a/platform-includes/configuration/integrations/javascript.hapi.mdx b/platform-includes/configuration/integrations/javascript.hapi.mdx index c8712e2712a52..7390c815a8120 100644 --- a/platform-includes/configuration/integrations/javascript.hapi.mdx +++ b/platform-includes/configuration/integrations/javascript.hapi.mdx @@ -1,7 +1,7 @@ ### Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`amqplibIntegration`](./amqplib/) | ✓ | | ✓ | | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | | [`contextLinesIntegration`](./contextlines/) | ✓ | ✓ | | | @@ -56,3 +56,4 @@ | [`trpcMiddleware`](./trpc/) | | ✓ | ✓ | ✓ | | [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | | [`pinoIntegration`](./pino/) | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | diff --git a/platform-includes/configuration/integrations/javascript.nestjs.mdx b/platform-includes/configuration/integrations/javascript.nestjs.mdx index 28e3d6cf083dd..97fa6f1a46988 100644 --- a/platform-includes/configuration/integrations/javascript.nestjs.mdx +++ b/platform-includes/configuration/integrations/javascript.nestjs.mdx @@ -1,7 +1,7 @@ ### Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`amqplibIntegration`](./amqplib/) | ✓ | | ✓ | | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | | [`contextLinesIntegration`](./contextlines/) | ✓ | ✓ | | | @@ -56,3 +56,4 @@ | [`typesafeIntegration`](./typesafe/) | ✓ | | ✓ | | | [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | | [`pinoIntegration`](./pino/) | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | diff --git a/platform-includes/configuration/integrations/javascript.nextjs.mdx b/platform-includes/configuration/integrations/javascript.nextjs.mdx index c9d21e039ed1f..35a7198397bd3 100644 --- a/platform-includes/configuration/integrations/javascript.nextjs.mdx +++ b/platform-includes/configuration/integrations/javascript.nextjs.mdx @@ -9,8 +9,8 @@ Depending on whether an integration enhances the functionality of a particular r ### Common Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`dedupeIntegration`](./dedupe/) | ✓ | ✓ | | | | [`eventFiltersIntegration`](./eventfilters/) | ✓ | ✓ | | | | [`functionToStringIntegration`](./functiontostring/) | ✓ | | | | @@ -21,43 +21,44 @@ Depending on whether an integration enhances the functionality of a particular r ### Browser Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | -| ----------------------------------------------------- | :--------------: | :--------: | :---------: | :--------: | :--------------------: | -| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | -| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | -| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | -| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | -| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | -| [`interactionsIntegration`](./interactions/) | | | ✓ | | | -| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | -| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | -| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | -| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | -| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | -| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | -| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | -| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | -| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | -| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | -| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | -| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | -| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | -| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | -| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | -| [`statsigIntegration`](./statsig/) | | | | | ✓ | -| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | -| [`unleashIntegration`](./unleash/) | | | | | ✓ | +| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | +| ---------------------------------------------------------------- | :-----------------: | :--------: | :---------: | :--------: | :--------------------: | +| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | +| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | +| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | +| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | +| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | +| [`interactionsIntegration`](./interactions/) | | | ✓ | | | +| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | +| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | +| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | +| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | +| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | +| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | +| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | +| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | +| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | +| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | +| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | +| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | +| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | +| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | +| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | +| [`statsigIntegration`](./statsig/) | | | | | ✓ | +| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | +| [`unleashIntegration`](./unleash/) | | | | | ✓ | ### Server (Node.js, Edge) Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| ----------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ------------------------------------------ | :--------------: | :--------: | :---------: | :--------------------: | | [`requestDataIntegration`](./requestdata/) | ✓ | | ✓ | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | ### Node.js Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`amqplibIntegration`](./amqplib/) | ✓ | | ✓ | | | [`awsLambdaWebIntegration`](./awslambdaweb/) | ✓ | | | ✓ | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | @@ -107,7 +108,7 @@ Depending on whether an integration enhances the functionality of a particular r ### Edge Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`winterCGFetchIntegration`](./wintercgfetch/) | ✓ | | ✓ | ✓ | | [`vercelAiIntegration`](./vercelai/) | | | ✓ | | diff --git a/platform-includes/configuration/integrations/javascript.node.mdx b/platform-includes/configuration/integrations/javascript.node.mdx index ac9a469467c0d..3362ecd736fd4 100644 --- a/platform-includes/configuration/integrations/javascript.node.mdx +++ b/platform-includes/configuration/integrations/javascript.node.mdx @@ -1,7 +1,7 @@ ### Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`amqplibIntegration`](./amqplib/) | ✓ | | ✓ | | | [`anrIntegration`](./anr/) | | ✓ | | | | [`awsLambdaWebIntegration`](./awslambdaweb/) | ✓ | | | ✓ | @@ -56,3 +56,4 @@ | [`firebaseIntegration`](./firebase/) | ✓ | | ✓ | | | [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | | [`pinoIntegration`](./pino/) | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | diff --git a/platform-includes/configuration/integrations/javascript.nuxt.mdx b/platform-includes/configuration/integrations/javascript.nuxt.mdx index 047fbcf8775fd..db4ec7cad18f7 100644 --- a/platform-includes/configuration/integrations/javascript.nuxt.mdx +++ b/platform-includes/configuration/integrations/javascript.nuxt.mdx @@ -8,8 +8,8 @@ Depending on whether an integration enhances the functionality of a particular r ### Common Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`dedupeIntegration`](./dedupe/) | ✓ | ✓ | | | | [`eventFiltersIntegration`](./eventfilters/) | ✓ | ✓ | | | | [`functionToStringIntegration`](./functiontostring/) | ✓ | | | | @@ -20,37 +20,37 @@ Depending on whether an integration enhances the functionality of a particular r ### Browser Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | -| ----------------------------------------------------- | :--------------: | :--------: | :---------: | :--------: | :--------------------: | -| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | -| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | -| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | -| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | -| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | -| [`interactionsIntegration`](./interactions/) | | | ✓ | | | -| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | -| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | -| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | -| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | -| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | -| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | -| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | -| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | -| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | -| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | -| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | -| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | -| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | -| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | -| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | -| [`statsigIntegration`](./statsig/) | | | | | ✓ | -| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | -| [`unleashIntegration`](./unleash/) | | | | | ✓ | +| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | +| ---------------------------------------------------------------- | :-----------------: | :--------: | :---------: | :--------: | :--------------------: | +| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | +| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | +| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | +| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | +| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | +| [`interactionsIntegration`](./interactions/) | | | ✓ | | | +| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | +| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | +| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | +| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | +| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | +| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | +| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | +| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | +| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | +| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | +| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | +| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | +| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | +| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | +| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | +| [`statsigIntegration`](./statsig/) | | | | | ✓ | +| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | +| [`unleashIntegration`](./unleash/) | | | | | ✓ | ### Node.js Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`amqplibIntegration`](./amqplib/) | ✓ | | ✓ | | | [`awsLambdaWebIntegration`](./awslambdaweb/) | ✓ | | | ✓ | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | @@ -97,3 +97,4 @@ Depending on whether an integration enhances the functionality of a particular r | [`typesafeIntegration`](./typesafe/) | ✓ | | ✓ | | | [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | | [`pinoIntegration`](./pino/) | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | diff --git a/platform-includes/configuration/integrations/javascript.remix.mdx b/platform-includes/configuration/integrations/javascript.remix.mdx index 651fe9ea347ff..b90d1bd450b58 100644 --- a/platform-includes/configuration/integrations/javascript.remix.mdx +++ b/platform-includes/configuration/integrations/javascript.remix.mdx @@ -8,8 +8,8 @@ Depending on whether an integration enhances the functionality of a particular r ### Common Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`dedupeIntegration`](./dedupe/) | ✓ | ✓ | | | | [`eventFiltersIntegration`](./eventfilters/) | ✓ | ✓ | | | | [`functionToStringIntegration`](./functiontostring/) | ✓ | | | | @@ -20,37 +20,37 @@ Depending on whether an integration enhances the functionality of a particular r ### Browser Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | -| ----------------------------------------------------- | :--------------: | :--------: | :---------: | :--------: | :--------------------: | -| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | -| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | -| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | -| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | -| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | -| [`interactionsIntegration`](./interactions/) | | | ✓ | | | -| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | -| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | -| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | -| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | -| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | -| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | -| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | -| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | -| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | -| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | -| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | -| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | -| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | -| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | -| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | -| [`statsigIntegration`](./statsig/) | | | | | ✓ | -| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | -| [`unleashIntegration`](./unleash/) | | | | | ✓ | +| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | +| ---------------------------------------------------------------- | :-----------------: | :--------: | :---------: | :--------: | :--------------------: | +| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | +| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | +| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | +| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | +| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | +| [`interactionsIntegration`](./interactions/) | | | ✓ | | | +| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | +| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | +| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | +| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | +| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | +| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | +| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | +| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | +| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | +| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | +| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | +| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | +| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | +| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | +| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | +| [`statsigIntegration`](./statsig/) | | | | | ✓ | +| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | +| [`unleashIntegration`](./unleash/) | | | | | ✓ | ### Node.js Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`amqplibIntegration`](./amqplib/) | ✓ | | ✓ | | | [`awsLambdaWebIntegration`](./awslambdaweb/) | ✓ | | | ✓ | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | @@ -97,3 +97,4 @@ Depending on whether an integration enhances the functionality of a particular r | [`typesafeIntegration`](./typesafe/) | ✓ | | ✓ | | | [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | | [`pinoIntegration`](./pino/) | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | diff --git a/platform-includes/configuration/integrations/javascript.solidstart.mdx b/platform-includes/configuration/integrations/javascript.solidstart.mdx index 8a54f62c50c1f..44262f5509507 100644 --- a/platform-includes/configuration/integrations/javascript.solidstart.mdx +++ b/platform-includes/configuration/integrations/javascript.solidstart.mdx @@ -8,8 +8,8 @@ Depending on whether an integration enhances the functionality of a particular r ### Common Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`dedupeIntegration`](./dedupe/) | ✓ | ✓ | | | | [`eventFiltersIntegration`](./eventfilters/) | ✓ | ✓ | | | | [`functionToStringIntegration`](./functiontostring/) | ✓ | | | | @@ -20,37 +20,37 @@ Depending on whether an integration enhances the functionality of a particular r ### Browser Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | -| ----------------------------------------------------- | :--------------: | :--------: | :---------: | :--------: | :--------------------: | -| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | -| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | -| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | -| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | -| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | -| [`interactionsIntegration`](./interactions/) | | | ✓ | | | -| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | -| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | -| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | -| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | -| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | -| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | -| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | -| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | -| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | -| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | -| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | -| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | -| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | -| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | -| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | -| [`statsigIntegration`](./statsig/) | | | | | ✓ | -| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | -| [`unleashIntegration`](./unleash/) | | | | | ✓ | +| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | +| ---------------------------------------------------------------- | :-----------------: | :--------: | :---------: | :--------: | :--------------------: | +| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | +| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | +| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | +| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | +| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | +| [`interactionsIntegration`](./interactions/) | | | ✓ | | | +| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | +| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | +| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | +| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | +| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | +| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | +| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | +| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | +| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | +| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | +| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | +| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | +| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | +| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | +| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | +| [`statsigIntegration`](./statsig/) | | | | | ✓ | +| [`supabaseIntegration`](./supabase/) | | ✓ | ✓ | | | +| [`unleashIntegration`](./unleash/) | | | | | ✓ | ### Node.js Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`amqplibIntegration`](./amqplib/) | ✓ | | ✓ | | | [`awsLambdaWebIntegration`](./awslambdaweb/) | ✓ | | | ✓ | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | @@ -72,6 +72,7 @@ Depending on whether an integration enhances the functionality of a particular r | [`postgresIntegration`](./postgres/) | ✓ | | ✓ | | | [`redisIntegration`](./redis/) | ✓ | | ✓ | | | [`requestDataIntegration`](./requestdata/) | ✓ | | ✓ | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | | [`tediousIntegration`](./tedious/) | ✓ | | ✓ | | | [`dataloaderIntegration`](./dataloader/) | ✓ | | ✓ | | | [`childProcessIntegration`](./childProcess/) | ✓ | | | ✓ | diff --git a/platform-includes/configuration/integrations/javascript.sveltekit.mdx b/platform-includes/configuration/integrations/javascript.sveltekit.mdx index 9bdc2edaba282..d9ab94bd4c61e 100644 --- a/platform-includes/configuration/integrations/javascript.sveltekit.mdx +++ b/platform-includes/configuration/integrations/javascript.sveltekit.mdx @@ -8,8 +8,8 @@ Depending on whether an integration enhances the functionality of a particular r ### Common Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`dedupeIntegration`](./dedupe/) | ✓ | ✓ | | | | [`eventFiltersIntegration`](./eventfilters/) | ✓ | ✓ | | | | [`functionToStringIntegration`](./functiontostring/) | ✓ | | | | @@ -20,36 +20,36 @@ Depending on whether an integration enhances the functionality of a particular r ### Browser Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | -| ----------------------------------------------------- | :--------------: | :--------: | :---------: | :--------: | :--------------------: | -| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | -| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | -| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | -| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | -| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | -| [`interactionsIntegration`](./interactions/) | | | ✓ | | | -| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | -| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | -| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | -| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | -| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | -| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | -| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | -| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | -| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | -| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | -| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | -| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | -| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | -| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | -| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | -| [`statsigIntegration`](./statsig/) | | | | | ✓ | -| [`unleashIntegration`](./unleash/) | | | | | ✓ | +| | **Auto Enabled** | **Errors** | **Tracing** | **Replay** | **Additional Context** | +| ---------------------------------------------------------------- | :-----------------: | :--------: | :---------: | :--------: | :--------------------: | +| [`breadcrumbsIntegration`](./breadcrumbs/) | ✓ | | | | ✓ | +| [`browserApiErrorsIntegration`](./browserapierrors/) | ✓ | ✓ | | | | +| [`browserSessionIntegration`](./browsersession/) | ✓ | | | | ✓ | +| [`browserTracingIntegration`](./browsertracing/) | ✓ | | ✓ | | ✓ | +| [`fetchStreamPerformanceIntegration`](./fetchstreamperformance/) | | | ✓ | | | +| [`interactionsIntegration`](./interactions/) | | | ✓ | | | +| [`userTimingIntegration`](./usertiming/) | | | ✓ | | | +| [`webVitalsIntegration`](./webvitals/) | With BrowserTracing | | ✓ | | | +| [`globalHandlersIntegration`](./globalhandlers/) | ✓ | ✓ | | | | +| [`httpContextIntegration`](./httpcontext/) | ✓ | | | | ✓ | +| [`browserProfilingIntegration`](./browserprofiling/) | | | ✓ | | | +| [`contextLinesIntegration`](./contextlines/) | | ✓ | | | | +| [`featureFlagsIntegration`](./featureflags/) | | | | | ✓ | +| [`graphqlClientIntegration`](./graphqlclient/) | | | | | ✓ | +| [`httpClientIntegration`](./httpclient/) | | ✓ | | | | +| [`launchDarklyIntegration`](./launchdarkly/) | | | | | ✓ | +| [`moduleMetadataIntegration`](./modulemetadata/) | | | | | ✓ | +| [`openFeatureIntegration`](./openfeature/) | | | | | ✓ | +| [`replayCanvasIntegration`](./replaycanvas/) | | | | ✓ | | +| [`replayIntegration`](./replay/) | | | | ✓ | ✓ | +| [`reportingObserverIntegration`](./reportingobserver/) | | ✓ | | | | +| [`statsigIntegration`](./statsig/) | | | | | ✓ | +| [`unleashIntegration`](./unleash/) | | | | | ✓ | ### Node.js Integrations -| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | -| --------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | +| | **Auto Enabled** | **Errors** | **Tracing** | **Additional Context** | +| ---------------------------------------------------------- | :--------------: | :--------: | :---------: | :--------------------: | | [`amqplibIntegration`](./amqplib/) | ✓ | | ✓ | | | [`awsLambdaWebIntegration`](./awslambdaweb/) | ✓ | | | ✓ | | [`consoleIntegration`](./console/) | ✓ | | | ✓ | @@ -97,3 +97,4 @@ Depending on whether an integration enhances the functionality of a particular r | [`typesafeIntegration`](./typesafe/) | ✓ | | ✓ | | | [`zodErrorsIntegration`](./zodErrors/) | | | | ✓ | | [`pinoIntegration`](./pino/) | | ✓ | | | +| [`serveTunnelIntegration`](./servetunnel/) | | | | | diff --git a/platform-includes/configuration/sample-rate/dotnet.mdx b/platform-includes/configuration/sample-rate/dotnet.mdx index 513e0e52c4676..1c37c1b6d8e70 100644 --- a/platform-includes/configuration/sample-rate/dotnet.mdx +++ b/platform-includes/configuration/sample-rate/dotnet.mdx @@ -1,9 +1,9 @@ ```csharp // Add this to the SDK initialization callback -options.SampleRate = 0.25; +options.SampleRate = 0.25f; ``` ```fsharp // Add this to the SDK initialization callback -options.SampleRate <- 0.25 // Capture 25% +options.SampleRate <- Nullable 0.25f // Capture 25% ``` diff --git a/platform-includes/configuration/tunnel-browser-init/javascript.astro.mdx b/platform-includes/configuration/tunnel-browser-init/javascript.astro.mdx new file mode 100644 index 0000000000000..e5fd7022a3aa3 --- /dev/null +++ b/platform-includes/configuration/tunnel-browser-init/javascript.astro.mdx @@ -0,0 +1,6 @@ +```javascript {filename:sentry.client.config.ts} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + tunnel: true, +}); +``` diff --git a/platform-includes/configuration/tunnel-browser-init/javascript.mdx b/platform-includes/configuration/tunnel-browser-init/javascript.mdx new file mode 100644 index 0000000000000..62fccc01ecb07 --- /dev/null +++ b/platform-includes/configuration/tunnel-browser-init/javascript.mdx @@ -0,0 +1,6 @@ +```javascript {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + tunnel: true, +}); +``` diff --git a/platform-includes/configuration/tunnel-browser-init/javascript.nextjs.mdx b/platform-includes/configuration/tunnel-browser-init/javascript.nextjs.mdx new file mode 100644 index 0000000000000..de0506a736ec2 --- /dev/null +++ b/platform-includes/configuration/tunnel-browser-init/javascript.nextjs.mdx @@ -0,0 +1,6 @@ +```javascript {filename:instrumentation-client.ts} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + tunnel: true, +}); +``` diff --git a/platform-includes/configuration/tunnel-browser-init/javascript.nuxt.mdx b/platform-includes/configuration/tunnel-browser-init/javascript.nuxt.mdx new file mode 100644 index 0000000000000..e5fd7022a3aa3 --- /dev/null +++ b/platform-includes/configuration/tunnel-browser-init/javascript.nuxt.mdx @@ -0,0 +1,6 @@ +```javascript {filename:sentry.client.config.ts} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + tunnel: true, +}); +``` diff --git a/platform-includes/configuration/tunnel-browser-init/javascript.solidstart.mdx b/platform-includes/configuration/tunnel-browser-init/javascript.solidstart.mdx new file mode 100644 index 0000000000000..7f4092f7336c8 --- /dev/null +++ b/platform-includes/configuration/tunnel-browser-init/javascript.solidstart.mdx @@ -0,0 +1,6 @@ +```jsx {filename:src/entry-client.tsx} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + tunnel: true, +}); +``` diff --git a/platform-includes/configuration/tunnel-browser-init/javascript.sveltekit.mdx b/platform-includes/configuration/tunnel-browser-init/javascript.sveltekit.mdx new file mode 100644 index 0000000000000..703c2c561088e --- /dev/null +++ b/platform-includes/configuration/tunnel-browser-init/javascript.sveltekit.mdx @@ -0,0 +1,6 @@ +```javascript {filename:src/hooks.client.(js|ts)} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + tunnel: true, +}); +``` diff --git a/platform-includes/configuration/tunnel-browser-init/javascript.tanstackstart-react.mdx b/platform-includes/configuration/tunnel-browser-init/javascript.tanstackstart-react.mdx new file mode 100644 index 0000000000000..0232778842243 --- /dev/null +++ b/platform-includes/configuration/tunnel-browser-init/javascript.tanstackstart-react.mdx @@ -0,0 +1,6 @@ +```tsx {filename:src/instrument.client.ts} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + tunnel: true, +}); +``` diff --git a/platform-includes/configuration/tunnel-manual-route/javascript.bun.mdx b/platform-includes/configuration/tunnel-manual-route/javascript.bun.mdx new file mode 100644 index 0000000000000..6b19fb452af7f --- /dev/null +++ b/platform-includes/configuration/tunnel-manual-route/javascript.bun.mdx @@ -0,0 +1,14 @@ +```javascript +import * as Sentry from "@sentry/bun"; + +Bun.serve({ + routes: { + "/tunnel": { + POST: (request) => Sentry.handleTunnelRequest(request), + }, + }, + fetch(request) { + // Your app + }, +}); +``` diff --git a/platform-includes/configuration/tunnel-manual-route/javascript.cloudflare.mdx b/platform-includes/configuration/tunnel-manual-route/javascript.cloudflare.mdx new file mode 100644 index 0000000000000..5ca3941b6826b --- /dev/null +++ b/platform-includes/configuration/tunnel-manual-route/javascript.cloudflare.mdx @@ -0,0 +1,22 @@ +```javascript +import * as Sentry from "@sentry/cloudflare"; + +export default Sentry.withSentry( + (env) => ({ + dsn: "___PUBLIC_DSN___", + integrations: [ + Sentry.serveTunnelIntegration({ intercept: false, path: "/tunnel" }), + ], + }), + { + async fetch(request, env, ctx) { + const { pathname } = new URL(request.url); + if (request.method === "POST" && pathname === "/tunnel") { + return Sentry.handleTunnelRequest(request); + } + + // Your app + }, + } +); +``` diff --git a/platform-includes/configuration/tunnel-manual-route/javascript.deno.mdx b/platform-includes/configuration/tunnel-manual-route/javascript.deno.mdx new file mode 100644 index 0000000000000..09bbbb85878c5 --- /dev/null +++ b/platform-includes/configuration/tunnel-manual-route/javascript.deno.mdx @@ -0,0 +1,12 @@ +```javascript +import * as Sentry from "@sentry/deno"; + +Deno.serve((request) => { + const { pathname } = new URL(request.url); + if (request.method === "POST" && pathname === "/tunnel") { + return Sentry.handleTunnelRequest(request); + } + + // Your app +}); +``` diff --git a/platform-includes/configuration/tunnel-manual-route/javascript.elysia.mdx b/platform-includes/configuration/tunnel-manual-route/javascript.elysia.mdx new file mode 100644 index 0000000000000..7c9fa90a75f4d --- /dev/null +++ b/platform-includes/configuration/tunnel-manual-route/javascript.elysia.mdx @@ -0,0 +1,8 @@ +```javascript +import { Elysia } from "elysia"; +import * as Sentry from "@sentry/elysia"; + +const app = new Elysia().post("/tunnel", ({ request }) => + Sentry.handleTunnelRequest(request) +); +``` diff --git a/platform-includes/configuration/tunnel-manual-route/javascript.mdx b/platform-includes/configuration/tunnel-manual-route/javascript.mdx new file mode 100644 index 0000000000000..9ec59dfcd4caf --- /dev/null +++ b/platform-includes/configuration/tunnel-manual-route/javascript.mdx @@ -0,0 +1,43 @@ + + +```javascript {tabTitle:Express} +import express from "express"; +import * as Sentry from "___SDK_PACKAGE___"; + +const app = express(); + +app.post("/tunnel", (req, res) => Sentry.handleTunnelRequest(req, res)); +``` + +```javascript {tabTitle:Fetch API} +import * as Sentry from "___SDK_PACKAGE___"; + +export function POST(request) { + return Sentry.handleTunnelRequest(request); +} +``` + + + + + +```javascript {tabTitle:Express} +import express from "express"; +import * as Sentry from "@sentry/node"; + +const app = express(); + +app.post("/tunnel", (req, res) => Sentry.handleTunnelRequest(req, res)); +``` + +```javascript {tabTitle:Fetch API} +import * as Sentry from "@sentry/node"; + +export function POST(request) { + return Sentry.handleTunnelRequest(request); +} +``` + + + +Add the route before any middleware that reads the request body. diff --git a/platform-includes/configuration/tunnel-manual-route/javascript.nextjs.mdx b/platform-includes/configuration/tunnel-manual-route/javascript.nextjs.mdx new file mode 100644 index 0000000000000..e8fd86513fdf1 --- /dev/null +++ b/platform-includes/configuration/tunnel-manual-route/javascript.nextjs.mdx @@ -0,0 +1,7 @@ +```typescript {filename:app/tunnel/route.ts} +import * as Sentry from "@sentry/nextjs"; + +export function POST(request: Request) { + return Sentry.handleTunnelRequest(request); +} +``` diff --git a/platform-includes/configuration/tunnel-manual-route/javascript.sveltekit.mdx b/platform-includes/configuration/tunnel-manual-route/javascript.sveltekit.mdx new file mode 100644 index 0000000000000..06575d3b5c075 --- /dev/null +++ b/platform-includes/configuration/tunnel-manual-route/javascript.sveltekit.mdx @@ -0,0 +1,7 @@ +```typescript {filename:src/routes/tunnel/+server.ts} +import * as Sentry from "@sentry/sveltekit"; +import type { RequestHandler } from "./$types"; + +export const POST: RequestHandler = ({ request }) => + Sentry.handleTunnelRequest(request); +``` diff --git a/platform-includes/configuration/tunnel-server-init/javascript.astro.mdx b/platform-includes/configuration/tunnel-server-init/javascript.astro.mdx new file mode 100644 index 0000000000000..5bd72e5f4fb07 --- /dev/null +++ b/platform-includes/configuration/tunnel-server-init/javascript.astro.mdx @@ -0,0 +1,6 @@ +```javascript {filename:sentry.server.config.ts} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration()], +}); +``` diff --git a/platform-includes/configuration/tunnel-server-init/javascript.cloudflare.mdx b/platform-includes/configuration/tunnel-server-init/javascript.cloudflare.mdx new file mode 100644 index 0000000000000..cc492438015c2 --- /dev/null +++ b/platform-includes/configuration/tunnel-server-init/javascript.cloudflare.mdx @@ -0,0 +1,13 @@ +```javascript {4} +export default Sentry.withSentry( + (env) => ({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration()], + }), + { + async fetch(request, env, ctx) { + // Your app + }, + } +); +``` diff --git a/platform-includes/configuration/tunnel-server-init/javascript.mdx b/platform-includes/configuration/tunnel-server-init/javascript.mdx new file mode 100644 index 0000000000000..8e68d0296ed58 --- /dev/null +++ b/platform-includes/configuration/tunnel-server-init/javascript.mdx @@ -0,0 +1,6 @@ +```javascript {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration()], +}); +``` diff --git a/platform-includes/configuration/tunnel-server-init/javascript.nextjs.mdx b/platform-includes/configuration/tunnel-server-init/javascript.nextjs.mdx new file mode 100644 index 0000000000000..d5129db86745d --- /dev/null +++ b/platform-includes/configuration/tunnel-server-init/javascript.nextjs.mdx @@ -0,0 +1,15 @@ +```javascript {tabTitle:Server} {filename:sentry.server.config.ts} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration()], +}); +``` + +```javascript {tabTitle:Edge} {filename:sentry.edge.config.ts} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration()], +}); +``` + +Add the integration to both files. diff --git a/platform-includes/configuration/tunnel-server-init/javascript.nuxt.mdx b/platform-includes/configuration/tunnel-server-init/javascript.nuxt.mdx new file mode 100644 index 0000000000000..5bd72e5f4fb07 --- /dev/null +++ b/platform-includes/configuration/tunnel-server-init/javascript.nuxt.mdx @@ -0,0 +1,6 @@ +```javascript {filename:sentry.server.config.ts} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration()], +}); +``` diff --git a/platform-includes/configuration/tunnel-server-init/javascript.solidstart.mdx b/platform-includes/configuration/tunnel-server-init/javascript.solidstart.mdx new file mode 100644 index 0000000000000..7df51ae36aed2 --- /dev/null +++ b/platform-includes/configuration/tunnel-server-init/javascript.solidstart.mdx @@ -0,0 +1,20 @@ +```typescript {tabTitle:SolidStart 2} {filename:server/plugins/sentry.ts} {7} +import * as Sentry from "@sentry/solidstart"; +import { definePlugin } from "nitro"; + +export default definePlugin(() => { + Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration()], + }); +}); +``` + +```javascript {tabTitle:SolidStart 1} {filename:src/instrument.server.ts} {5} +import * as Sentry from "@sentry/solidstart"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration()], +}); +``` diff --git a/platform-includes/configuration/tunnel-server-init/javascript.sveltekit.mdx b/platform-includes/configuration/tunnel-server-init/javascript.sveltekit.mdx new file mode 100644 index 0000000000000..4e26d56ba28be --- /dev/null +++ b/platform-includes/configuration/tunnel-server-init/javascript.sveltekit.mdx @@ -0,0 +1,6 @@ +```javascript {filename:src/instrumentation.server.(js|ts)} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration()], +}); +``` diff --git a/platform-includes/configuration/tunnel-server-init/javascript.tanstackstart-react.mdx b/platform-includes/configuration/tunnel-server-init/javascript.tanstackstart-react.mdx new file mode 100644 index 0000000000000..8179385fa588c --- /dev/null +++ b/platform-includes/configuration/tunnel-server-init/javascript.tanstackstart-react.mdx @@ -0,0 +1,6 @@ +```javascript {filename:instrument.server.mjs} {3} +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [Sentry.serveTunnelIntegration()], +}); +``` diff --git a/platform-includes/crons/requirements/java.mdx b/platform-includes/crons/requirements/java.mdx index 13baa55a15e56..510d0678eb16c 100644 --- a/platform-includes/crons/requirements/java.mdx +++ b/platform-includes/crons/requirements/java.mdx @@ -6,5 +6,5 @@ - Send a monitor configuration from your code as shown below, and Sentry creates the monitor on the first check-in. You can also [create the monitor in Sentry](https://sentry.io/issues/alerts/new/crons/) instead. -- [Create the monitor in Sentry](https://sentry.io/issues/alerts/new/crons/) first. `@SentryCheckIn` does not send a monitor configuration, so Sentry drops check-ins for a slug that has no monitor. +- From Sentry Java SDK version `8.64.0`, `@SentryCheckIn(upsertMonitorConfig = true)` sends a monitor configuration based on the method's `@Scheduled` annotation, and Sentry creates the monitor on the first check-in. Without it, on older SDK versions, or for schedules that can't be converted, [create the monitor in Sentry](https://sentry.io/issues/alerts/new/crons/) first, because Sentry drops check-ins for a slug that has no monitor. diff --git a/platform-includes/crons/setup/java.spring-boot.mdx b/platform-includes/crons/setup/java.spring-boot.mdx index a711aa8b2bcdb..b48a78d756b9d 100644 --- a/platform-includes/crons/setup/java.spring-boot.mdx +++ b/platform-includes/crons/setup/java.spring-boot.mdx @@ -52,6 +52,30 @@ public class CustomJob { } ``` +### Monitor Configuration From `@Scheduled` + +From Sentry Java SDK version `8.64.0`, set `upsertMonitorConfig = true` and `@SentryCheckIn` reads the method's `@Scheduled` annotation and sends a monitor configuration with the in-progress check-in, so Sentry creates the monitor, or updates its schedule, from your code: + +```java +@Scheduled(cron = "0 0 * * * *") +@SentryCheckIn(value = "", upsertMonitorConfig = true) // 👈 +void execute() { + // your task code +} +``` + +The schedule is converted like this: + +- `cron`: a Spring cron expression with a fixed seconds field (for example `0 0 * * * *`) is sent as a crontab schedule without the seconds. If the seconds field isn't `0`, a check-in margin of 2 minutes is sent too, since the job checks in up to 59 seconds after the minute Sentry expects. This replaces a margin set in Sentry; set a larger `options.cron` default check-in margin to keep it. Spring macros such as `@hourly` and `@daily` are supported. +- `fixedRate` (including `fixedRateString`, such as `"5m"` or `"PT5M"`, and `timeUnit`): sent as an interval schedule when the period is a whole number of minutes. `fixedDelay` jobs send no monitor config. +- `zone`: sent as the monitor's timezone for cron schedules. Without `zone`, the JVM's default time zone is sent, since that's where Spring runs the job. It must be an IANA time zone ID such as `Europe/Vienna`; whole-hour offsets such as `GMT+2` are sent as `Etc/GMT-2`. + +Placeholders such as `${app.cleanup.cron}` are resolved. No configuration is sent for cron expressions with variable seconds (for example `*/30 * * * * *`), cron expressions that set both day-of-month and day-of-week (on Spring 5.3 and later, a day-of-month step such as `0 0 9 */2 * MON` is converted; on older Spring versions, none are), `#5` days of week on Spring 5.3 and later, cron syntax Sentry doesn't support (such as `15W`, `L-3`, or wrap-around ranges like `22-2`), other time zones, periods that aren't whole minutes, methods with more than one `@Scheduled`, or heartbeat check-ins. For those, for methods without `upsertMonitorConfig = true`, and for older SDK versions, [create the monitor in Sentry](https://sentry.io/issues/alerts/new/crons/) first. + +Sentry only updates the fields that were sent. Margins, max runtime, and thresholds configured in Sentry are kept unless you set defaults for them in `options.cron`, which are sent only with check-ins that carry a monitor configuration. + +When you turn on `upsertMonitorConfig` for a monitor that already exists, it gets the schedule and timezone from `@Scheduled` (the JVM's default time zone if `zone` isn't set), overwriting the ones set in Sentry. + ## Heartbeat Heartbeat monitoring notifies Sentry of a job's status through one check-in. This setup will only notify you if your job didn't start when expected (missed). If you need to track a job to see if it exceeded its maximum runtime (failed), use check-ins instead. To start sending heartbeats simply add the `@SentryCheckIn(monitorSlug = "", heartbeat = true)` annotation to the method you want to send heartbeats for. diff --git a/platform-includes/debug-files/unity.mdx b/platform-includes/debug-files/unity.mdx new file mode 100644 index 0000000000000..54fbdc5d3a923 --- /dev/null +++ b/platform-includes/debug-files/unity.mdx @@ -0,0 +1,5 @@ +Files can be uploaded using the `debug-files upload` command. This command scans a given folder recursively for files and uploads them to Sentry: + +```bash +sentry-cli debug-files upload --il2cpp-mapping --org ___ORG_SLUG___ --project ___PROJECT_SLUG___ PATH_TO_BUILD_OUTPUT +``` diff --git a/platform-includes/distributed-tracing/custom-instrumentation/python.mdx b/platform-includes/distributed-tracing/custom-instrumentation/python.mdx index 21ff75fe96ad5..a81972d725175 100644 --- a/platform-includes/distributed-tracing/custom-instrumentation/python.mdx +++ b/platform-includes/distributed-tracing/custom-instrumentation/python.mdx @@ -4,7 +4,7 @@ This page describes how to manually propagate trace information into and out of -This page covers both transaction mode (default) and stream mode. See Streamed Spans to learn more. +The examples on this page are for SDK `3.x`. The **SDK 2.x** tabs show the equivalent code for the default transaction mode of SDK `2.x`. If you use stream mode in SDK `2.x`, follow the **SDK 3.x** examples, but call the tracing functions on `sentry_sdk.traces` (for example, `sentry_sdk.traces.start_span()`) and set `trace_lifecycle="stream"` in `sentry_sdk.init()`. @@ -17,34 +17,35 @@ Incoming tracing information has to be extracted and stored in memory for later - You also can pick up tracing information from environment variables. -In **transaction mode**, `sentry_sdk.continue_trace()` returns a transaction, but does not start it. To start the transaction, use `start_transaction()`. -In **stream mode**, `sentry_sdk.traces.continue_trace()` replaces `sentry_sdk.continue_trace()` and is not a context manager. The next span created with `sentry_sdk.traces.start_span()` picks it up automatically. +`sentry_sdk.continue_trace()` isn't a context manager and doesn't start a span. The next span created with `sentry_sdk.start_span()` picks up the incoming trace automatically. + +In SDK `2.x`, `sentry_sdk.continue_trace()` returns a transaction, but doesn't start it. To start the transaction, use `start_transaction()`. Here's an example of how to extract and store incoming tracing information using `continue_trace()`: -```python {tabTitle:Transaction Mode (Default)} +```python {tabTitle:SDK 3.x} import sentry_sdk from my_project import get_incoming_headers_as_dict headers = get_incoming_headers_as_dict() -transaction = sentry_sdk.continue_trace(headers) -with sentry_sdk.start_transaction(transaction): +sentry_sdk.continue_trace(headers) + +with sentry_sdk.start_span(name="handle request"): ... ``` -```python {tabTitle:Stream Mode} +```python {tabTitle:SDK 2.x} import sentry_sdk from my_project import get_incoming_headers_as_dict headers = get_incoming_headers_as_dict() -sentry_sdk.traces.continue_trace(headers) - -with sentry_sdk.traces.start_span(name="handle request"): +transaction = sentry_sdk.continue_trace(headers) +with sentry_sdk.start_transaction(transaction): ... ``` @@ -53,21 +54,21 @@ In these examples, `get_incoming_headers_as_dict()` returns a dictionary that co ## 2. Start a New Trace - This step only applies to stream mode and is not available in transaction - mode. + In SDK `2.x`, this step only applies to stream mode, where the function is + `sentry_sdk.traces.new_trace()`. It isn't available in transaction mode. -In stream mode, if you need to start a completely new trace unconnected to the current one, use `sentry_sdk.traces.new_trace()`. This is useful for background jobs or scheduled tasks where you want a clean trace boundary: +If you need to start a completely new trace unconnected to the current one, use `sentry_sdk.new_trace()`. This is useful for background jobs or scheduled tasks where you want a clean trace boundary: ```python import sentry_sdk -with sentry_sdk.traces.start_span(name="span in trace 1"): +with sentry_sdk.start_span(name="span in trace 1"): ... -sentry_sdk.traces.new_trace() +sentry_sdk.new_trace() -with sentry_sdk.traces.start_span(name="span in trace 2"): +with sentry_sdk.start_span(name="span in trace 2"): # This span is the root of a new, separate trace ... ``` diff --git a/platform-includes/distributed-tracing/custom-instrumentation/unity.mdx b/platform-includes/distributed-tracing/custom-instrumentation/unity.mdx index 424e9fd811f62..e9e3e7ee68c6e 100644 --- a/platform-includes/distributed-tracing/custom-instrumentation/unity.mdx +++ b/platform-includes/distributed-tracing/custom-instrumentation/unity.mdx @@ -21,6 +21,7 @@ If you're using .NET's `HttpClient`, you can extract trace headers from the resp using System.Linq; using System.Net.Http; using System.Threading.Tasks; +using Sentry.Unity; using UnityEngine; public class TraceReceiver : MonoBehaviour @@ -73,6 +74,7 @@ For WebGL builds or if you prefer Unity's coroutine-based approach, use `UnityWe ```csharp using System.Collections; +using Sentry.Unity; using UnityEngine; using UnityEngine.Networking; @@ -128,7 +130,7 @@ The easiest way to propagate traces is to use .NET's `HttpClient` with `SentryHt ```csharp using System.Net.Http; using System.Threading.Tasks; -using Sentry.Http; +using Sentry; using UnityEngine; public class TraceSender : MonoBehaviour @@ -164,6 +166,7 @@ For WebGL builds or if you prefer Unity's coroutine-based approach, you can manu ```csharp using System.Collections; +using Sentry.Unity; using UnityEngine; using UnityEngine.Networking; @@ -171,8 +174,13 @@ public class TraceSender : MonoBehaviour { IEnumerator SendRequest() { - var jsonData = "{}"; - using var www = UnityWebRequest.Post("https://example.com/api/action", jsonData, "application/json"); + var jsonData = System.Text.Encoding.UTF8.GetBytes("{}"); + using var www = new UnityWebRequest("https://example.com/api/action", UnityWebRequest.kHttpVerbPOST) + { + uploadHandler = new UploadHandlerRaw(jsonData), + downloadHandler = new DownloadHandlerBuffer() + }; + www.SetRequestHeader("Content-Type", "application/json"); // Add Sentry trace headers to propagate the trace var traceHeader = SentrySdk.GetTraceHeader(); diff --git a/platform-includes/distributed-tracing/how-to-use/javascript.remix.mdx b/platform-includes/distributed-tracing/how-to-use/javascript.remix.mdx index 41f2df3b033b6..ca6db1c7d0af6 100644 --- a/platform-includes/distributed-tracing/how-to-use/javascript.remix.mdx +++ b/platform-includes/distributed-tracing/how-to-use/javascript.remix.mdx @@ -25,7 +25,7 @@ if (serverTimingValue) { return response; ``` -See the [Hydrogen on Cloudflare guide](/platforms/javascript/guides/cloudflare/frameworks/hydrogen-remix/#trace-propagation) for a complete example. +See the [Hydrogen with Remix guide](/platforms/javascript/guides/remix/hydrogen/#trace-propagation) for a complete example.
diff --git a/platform-includes/enriching-events/breadcrumbs/automatic-breadcrumbs/unity.mdx b/platform-includes/enriching-events/breadcrumbs/automatic-breadcrumbs/unity.mdx index 0a9565d058b51..2f0dedb40eb54 100644 --- a/platform-includes/enriching-events/breadcrumbs/automatic-breadcrumbs/unity.mdx +++ b/platform-includes/enriching-events/breadcrumbs/automatic-breadcrumbs/unity.mdx @@ -1,13 +1,15 @@ The Unity SDK captures breadcrumbs automatically for: - **Unity Logs** - - Unity logs from the built-in logging system are captured when using the default `UnityApplicationLoggingIntegration`: + - Unity logs from the built-in logging system are captured when using the default `UnityApplicationLoggingIntegration`: - `Debug.Log` (captured at `Info` level) - `Debug.LogWarning` (captured at `Warning` level) - - `Debug.LogError` and `Debug.LogAssert` (captured at `Error` level) + - `Debug.LogError` and `Debug.LogAssertion` (captured at `Error` level; Unity only runs `Debug.LogAssertion` in the editor and development builds) + - [`AddBreadcrumbsForLogType`](/platforms/unity/configuration/options/#AddBreadcrumbsForLogType) turns log breadcrumbs on or off for each log type. + - When structured logs are on, the SDK doesn't add log breadcrumbs unless you set `AddBreadcrumbsWithStructuredLogs` to `true`. - **Scene Events** -- Scene events are captured when using `SceneManagerIntegration`: + - Scene events are captured when using `SceneManagerIntegration`: - Scene loaded - Scene unloaded - Active scene changed @@ -24,4 +26,4 @@ The Unity SDK captures breadcrumbs automatically for: - Captured when native support is enabled (default for Android, iOS, macOS, and other platforms): - **Android**: Activity lifecycle, system events, user interactions, and HTTP requests via the Sentry Android SDK - **iOS/macOS**: Application lifecycle, UIControl events, system events (battery, memory, orientation), and HTTP requests via the Sentry Cocoa SDK - - **Other platforms**: Native crash handling and scope synchronization via `sentry-native` + - **Other platforms**: The SDK syncs the C# breadcrumbs to the native SDK, so native crashes include them. See Scope Sync. diff --git a/platform-includes/enriching-events/scopes/configure-scope/dotnet.mdx b/platform-includes/enriching-events/scopes/configure-scope/dotnet.mdx index e4dae22941902..3ed47f913d2bd 100644 --- a/platform-includes/enriching-events/scopes/configure-scope/dotnet.mdx +++ b/platform-includes/enriching-events/scopes/configure-scope/dotnet.mdx @@ -2,7 +2,7 @@ SentrySdk.ConfigureScope(scope => { scope.SetTag("my-tag", "my value"); - scope.User = new User + scope.User = new SentryUser { Id = "42", Email = "john.doe@example.com" @@ -16,7 +16,7 @@ open Sentry SentrySdk.ConfigureScope ( fun scope -> scope.SetTag ("my-tag", "my value") - scope.User <- User ( + scope.User <- SentryUser ( Id = "42", Email = "john.doe@example.com" ) diff --git a/platform-includes/enriching-events/scopes/configure-scope/unity.mdx b/platform-includes/enriching-events/scopes/configure-scope/unity.mdx new file mode 100644 index 0000000000000..ff24947c92843 --- /dev/null +++ b/platform-includes/enriching-events/scopes/configure-scope/unity.mdx @@ -0,0 +1,14 @@ +```csharp +using Sentry; +using Sentry.Unity; + +SentrySdk.ConfigureScope(scope => +{ + scope.SetTag("my-tag", "my value"); + scope.User = new SentryUser + { + Id = "42", + Email = "john.doe@example.com" + }; +}); +``` diff --git a/platform-includes/enriching-events/set-tag/dotnet.nlog.mdx b/platform-includes/enriching-events/set-tag/dotnet.nlog.mdx index 346787f21dac8..205b0cf88aa54 100644 --- a/platform-includes/enriching-events/set-tag/dotnet.nlog.mdx +++ b/platform-includes/enriching-events/set-tag/dotnet.nlog.mdx @@ -15,7 +15,7 @@ For more information on how to dynamically set event tags via `NLog.config`, see - + @@ -29,7 +29,6 @@ For more information on how to dynamically set event tags via `NLog.config`, see ```csharp LogManager.Configuration.AddSentry(options => { - options.Dsn = "___PUBLIC_DSN___"; // Tags configured on the target can use NLog layouts options.AddTag("logger", "${logger}"); }); @@ -38,7 +37,6 @@ LogManager.Configuration.AddSentry(options => ```fsharp LogManager.Configuration.AddSentry( fun options -> - options.Dsn <- "___PUBLIC_DSN___" // Tags configured on the target can use NLog layouts options.AddTag("logger", "${logger}") ) |> ignore diff --git a/platform-includes/enriching-events/set-user/dotnet.nlog.mdx b/platform-includes/enriching-events/set-user/dotnet.nlog.mdx index 28ec6343db210..5a0a64254a568 100644 --- a/platform-includes/enriching-events/set-user/dotnet.nlog.mdx +++ b/platform-includes/enriching-events/set-user/dotnet.nlog.mdx @@ -15,7 +15,7 @@ - + @@ -29,7 +29,7 @@ ```csharp SentrySdk.ConfigureScope(scope => { - scope.User = new User + scope.User = new SentryUser { Email = "john.doe@example.com" }; @@ -39,7 +39,7 @@ SentrySdk.ConfigureScope(scope => ```fsharp SentrySdk.ConfigureScope( fun scope -> - scope.User <- User(Email = "john.doe@example.com") + scope.User <- SentryUser(Email = "john.doe@example.com") () ) ``` diff --git a/platform-includes/getting-started-capture-errors/javascript.fastify.mdx b/platform-includes/getting-started-capture-errors/javascript.fastify.mdx index f8b66c63d354f..7d3008e9a8f45 100644 --- a/platform-includes/getting-started-capture-errors/javascript.fastify.mdx +++ b/platform-includes/getting-started-capture-errors/javascript.fastify.mdx @@ -1,3 +1,3 @@ ### Report Unhandled Exceptions -`fastifyIntegration` captures errors from your routes and hooks automatically, so you don't need to register a Sentry error handler. Errors with a 3xx or 4xx status code are skipped. To change which errors are captured, use the `shouldHandleError` option. +`fastifyIntegration` captures errors from your routes and hooks automatically, so you don't need to register a Sentry error handler. Errors with a 3xx or 4xx status code are skipped. To change which errors are captured, use the `shouldHandleError` option. diff --git a/platform-includes/getting-started-cloudflare/javascript.astro.mdx b/platform-includes/getting-started-cloudflare/javascript.astro.mdx new file mode 100644 index 0000000000000..d28113db03d3f --- /dev/null +++ b/platform-includes/getting-started-cloudflare/javascript.astro.mdx @@ -0,0 +1,258 @@ +### Install the Sentry SDKs + +Install both `@sentry/astro` and `@sentry/cloudflare`: + +```bash {tabTitle:npm} +npm install @sentry/astro @sentry/cloudflare +``` + +```bash {tabTitle:yarn} +yarn add @sentry/astro @sentry/cloudflare +``` + +```bash {tabTitle:pnpm} +pnpm add @sentry/astro @sentry/cloudflare +``` + +## Configure + +### Wrangler Configuration + + + +### Configure Custom Entry Point + +Astro 6 with `@astrojs/cloudflare` v13+ supports custom entry points directly from `wrangler.jsonc`. Update your wrangler configuration to point to a custom Sentry entry point: + +```jsonc {filename:wrangler.jsonc} +{ + "main": "./sentry.server.config.ts", + // ... other configuration +} +``` + +Create a `sentry.server.config.ts` file in the root of your project that wraps the Astro Cloudflare handler with Sentry: + +```typescript {filename:sentry.server.config.ts} +import * as Sentry from "@sentry/cloudflare"; +import handler from "@astrojs/cloudflare/entrypoints/server"; + +export default Sentry.withSentry( + (env) => ({ + dsn: env.SENTRY_DSN, + // ___PRODUCT_OPTION_START___ performance + // Define how likely traces are sampled. Adjust this value in production, + // or use tracesSampler for greater control. + tracesSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ performance + }), + handler +); +``` + +### Register the Sentry Integration + +Follow [Astro's Cloudflare deployment guide](https://docs.astro.build/en/guides/deploy/cloudflare/) if you haven't already. Then add the Sentry integration to your `astro.config.mjs` alongside the Cloudflare adapter. + +```javascript {filename:astro.config.mjs} +import { defineConfig } from "astro/config"; +import cloudflare from "@astrojs/cloudflare"; +import sentry from "@sentry/astro"; + +export default defineConfig({ + adapter: cloudflare(), + integrations: [sentry()], +}); +``` + +### Configure Client-side Sentry + +Create a `sentry.client.config.(ts|js)` file in the root of your project. In this file, import and initialize Sentry for the client: + +```javascript {filename:sentry.client.config.(ts|js)} +import * as Sentry from "@sentry/astro"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + + integrations: [ + // ___PRODUCT_OPTION_START___ performance + Sentry.browserTracingIntegration(), + // ___PRODUCT_OPTION_END___ performance + // ___PRODUCT_OPTION_START___ session-replay + Sentry.replayIntegration(), + // ___PRODUCT_OPTION_END___ session-replay + // ___PRODUCT_OPTION_START___ user-feedback + Sentry.feedbackIntegration({ + // Additional SDK configuration goes in here, for example: + colorScheme: "system", + }), + // ___PRODUCT_OPTION_END___ user-feedback + ], + // ___PRODUCT_OPTION_START___ performance + + // Define how likely traces are sampled. Adjust this value in production, + // or use tracesSampler for greater control. + tracesSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ performance + // ___PRODUCT_OPTION_START___ session-replay + + // This sets the sample rate to be 10%. You may want this to be 100% while + // in development and sample at a lower rate in production + replaysSessionSampleRate: 0.1, + + // If the entire session is not sampled, use the below sample rate to sample + // sessions when an error occurs. + replaysOnErrorSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ session-replay +}); +``` + +### Configure Server-side Sentry + +Server-side Sentry is already configured in your custom entry point file (`sentry.server.config.ts`) created in the previous step. + +### Add Readable Stack Traces With Source Maps + +To upload source maps for clear error stack traces, add your Sentry auth token, organization, and project slugs in the `sentry` options inside `astro.config.mjs`: + +```javascript {filename:astro.config.mjs} +import { defineConfig } from "astro/config"; +import cloudflare from "@astrojs/cloudflare"; +import sentry from "@sentry/astro"; + +export default defineConfig({ + adapter: cloudflare(), + integrations: [ + sentry({ + org: "___ORG_SLUG___", + project: "___PROJECT_SLUG___", + // store your auth token in an environment variable + authToken: process.env.SENTRY_AUTH_TOKEN, + }), + ], +}); +``` + +To keep your auth token secure, set the `SENTRY_AUTH_TOKEN` environment variable in your build environment: + + + +```bash {filename:.env.sentry-build-plugin} +SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ +``` + + + +### Control the Data You Send to Sentry (Optional) + + + +## Verify Your Setup + +Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. + +### Issues + + +To verify that Sentry captures errors and creates issues in your Sentry project, +create a test page, for example, at `src/pages/test.astro` with two buttons. + +```html {filename: test.astro} + + + + +``` + +Then also create the route we're calling in our test page, like `src/pages/api/test-error.(js|ts)`: + +Next, open your test page in a browser and click the buttons to trigger a frontend error and an error in the API route. + +```javascript {filename: test-error.(js|ts)} +export async function GET() { + throw new Error("Sentry Example API Route Error"); +} +``` + + + +### Tracing + +To test tracing, create a custom span to measure the time it takes for the API request to complete: + +```html {filename: test.astro} + + + +``` + + + + + + + + + + + +### View Captured Data in Sentry + +Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). + + + +## Next Steps + +At this point, you should have integrated Sentry into your Astro application and should already be sending data to your Sentry project. + +Now's a good time to customize your setup and look into more advanced topics. +Our next recommended steps for you are: + +- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup +- Continue to customize your configuration +- Learn how to manually capture errors +- Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts + + + +- Find various topics in Troubleshooting +- [Get support](https://www.sentry.help/en/) + + diff --git a/platform-includes/getting-started-cloudflare/javascript.nextjs.mdx b/platform-includes/getting-started-cloudflare/javascript.nextjs.mdx new file mode 100644 index 0000000000000..cc837dc1b1e5c --- /dev/null +++ b/platform-includes/getting-started-cloudflare/javascript.nextjs.mdx @@ -0,0 +1,209 @@ +## Prerequisites + +You need: + +- A Sentry [account](https://sentry.io/signup/) and [project](/product/projects/) +- A Next.js application that runs on Cloudflare Workers with the [OpenNext Cloudflare adapter](https://opennext.js.org/cloudflare) or [vinext](https://github.com/cloudflare/vinext) + + + If you haven't deployed a Next.js app to Cloudflare Workers before, follow + Cloudflare's [Next.js deployment + guide](https://developers.cloudflare.com/workers/framework-guides/web-apps/nextjs/) + first. + + + + +## Install + +### Run the Installation Wizard + +Run the Sentry wizard to automatically install the SDK and configure Sentry in your Next.js application: + +```bash +npx @sentry/wizard@latest -i nextjs +``` + +The wizard asks whether you want to enable **Tracing** and **Session Replay**, route browser requests through your server to avoid ad blockers, and create an example page. To match the configuration in this guide, answer **Yes** to each. + +Prefer to set things up yourself? Check out the [Manual Setup](/platforms/javascript/guides/nextjs/manual-setup/) guide. + +## Configure + +**Error Monitoring** starts working as soon as you call `Sentry.init()`. **Logs** and **Application Metrics** need no extra configuration, and you'll learn how to send them in steps [#3](#send-logs) and [#4](#send-application-metrics-). +This guide also enables **Tracing**, **Session Replay**, and **User Feedback**. + + + +The wizard creates the files below. On Cloudflare Workers, you set the server options in the Worker entry instead, as the [Wrap the Worker Entry](#wrap-the-worker-entry) step shows. + + + +### Configure Wrangler + +The SDK uses Node.js APIs that the Workers runtime only provides with the `nodejs_compat` [compatibility flag](https://developers.cloudflare.com/workers/runtime-apis/nodejs/). Set the [compatibility date](https://developers.cloudflare.com/workers/configuration/compatibility-dates/) to `2025-08-16` or later, which adds the `https.request` API that the SDK uses to send data: + +```jsonc {tabTitle:JSON} {filename:wrangler.jsonc} +{ + "compatibility_flags": ["nodejs_compat"], + "compatibility_date": "2025-08-16", +} +``` + +```toml {tabTitle:Toml} {filename:wrangler.toml} +compatibility_flags = ["nodejs_compat"] +compatibility_date = "2025-08-16" +``` + +### Wrap the Worker Entry + + + +If you build your app with vinext, skip to [Wrap the Worker Entry With vinext](#wrap-the-worker-entry-with-vinext). + +On Cloudflare Workers, your Next.js app runs inside the Worker entry that OpenNext generates (`.open-next/worker.js`). Wrap this entry with `withSentry` from `@sentry/nextjs/cloudflare` to get the same Next.js spans as on Node.js, plus Cloudflare data such as spans for D1 queries. Each request gets one `http.server` span with the name of the Next.js route, and the Next.js spans become its children. + +`@sentry/nextjs` depends on `@sentry/cloudflare`, so you don't need to install another package. + +First, create a [custom Worker](https://opennext.js.org/cloudflare/howtos/custom-worker) that imports the handler of OpenNext and wraps it with `withSentry`. Pass your Sentry options to `withSentry`: + +```typescript {filename:worker.ts} +import * as Sentry from "@sentry/nextjs/cloudflare"; +// @ts-ignore `.open-next/worker.js` is generated at build time +import handler from "./.open-next/worker.js"; + +// Re-export the Durable Objects your app uses, for example for the DO Queue and DO Tag Cache of OpenNext +// @ts-ignore `.open-next/worker.js` is generated at build time +export { DOQueueHandler, DOShardedTagCache } from "./.open-next/worker.js"; + +export default Sentry.withSentry( + () => ({ + dsn: "___PUBLIC_DSN___", + + // Set tracesSampleRate to 1.0 to capture 100% of spans for tracing. + // Learn more at + // https://docs.sentry.io/platforms/javascript/guides/cloudflare/configuration/options/#tracesSampleRate + tracesSampleRate: 1.0, + }), + handler +); +``` + +Then, point `main` in your Wrangler configuration to this file: + +```jsonc {tabTitle:JSON} {filename:wrangler.jsonc} +{ + "main": "./worker.ts", +} +``` + +```toml {tabTitle:Toml} {filename:wrangler.toml} +main = "./worker.ts" +``` + +#### Wrap the Worker Entry With vinext + +With [vinext](https://github.com/cloudflare/vinext), you don't need a custom Worker. Add the [Sentry Vite plugin](/platforms/javascript/guides/cloudflare/install/vite-plugin/) to your Vite config, and it wraps your Worker entry with `withSentry` from `@sentry/nextjs/cloudflare` automatically. + +#### Server and Edge Configuration in the Worker + +In the Worker, `withSentry` creates the Sentry client. `Sentry.init()` in `sentry.server.config.ts` and `sentry.edge.config.ts` still runs, but it creates no client and only applies the `release` option. Set all other options in `withSentry`. + +On Workers, these two files are optional. Keep them if you use `next dev`, which runs on Node.js and doesn't use the Worker entry. They also pass on the release that `withSentryConfig` sets at build time. + +Keep `instrumentation.ts`, because Next.js reports server errors, for example from Server Components and route handlers, through its `onRequestError` hook. + +The SDK takes the release from the first of these sources that has a value: + +1. The `release` option of `withSentry` +2. The `SENTRY_RELEASE` environment variable +3. The ID of the `CF_VERSION_METADATA` binding +4. The `release` option of `Sentry.init()` in `sentry.server.config.ts` or `sentry.edge.config.ts`, or else the release that `withSentryConfig` sets at build time + +On Node.js, the build release comes before `SENTRY_RELEASE`. + +### Control the Data You Send to Sentry + + + +## Send Logs + + + +If you're already logging with `console` or Consola, use an integration to capture those logs as Sentry Logs automatically: + +- `consoleLoggingIntegration` for `console` calls +- Consola + +## Send Application Metrics + + + +## Verify Your Setup + +Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. + +The wizard created an example page that sends a test error from both your frontend and your backend: + +1. Build your app and run it in the Workers runtime on your machine: + + ```bash + npx opennextjs-cloudflare build && npx opennextjs-cloudflare preview + ``` + +2. Open `/sentry-example-page` on the URL that the preview command prints. +3. Click **Throw Sample Error**. + +If you skipped the example page, add a test button to one of your pages instead. Clicking it will trigger an error for Sentry to capture. + +```tsx {filename:app/page.tsx} +"use client"; + +export default function Page() { + return ( + + ); +} +``` + + + +### View Captured Data in Sentry + +Now, head over to your project on [Sentry.io](https://sentry.io/) to view the collected data (it takes a couple of moments for the data to appear). + + + +## Next Steps + +At this point, you should have integrated Sentry into your Next.js application on Cloudflare Workers. Here's what to explore next: + +- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup +- [Distributed Tracing](/platforms/javascript/guides/nextjs/tracing/distributed-tracing/) to trace requests across services +- Set up tunneling to avoid ad blockers blocking Sentry events, if you didn't enable it in the wizard + + + +- If you encountered issues with our installation wizard, try [setting up Sentry manually](/platforms/javascript/guides/nextjs/manual-setup/) +- Find various topics in Troubleshooting +- [Get support](https://www.sentry.help/en/) + + + + diff --git a/platform-includes/getting-started-cloudflare/javascript.nuxt.mdx b/platform-includes/getting-started-cloudflare/javascript.nuxt.mdx new file mode 100644 index 0000000000000..b1d5b083fcdcb --- /dev/null +++ b/platform-includes/getting-started-cloudflare/javascript.nuxt.mdx @@ -0,0 +1,314 @@ + + + + +## Install + +Choose the features you want to configure, and this guide will show you how: + + + + + +### Install the Sentry SDK + +Run the command for your preferred package manager to add the Sentry SDK to your application: + +```bash {tabTitle:npm} +npm install @sentry/nuxt --save +``` + +```bash {tabTitle:yarn} +yarn add @sentry/nuxt +``` + +```bash {tabTitle:pnpm} +pnpm add @sentry/nuxt +``` + +## Configure + +### Apply Instrumentation to Your App + +Add the Sentry Nuxt module to your `nuxt.config.ts` file: + +```javascript {filename:nuxt.config.ts} +export default defineNuxtConfig({ + modules: ["@sentry/nuxt/module"], +}); +``` + +### Configure Client-Side Sentry + +Add a `sentry.client.config.ts` file to the root of your project (this is probably the same level as the `package.json`). In this file, import and initialize Sentry, specifying any SDK options for the client: + +```javascript {filename:sentry.client.config.ts} +import * as Sentry from "@sentry/nuxt"; + +Sentry.init({ + // If set up, you can use the Nuxt runtime config here + // dsn: useRuntimeConfig().public.sentry.dsn + // modify depending on your custom runtime config + dsn: "___PUBLIC_DSN___", + + // ___PRODUCT_OPTION_START___ session-replay + + // Replay may only be enabled for the client-side + integrations: [ + Sentry.replayIntegration(), + // ___PRODUCT_OPTION_START___ user-feedback + Sentry.feedbackIntegration({ + // Additional SDK configuration goes in here, for example: + colorScheme: "system", + }), + // ___PRODUCT_OPTION_END___ user-feedback + ], + // ___PRODUCT_OPTION_END___ session-replay + // ___PRODUCT_OPTION_START___ performance + + // Set tracesSampleRate to 1.0 to capture 100% + // of transactions for tracing. + // We recommend adjusting this value in production + // Learn more at + // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate + tracesSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ performance + // ___PRODUCT_OPTION_START___ session-replay + + // Capture Replay for 10% of all sessions, + // plus for 100% of sessions with an error + // Learn more at + // https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ session-replay +}); +``` + +We recommend you store your Sentry [Data Source Name](/concepts/key-terms/dsn-explainer/) (DSN) in an environment variable and configure it via the Nuxt runtime config. + +This allows you to access the DSN using `useRuntimeConfig().public.sentry.dsn`. + +```javascript {filename:nuxt.config.ts} +export default defineNuxtConfig({ + modules: ["@sentry/nuxt/module"], + runtimeConfig: { + public: { + sentry: { + dsn: process.env.NUXT_PUBLIC_SENTRY_DSN, // Use a public environment variable for the DSN + }, + }, + }, +}); +``` + +### Configure Cloudflare for Sentry + + + +#### Add the Nitro Plugin + + + If you have an existing `sentry.server.config.ts` file, delete it, as it will + conflict with the Cloudflare setup. + + +To enable Sentry for your Nuxt app on Cloudflare, create a new file in `server/plugins` and add the following code to it: + +```TypeScript {filename:server/plugins/sentry-cloudflare-plugin.ts} +import { sentryCloudflareNitroPlugin } from '@sentry/nuxt/module/plugins' + +export default defineNitroPlugin(sentryCloudflareNitroPlugin({ + dsn: '___PUBLIC_DSN___', + tracesSampleRate: 1.0, +})) +``` + +Or, if you need access to `nitroApp`: + +```TypeScript {filename:server/plugins/sentry-cloudflare-plugin.ts} +import { sentryCloudflareNitroPlugin } from '@sentry/nuxt/module/plugins' + +export default defineNitroPlugin(sentryCloudflareNitroPlugin((nitroApp: NitroApp) => { + // You can access `nitroApp` here if needed + return { + dsn: '___PUBLIC_DSN___', + tracesSampleRate: 1.0, + } +})) +``` + +### Add Readable Stack Traces With Source Maps (Optional) + +To upload source maps for clear error stack traces, add your Sentry auth token, organization, and project slugs in the `sentry` options inside your configuration file: + +These `sentry` options only affect the **build time** of the SDK. + +```javascript {filename:nuxt.config.ts} {3-10} +export default defineNuxtConfig({ + modules: ["@sentry/nuxt/module"], + sentry: { + org: "___ORG_SLUG___", + project: "___PROJECT_SLUG___", + // store your auth token in an environment variable + authToken: process.env.SENTRY_AUTH_TOKEN, + }, +}); +``` + +To keep your auth token secure, always store it in an environment variable instead of directly in your files: + + + +```bash {filename:.env} +SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ +``` + +#### Enable Client-Side Source Maps + +While Nuxt generates source maps on the server side by default, you need to explicitly enable client-side source maps in your Nuxt configuration. + +The `hidden` option enables source map generation while preventing source map reference comments that would normally appear at the end of each generated file in the build output. + +```javascript {filename:nuxt.config.ts} {2} +export default defineNuxtConfig({ + sourcemap: { client: "hidden" }, +}); +``` + +### Control the Data You Send to Sentry (Optional) + + + +## Verify Your Setup + +Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. + +### Issues + +To verify that Sentry captures errors and creates issues in your Sentry project, create a test page with a button. + + + +```html {tabTitle:Vue} {filename:pages/example-error.vue} + + + +``` + + +### Tracing + +To test tracing, create a test API route `server/api/sentry-example.get.ts`: + +```js {tabTitle:Nitro} {filename:server/api/sentry-example.get.ts} +export default defineEventHandler((event) => { + throw new Error("Sentry Example API Route Error"); +}); +``` + +Then update the test page by including a new button that executes a function to fetch your API route: + +```html {tabTitle:Vue} {filename:pages/example-error.vue} + + + +``` + + + + + + + + + + + + + Once you have your test code in place, open the page in a browser and click + the button to trigger an error. + + + + +Once you have your test code in place, build and run your project. + +After running your project, open your test page in a browser and click the buttons. + + + +### View Captured Data in Sentry + +Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). + + + +## Next Steps + +At this point, you should have integrated Sentry into your Nuxt application and should already be sending data to your Sentry project. + +Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are: + +- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup +- Learn how to [manually capture errors](/platforms/javascript/guides/nuxt/usage/) +- Continue to [customize your configuration](/platforms/javascript/guides/nuxt/configuration/) +- Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts +- Learn how to [track your Vue components or your Pinia store](/platforms/javascript/guides/nuxt/features/) + + + +- Find various support topics in [Cloudflare troubleshooting](/platforms/javascript/guides/cloudflare/troubleshooting/) and [Nuxt troubleshooting](/platforms/javascript/guides/nuxt/troubleshooting/) +- [Get support](https://www.sentry.help/en/) + + + + diff --git a/platform-includes/getting-started-cloudflare/javascript.remix.mdx b/platform-includes/getting-started-cloudflare/javascript.remix.mdx new file mode 100644 index 0000000000000..ee817b2c68666 --- /dev/null +++ b/platform-includes/getting-started-cloudflare/javascript.remix.mdx @@ -0,0 +1,388 @@ +## Configure + +### Configure Client-Side Sentry + +Create a client file `entry.client.tsx` in the `app` folder of your project if you don't have one already. In this file, import and initialize the Sentry SDK: + +```typescript {tabTitle:Client} {filename: entry.client.tsx} +import { useLocation, useMatches } from "@remix-run/react"; +import * as Sentry from "@sentry/remix"; +import { useEffect } from "react"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + + integrations: [ + // ___PRODUCT_OPTION_START___ performance + Sentry.browserTracingIntegration({ + useEffect, + useLocation, + useMatches, + }), + // ___PRODUCT_OPTION_END___ performance + // ___PRODUCT_OPTION_START___ session-replay + // Replay is only available in the client + Sentry.replayIntegration(), + // ___PRODUCT_OPTION_END___ session-replay + // ___PRODUCT_OPTION_START___ user-feedback + Sentry.feedbackIntegration({ + // Additional SDK configuration goes in here, for example: + colorScheme: "system", + }), + // ___PRODUCT_OPTION_END___ user-feedback + ], + // ___PRODUCT_OPTION_START___ performance + + // Set tracesSampleRate to 1.0 to capture 100% + // of transactions for tracing. + // We recommend adjusting this value in production + // Learn more at + // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate + tracesSampleRate: 1.0, + + // Set `tracePropagationTargets` to control for which URLs distributed tracing should be enabled + tracePropagationTargets: ["localhost", /^https:\/\/yourserver\.io\/api/], + // ___PRODUCT_OPTION_END___ performance + // ___PRODUCT_OPTION_START___ session-replay + + // Capture Replay for 10% of all sessions, + // plus for 100% of sessions with an error + // Learn more at + // https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ session-replay +}); +``` + +#### Remix ErrorBoundary + +To capture errors from your [ErrorBoundary](https://remix.run/docs/en/main/route/error-boundary), define it in `root.tsx` to act as a fallback for all routes or create route-specific error boundaries in your route components. + +In your `ErrorBoundary` component, use `Sentry.captureRemixErrorBoundaryError` to send the captured error to Sentry: + +```tsx {filename: root.tsx} +import { captureRemixErrorBoundaryError } from "@sentry/remix"; + +export const ErrorBoundary = () => { + const error = useRouteError(); + + captureRemixErrorBoundaryError(error); + + return
...
; +}; +``` + +#### Performance Monitoring + +Wrap your Remix root component with `withSentry` to capture performance data: + +```tsx {filename: root.tsx} +import { + Links, + LiveReload, + Meta, + Outlet, + Scripts, + ScrollRestoration, +} from "@remix-run/react"; + +import { withSentry } from "@sentry/remix"; + +function App() { + return ( + + + + + + + + + + + + + ); +} + +export default withSentry(App); +``` + +### Configure Server-Side Sentry + +Create a Worker entry file, for example `server.ts` in your project's root folder, and set it as `main` in your wrangler config. + +In this file, instrument your Remix server build with `instrumentBuild` from `@sentry/remix/cloudflare`, pass it to `createRequestHandler`, and wrap the exported handler with `Sentry.withSentry()` from `@sentry/cloudflare`. `withSentry` isolates each request, so scope data like tags and users stays on the request that set it. + + + +Don't also wrap `createRequestHandler` with `makeWrappedCreateRequestHandler`. Combined with `withSentry`, it reports every request twice, as two `http.server` transactions in two different traces. + + + +```typescript {filename:server.ts} +import { createRequestHandler } from "@remix-run/cloudflare"; +import * as Sentry from "@sentry/cloudflare"; +import { instrumentBuild } from "@sentry/remix/cloudflare"; +// The server build produced by `remix vite:build` +import * as remixBuild from "./build/server/index.js"; + +const handleRequest = createRequestHandler(instrumentBuild(remixBuild)); + +export default Sentry.withSentry( + (env) => ({ + dsn: "___PUBLIC_DSN___", + // ___PRODUCT_OPTION_START___ performance + + // Set tracesSampleRate to 1.0 to capture 100% + // of transactions for tracing. + // We recommend adjusting this value in production + // Learn more at + // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate + tracesSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ performance + }), + { + async fetch(request, env, ctx) { + return handleRequest(request, { env, ctx }); + }, + } +); +``` + + + + + +```javascript {filename:functions/_middleware.js} +import * as Sentry from "@sentry/cloudflare"; + +export const onRequest = [ + // Make sure Sentry is the first middleware + Sentry.sentryPagesPlugin((context) => ({ + dsn: "___PUBLIC_DSN___", + + // ___PRODUCT_OPTION_START___ performance + + // Set tracesSampleRate to 1.0 to capture 100% + // of transactions for tracing. + // We recommend adjusting this value in production + // Learn more at + // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate + tracesSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ performance + + // Optionally limit which action formData fields are captured. + // Without this option, all fields are captured. + captureActionFormDataKeys: { + key_x: true, + key_y: true, + }, + })), + // Add more middlewares here +]; +``` + + + +### Capture Server-Side Errors + +To automatically capture server-side errors, export `sentryHandleError` as the [`handleError`](https://remix.run/docs/en/main/file-conventions/entry.server#handleerror) function from your server entry point (`entry.server.tsx`). Without this export, Remix handles errors thrown in loaders and actions itself, and Sentry doesn't receive them. + + + +Import from `@sentry/remix/cloudflare`, not from `@sentry/remix`. In a Cloudflare server build, `sentryHandleError` from `@sentry/remix` is `undefined`, and no errors are captured. + + + +```typescript {filename: entry.server.tsx} +import { sentryHandleError } from "@sentry/remix/cloudflare"; + +export const handleError = sentryHandleError; +``` + +### Configure Cloudflare for Sentry + + + +### Configure Vite + +Add two Sentry plugins to your `vite.config.ts`, next to the Remix plugin: + +- `sentryRemixVitePlugin` from `@sentry/remix/vite` parameterizes transaction names with your route patterns, for example `/users/:id`. +- `sentryCloudflareVitePlugin` from `@sentry/cloudflare/vite` instruments supported bundled dependencies at build time, so you get spans for database clients like `mysql`. Without it, database calls produce no spans and no warning. + +Set `ssr.target` to `webworker` and bundle the Sentry packages and any database client you want traced with `ssr.noExternal`. Setting `noExternal: true` bundles every dependency, which works too. + +```typescript {filename:vite.config.ts} {2-3, 11-12, 14-17} +import { vitePlugin as remix } from "@remix-run/dev"; +import { sentryCloudflareVitePlugin } from "@sentry/cloudflare/vite"; +import { sentryRemixVitePlugin } from "@sentry/remix/vite"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [ + remix({ + // ... your Remix plugin options + }), + sentryRemixVitePlugin(), + sentryCloudflareVitePlugin(), + ], + ssr: { + target: "webworker", + noExternal: ["mysql", /^@sentry\//, "@opentelemetry/api"], + }, +}); +``` + +Build your app with `remix vite:build`. Under Vite 6, a plain `vite build` only builds the client and skips `build/server`, without an error. + +```bash +npx remix vite:build +``` + +### Add Readable Stack Traces With Source Maps (Optional) + +To upload source maps for clear error stack traces, pass your Sentry organization, project, and auth token to `sentryRemixVitePlugin` from the previous step. It injects debug IDs, uploads the source maps during your production build, and deletes them from your build output afterwards. + +The plugin also turns on hidden source maps for you, unless you set `build.sourcemap` yourself. + + + +Check our [Source Maps documentation](/platforms/javascript/guides/remix/sourcemaps/) for +alternative setup options. + + + +```javascript {filename:vite.config.ts} {10-16} +import { vitePlugin as remix } from "@remix-run/dev"; +import { sentryRemixVitePlugin } from "@sentry/remix/vite"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [ + remix({ + // ... your Remix plugin options + }), + sentryRemixVitePlugin({ + // If you use environment variables, + // you don't need to specify these options + org: "___ORG_SLUG___", + project: "___PROJECT_SLUG___", + // store your auth token in an environment variable + authToken: process.env.SENTRY_AUTH_TOKEN, + }), + // ... other plugins + ], +}); +``` + +To keep your auth token secure, always store it in an environment variable instead of directly in your files: + + + +```bash {filename:.env} +SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ +``` + + + +### Control the Data You Send to Sentry (Optional) + + + +## Verify Your Setup + +Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. + +### Issues + + + +To verify that Sentry captures errors and creates issues in your Sentry project, add a test button to one of your pages. + + + +Open the page in a browser and click the button to trigger a frontend error. + + + +```javascript + +``` + + + +### Tracing + +To test your tracing configuration, update the previous code snippet by calling a non-existing route and starting a trace to measure the time it takes for the execution of your code. + +Open the page in a browser and click the button to trigger the frontend error and a trace. + +```javascript + +``` + + + + + + + + + + + +### View Captured Data in Sentry + +Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). + + + +## Next Steps + +At this point, you should have integrated Sentry into your Remix application and should already be sending error and performance data to your Sentry project. + +Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are: + +- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup +- Learn how to manually capture errors +- Continue to customize your configuration +- Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts + + + +- If you encountered issues with the manual setup, try our installation wizard +- Find various support topics in [Cloudflare troubleshooting](/platforms/javascript/guides/cloudflare/troubleshooting/) and [Remix troubleshooting](/platforms/javascript/guides/remix/troubleshooting/) +- [Get support](https://www.sentry.help/en/) + + diff --git a/platform-includes/getting-started-cloudflare/javascript.sveltekit.mdx b/platform-includes/getting-started-cloudflare/javascript.sveltekit.mdx new file mode 100644 index 0000000000000..e5f5b3efe3bdd --- /dev/null +++ b/platform-includes/getting-started-cloudflare/javascript.sveltekit.mdx @@ -0,0 +1,358 @@ +## Prerequisites + +You need: + +- A Sentry [account](https://sentry.io/signup/) and [project](/product/projects/) +- Your application up and running +- SvelteKit version `2.0.0+` (we recommend `2.31.0` or higher for best support) +- Vite version `4.2` or newer + + + +Version `2.31.0` of SvelteKit introduces [official support for observability and tracing](https://svelte.dev/docs/kit/observability). +This means that Sentry can now follow the official best practice for how the SDK should be set up: + +- The Sentry SDK will be initialized at the correct, earliest possible time on the server, allowing for all its auto-instrumentation to work correctly. + This means, you will now get spans from auto instrumentation (e.g. database queries) automatically. +- The Sentry SDK picks up spans emitted from SvelteKit directly. + You'll get more accurate insights into the performance of your handlers, server actions, `load`, and remote functions. + +SvelteKit observability is still an experimental feature in SvelteKit 2.x, but we recommend giving it a try. +The Sentry wizard, as well as this guide, will use it as the default way of setting up the SDK. + + + + + +## Install + +Choose the features you want to configure, and this guide will show you how: + + + + + +### Install the Sentry SDK + +Run the command for your preferred package manager to add the Sentry SDK to your application: + +If you're updating your Sentry SDK to the latest version, check out our migration guide to learn more about breaking changes. + +```bash {tabTitle:npm} +npm install @sentry/sveltekit --save +``` + +```bash {tabTitle:yarn} +yarn add @sentry/sveltekit +``` + +```bash {tabTitle:pnpm} +pnpm add @sentry/sveltekit +``` + +## Configure + +You need to initialize and configure the Sentry SDK in three places: the client side, the server side, and your Vite config. + +### Configure Client-Side Sentry + +Create a client hooks file `src/hooks.client.(js|ts)` in your project if you don't have one already. In this file, import and initialize the Sentry SDK and add the `handleErrorWithSentry` function to the [`handleError` hook](https://svelte.dev/docs/kit/hooks#Shared-hooks-handleError). + +```javascript {filename:src/hooks.client.(js|ts)} {1, 3-37, 43} +import * as Sentry from "@sentry/sveltekit"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + + // ___PRODUCT_OPTION_START___ performance + + // Set tracesSampleRate to 1.0 to capture 100% + // of transactions for tracing. + // We recommend adjusting this value in production + // Learn more at + // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate + tracesSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ performance + integrations: [ + // ___PRODUCT_OPTION_START___ session-replay + Sentry.replayIntegration(), + // ___PRODUCT_OPTION_END___ session-replay + // ___PRODUCT_OPTION_START___ user-feedback + Sentry.feedbackIntegration({ + // Additional SDK configuration goes in here, for example: + colorScheme: "system", + }), + // ___PRODUCT_OPTION_END___ user-feedback + ], + + // ___PRODUCT_OPTION_START___ session-replay + // Capture Replay for 10% of all sessions, + // plus for 100% of sessions with an error + // Learn more at + // https://docs.sentry.io/platforms/javascript/session-replay/configuration/#general-integration-configuration + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ session-replay +}); + +const myErrorHandler = ({ error, event }) => { + console.error("An error occurred on the client side:", error, event); +}; + +export const handleError = Sentry.handleErrorWithSentry(myErrorHandler); + +// or alternatively, if you don't have a custom error handler: +// export const handleError = handleErrorWithSentry(); +``` + +### Configure Server-Side Sentry + +_Requires SvelteKit `2.31.0` or higher and `@sentry/sveltekit` `10.8.0` or higher._ + +Configure server-side instrumentation and tracing. Where this config lives depends on your SvelteKit version — SvelteKit 2 uses `svelte.config.js`, while SvelteKit 3 moved it into the `sveltekit()` Vite plugin options in `vite.config.(js|ts)` instead (see [Configure Vite](#configure-vite) below). SvelteKit 3 no longer needs an instrumentation flag, so the only option to set there is `tracing`. + +```js {tabTitle:SvelteKit 2} {mdExpandTabs} {filename:svelte.config.js} {3-12} +const config = { + kit: { + experimental: { + instrumentation: { + server: true, + }, + // ___PRODUCT_OPTION_START___ performance + tracing: { + server: true, + }, + // ___PRODUCT_OPTION_END___ performance + }, + }, +}; + +export default config; +``` + +```js {tabTitle:SvelteKit 3} {filename:vite.config.(js|ts)} +import { sveltekit } from "@sveltejs/kit/vite"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [ + sveltekit({ + // ___PRODUCT_OPTION_START___ performance + tracing: { + server: true, + }, + // ___PRODUCT_OPTION_END___ performance + // ... rest of your SvelteKit config + }), + ], + // ... rest of your Vite config +}); +``` + +Create a server hooks file `src/hooks.server.(js|ts)` in your project if you don't have one already. In this file, import and initialize the Sentry SDK and add the `handleErrorWithSentry` function to the [`handleError` hook](https://svelte.dev/docs/kit/hooks#Shared-hooks-handleError) and Sentry's Cloudflare request handler to the [`handle` hook](https://kit.svelte.dev/docs/hooks#server-hooks-handle). + +```javascript {filename:src/hooks.server.(js|ts)} +import { + handleErrorWithSentry, + sentryHandle, + initCloudflareSentryHandle, +} from "@sentry/sveltekit"; +import { sequence } from "@sveltejs/kit/hooks"; +import * as Sentry from "@sentry/sveltekit"; + +export const handle = sequence( + initCloudflareSentryHandle({ + dsn: "___PUBLIC_DSN___", + + // ___PRODUCT_OPTION_START___ performance + + // Set tracesSampleRate to 1.0 to capture 100% + // of transactions for tracing. + // We recommend adjusting this value in production + // Learn more at + // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate + tracesSampleRate: 1.0, + // ___PRODUCT_OPTION_END___ performance + }), + sentryHandle() +); + +const myErrorHandler = ({ error, event }) => { + console.error("An error occurred on the server side:", error, event); +}; + +export const handleError = Sentry.handleErrorWithSentry(myErrorHandler); +// or alternatively, if you don't have a custom error handler: +// export const handleError = handleErrorWithSentry(); +``` + +### Configure Vite + +Add the `sentrySvelteKit` plugin **before** `sveltekit` in your `vite.config.(js|ts)` file to automatically upload source maps to Sentry and instrument `load` functions for tracing if it's configured. + +```javascript {filename:vite.config.(js|ts)} {2,6} +import { sveltekit } from "@sveltejs/kit/vite"; +import { sentrySvelteKit } from "@sentry/sveltekit/vite"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [sentrySvelteKit(), sveltekit()], + // ... rest of your Vite config +}); +``` + +### Configure Cloudflare for Sentry + + + +### Add Readable Stack Traces With Source Maps (Optional) + +To upload source maps for clear error stack traces, add your Sentry auth token, organization, and project slug in your `vite.config.(js|ts)` file: + +```javascript {filename:vite.config.(js|ts)} {6-13} +import { sveltekit } from "@sveltejs/kit/vite"; +import { sentrySvelteKit } from "@sentry/sveltekit/vite"; + +export default { + plugins: [ + sentrySvelteKit({ + org: "___ORG_SLUG___", + project: "___PROJECT_SLUG___", + // store your auth token in an environment variable + authToken: process.env.SENTRY_AUTH_TOKEN, + }), + sveltekit(), + ], + // ... rest of your Vite config +}; +``` + +To keep your auth token secure, always store it in an environment variable instead of directly in your files: + + + +```bash {filename:.env} +SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ +``` + + + +### Control the Data You Send to Sentry (Optional) + + + +## Verify Your Setup + +Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. + +### Issues + +To verify that Sentry captures errors and creates issues in your Sentry project, create a test page, for example, at `src/routes/sentry-example/+page.svelte` with a button that throws an error when clicked. + + + Open the page `sentry-example` in a browser and click the button to trigger a + frontend error. + + + + +```html {filename:+page.svelte} + + + +``` + + +### Tracing + +To test tracing, create a test API route like `src/routes/sentry-example/+server.(js|ts)`. + +```javascript {filename:+server.(js|ts)} +export const GET = async () => { + throw new Error("Sentry Example API Route Error"); +}; +``` + +Next, update your test button to call this route and throw an error if the response isn't `ok`. + +Open the page `sentry-example` in a browser and click the button to trigger two errors: + +- a frontend error +- an error within the API route + +Additionally, this starts a trace to measure the time it takes for the API request to complete. + +```html {filename:+page.svelte} + + + +``` + + + + + + + + + + + +### View Captured Data in Sentry + +Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). + + + +## Next Steps + +At this point, you should have integrated Sentry into your SvelteKit application and should already be sending data to your Sentry project. + +Now's a good time to customize your setup and look into more advanced topics. +Our next recommended steps for you are: + +- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup +- Learn how to [manually capture errors](/platforms/javascript/guides/cloudflare/usage/) +- Continue to [customize your configuration](/platforms/javascript/guides/cloudflare/configuration/) +- Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts +- Learn how to [manually instrument](/platforms/javascript/guides/sveltekit/apis/#load-function-instrumentation) SvelteKit-specific features + + + +- Find various support topics in [Cloudflare troubleshooting](/platforms/javascript/guides/cloudflare/troubleshooting/) and [SvelteKit troubleshooting](/platforms/javascript/guides/sveltekit/troubleshooting/) +- [Get support](https://www.sentry.help/en/) + + + + diff --git a/platform-includes/getting-started-complete/javascript.astro.mdx b/platform-includes/getting-started-complete/javascript.astro.mdx index 064dff9974b45..fb3cac04de9db 100644 --- a/platform-includes/getting-started-complete/javascript.astro.mdx +++ b/platform-includes/getting-started-complete/javascript.astro.mdx @@ -1,5 +1,3 @@ - - ### Install the Sentry SDK Install and add the Sentry integration using the `astro` CLI: @@ -34,88 +32,8 @@ pnpm add @sentry/profiling-node - - - - -### Install the Sentry SDKs - -Install both `@sentry/astro` and `@sentry/cloudflare`: - -```bash {tabTitle:npm} -npm install @sentry/astro @sentry/cloudflare -``` - -```bash {tabTitle:yarn} -yarn add @sentry/astro @sentry/cloudflare -``` - -```bash {tabTitle:pnpm} -pnpm add @sentry/astro @sentry/cloudflare -``` - - - ## Configure - - -### Wrangler Configuration - - - -### Configure Custom Entry Point - -Astro 6 with `@astrojs/cloudflare` v13+ supports custom entry points directly from `wrangler.jsonc`. Update your wrangler configuration to point to a custom Sentry entry point: - -```jsonc {filename:wrangler.jsonc} -{ - "main": "./sentry.server.config.ts", - // ... other configuration -} -``` - -Create a `sentry.server.config.ts` file in the root of your project that wraps the Astro Cloudflare handler with Sentry: - -```typescript {filename:sentry.server.config.ts} -import * as Sentry from "@sentry/cloudflare"; -import handler from "@astrojs/cloudflare/entrypoints/server"; - -export default Sentry.withSentry( - (env) => ({ - dsn: env.SENTRY_DSN, - // ___PRODUCT_OPTION_START___ performance - // Define how likely traces are sampled. Adjust this value in production, - // or use tracesSampler for greater control. - tracesSampleRate: 1.0, - // ___PRODUCT_OPTION_END___ performance - }), - handler -); -``` - -### Register the Sentry Integration - -Follow [Astro's Cloudflare deployment guide](https://docs.astro.build/en/guides/deploy/cloudflare/) if you haven't already. Then add the Sentry integration to your `astro.config.mjs` alongside the Cloudflare adapter. - -```javascript {filename:astro.config.mjs} -import { defineConfig } from "astro/config"; -import cloudflare from "@astrojs/cloudflare"; -import sentry from "@sentry/astro"; - -export default defineConfig({ - adapter: cloudflare(), - integrations: [sentry()], -}); -``` - - - - - ### Apply Instrumentation to Your App Register the Sentry integration in your `astro.config.mjs` file: @@ -129,8 +47,6 @@ export default defineConfig({ }); ``` - - ### Configure Client-side Sentry Create a `sentry.client.config.(ts|js)` file in the root of your project. In this file, import and initialize Sentry for the client: @@ -174,8 +90,6 @@ Sentry.init({ }); ``` - - Sentry automatically detects configuration files named `sentry.(client|server).config.(ts|js)` in the root of your project. You can rename these files or move them to a custom folder within your project. @@ -195,12 +109,8 @@ export default defineConfig({ - - ### Configure Server-side Sentry - - Create a `sentry.server.config.(ts|js)` file in the root of your project. In this file, import and initialize Sentry for the server: ```javascript {filename:sentry.server.config.(ts|js)} @@ -233,27 +143,15 @@ Sentry.init({ }); ``` - - - - -Server-side Sentry is already configured in your custom entry point file (`sentry.server.config.ts`) created in the previous step. - - - ### Add Readable Stack Traces With Source Maps To upload source maps for clear error stack traces, add your Sentry auth token, organization, and project slugs in the `sentry` options inside `astro.config.mjs`: - - ```javascript {filename:astro.config.mjs} import { defineConfig } from "astro/config"; -import cloudflare from "@astrojs/cloudflare"; import sentry from "@sentry/astro"; export default defineConfig({ - adapter: cloudflare(), integrations: [ sentry({ org: "___ORG_SLUG___", @@ -265,28 +163,6 @@ export default defineConfig({ }); ``` - - - - -```javascript {filename:astro.config.mjs} -import { defineConfig } from "astro/config"; -import sentry from "@sentry/astro"; - -export default defineConfig({ - integrations: [ - sentry({ - org: "___ORG_SLUG___", - project: "___PROJECT_SLUG___", - // store your auth token in an environment variable - authToken: process.env.SENTRY_AUTH_TOKEN, - }), - ], -}); -``` - - - To keep your auth token secure, set the `SENTRY_AUTH_TOKEN` environment variable in your build environment: @@ -297,14 +173,10 @@ SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ - - ### Avoid Ad Blockers With Tunneling (Optional) - - ### Control the Data You Send to Sentry (Optional) @@ -394,18 +266,8 @@ To test tracing, create a custom span to measure the time it takes for the API r Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). - - - - - - - - - - ## Next Steps At this point, you should have integrated Sentry into your Astro application and should already be sending data to your Sentry project. @@ -413,25 +275,12 @@ At this point, you should have integrated Sentry into your Astro application and Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are: - - -- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Continue to customize your configuration -- Learn how to manually capture errors -- Learn more about [deploying Astro apps to Cloudflare](/platforms/javascript/guides/cloudflare/frameworks/astro/) -- Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts - - - - - - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup - Continue to customize your configuration - Learn how to manually capture errors +- Learn more about [deploying Astro apps to Cloudflare](/platforms/javascript/guides/astro/cloudflare/) - Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts - - - Find various topics in Troubleshooting diff --git a/platform-includes/getting-started-complete/javascript.mdx b/platform-includes/getting-started-complete/javascript.mdx index 2730660e61b65..1b1b1c3960a73 100644 --- a/platform-includes/getting-started-complete/javascript.mdx +++ b/platform-includes/getting-started-complete/javascript.mdx @@ -205,7 +205,7 @@ At this point, you should have integrated Sentry into your JavaScript applicatio - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup - Extend Sentry to your backend using one of our [SDKs](/) -- Set up tunneling to avoid ad blockers from blocking Sentry events +- Set up tunneling to avoid ad blockers from blocking Sentry events diff --git a/platform-includes/getting-started-complete/javascript.nuxt.mdx b/platform-includes/getting-started-complete/javascript.nuxt.mdx index 8847328ac123f..d026ff24a141b 100644 --- a/platform-includes/getting-started-complete/javascript.nuxt.mdx +++ b/platform-includes/getting-started-complete/javascript.nuxt.mdx @@ -18,18 +18,8 @@ Choose the features you want to configure, and this guide will show you how: ]} /> - - - - - - - - - - ### Install the Sentry SDK Run the command for your preferred package manager to add the Sentry SDK to your application: @@ -122,7 +112,6 @@ export default defineNuxtConfig({ }); ``` - ### Configure Server-Side Sentry Add a `sentry.server.config.ts` file to the root of your project and initialize Sentry in it. @@ -177,51 +166,6 @@ To learn more, see [Server-Side Installation](/platforms/javascript/guides/nuxt/ node .output/server/index.mjs ``` - - - - -### Configure Cloudflare for Sentry - - - -#### Add the Nitro Plugin - - - If you have an existing `sentry.server.config.ts` file, delete it, as it will - conflict with the Cloudflare setup. - - -To enable Sentry for your Nuxt app on Cloudflare, create a new file in `server/plugins` and add the following code to it: - -```TypeScript {filename:server/plugins/sentry-cloudflare-plugin.ts} -import { sentryCloudflareNitroPlugin } from '@sentry/nuxt/module/plugins' - -export default defineNitroPlugin(sentryCloudflareNitroPlugin({ - dsn: '___PUBLIC_DSN___', - tracesSampleRate: 1.0, -})) -``` - -Or, if you need access to `nitroApp`: - -```TypeScript {filename:server/plugins/sentry-cloudflare-plugin.ts} -import { sentryCloudflareNitroPlugin } from '@sentry/nuxt/module/plugins' - -export default defineNitroPlugin(sentryCloudflareNitroPlugin((nitroApp: NitroApp) => { - // You can access `nitroApp` here if needed - return { - dsn: '___PUBLIC_DSN___', - tracesSampleRate: 1.0, - } -})) -``` - - - ### Add Readable Stack Traces With Source Maps (Optional) To upload source maps for clear error stack traces, add your Sentry auth token, organization, and project slugs in the `sentry` options inside your configuration file: @@ -260,14 +204,9 @@ export default defineNuxtConfig({ }); ``` - ### Avoid Ad Blockers With Tunneling (Optional) - - + ### Control the Data You Send to Sentry (Optional) @@ -354,18 +293,8 @@ Then update the test page by including a new button that executes a function to - - -Once you have your test code in place, build and run your project. - - - - - Once you have your test code in place, run your project in production mode (`nuxi build`, then `node .output/server/index.mjs`) or in development mode (`nuxt dev`). - - After running your project, open your test page in a browser and click the buttons. @@ -374,25 +303,14 @@ After running your project, open your test page in a browser and click the butto Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). - - - - - - - - - - ## Next Steps At this point, you should have integrated Sentry into your Nuxt application and should already be sending data to your Sentry project. Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are: - - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup - Learn how to [manually capture errors](/platforms/javascript/guides/nuxt/usage/) - Continue to [customize your configuration](/platforms/javascript/guides/nuxt/configuration/) @@ -409,22 +327,4 @@ Now's a good time to customize your setup and look into more advanced topics. Ou - - - -- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Learn how to [manually capture errors](/platforms/javascript/guides/nuxt/usage/) -- Continue to [customize your configuration](/platforms/javascript/guides/nuxt/configuration/) -- Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts -- Learn how to [track your Vue components or your Pinia store](/platforms/javascript/guides/nuxt/features/) - - - -- Find various support topics in Cloudflare troubleshooting and [Nuxt troubleshooting](/platforms/javascript/guides/nuxt/troubleshooting/) -- [Get support](https://www.sentry.help/en/) - - - - - diff --git a/platform-includes/getting-started-complete/javascript.remix.mdx b/platform-includes/getting-started-complete/javascript.remix.mdx index d3507e2ad8fa6..db074eb1a0887 100644 --- a/platform-includes/getting-started-complete/javascript.remix.mdx +++ b/platform-includes/getting-started-complete/javascript.remix.mdx @@ -111,8 +111,6 @@ export default withSentry(App); ### Configure Server-Side Sentry - - Create an instrumentation file `instrument.server.mjs` in your project's root folder and initialize the Sentry SDK within it: ```typescript {tabTitle:Server} {filename: instrument.server.mjs} @@ -178,91 +176,8 @@ const app = express(); - - - - -Create a Worker entry file, for example `server.ts` in your project's root folder, and set it as `main` in your wrangler config. - -In this file, instrument your Remix server build with `instrumentBuild` from `@sentry/remix/cloudflare`, pass it to `createRequestHandler`, and wrap the exported handler with `Sentry.withSentry()` from `@sentry/cloudflare`. `withSentry` isolates each request, so scope data like tags and users stays on the request that set it. - - - -Don't also wrap `createRequestHandler` with `makeWrappedCreateRequestHandler`. Combined with `withSentry`, it reports every request twice, as two `http.server` transactions in two different traces. - - - -```typescript {filename:server.ts} -import { createRequestHandler } from "@remix-run/cloudflare"; -import * as Sentry from "@sentry/cloudflare"; -import { instrumentBuild } from "@sentry/remix/cloudflare"; -// The server build produced by `remix vite:build` -import * as remixBuild from "./build/server/index.js"; - -const handleRequest = createRequestHandler(instrumentBuild(remixBuild)); - -export default Sentry.withSentry( - (env) => ({ - dsn: "___PUBLIC_DSN___", - // ___PRODUCT_OPTION_START___ performance - - // Set tracesSampleRate to 1.0 to capture 100% - // of transactions for tracing. - // We recommend adjusting this value in production - // Learn more at - // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate - tracesSampleRate: 1.0, - // ___PRODUCT_OPTION_END___ performance - }), - { - async fetch(request, env, ctx) { - return handleRequest(request, { env, ctx }); - }, - } -); -``` - - - - - -```javascript {filename:functions/_middleware.js} -import * as Sentry from "@sentry/cloudflare"; - -export const onRequest = [ - // Make sure Sentry is the first middleware - Sentry.sentryPagesPlugin((context) => ({ - dsn: "___PUBLIC_DSN___", - - // ___PRODUCT_OPTION_START___ performance - - // Set tracesSampleRate to 1.0 to capture 100% - // of transactions for tracing. - // We recommend adjusting this value in production - // Learn more at - // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate - tracesSampleRate: 1.0, - // ___PRODUCT_OPTION_END___ performance - - // Optionally limit which action formData fields are captured. - // Without this option, all fields are captured. - captureActionFormDataKeys: { - key_x: true, - key_y: true, - }, - })), - // Add more middlewares here -]; -``` - - - - - ### Capture Server-Side Errors - - To automatically capture server-side errors, export a [`handleError`](https://remix.run/docs/en/main/file-conventions/entry.server#handleerror) function from your server entry point (`entry.server.tsx`). Choose one of the two options: - Wrap your custom error handler with `wrapHandleErrorWithSentry`. @@ -290,41 +205,8 @@ import * as Sentry from "@sentry/remix"; export const handleError = Sentry.sentryHandleError; ``` - - - - -To automatically capture server-side errors, export `sentryHandleError` as the [`handleError`](https://remix.run/docs/en/main/file-conventions/entry.server#handleerror) function from your server entry point (`entry.server.tsx`). Without this export, Remix handles errors thrown in loaders and actions itself, and Sentry doesn't receive them. - - - -Import from `@sentry/remix/cloudflare`, not from `@sentry/remix`. In a Cloudflare server build, `sentryHandleError` from `@sentry/remix` is `undefined`, and no errors are captured. - - - -```typescript {filename: entry.server.tsx} -import { sentryHandleError } from "@sentry/remix/cloudflare"; - -export const handleError = sentryHandleError; -``` - - - - - -### Configure Cloudflare for Sentry - - - - - ### Configure Vite - - Add `sentryRemixVitePlugin` from `@sentry/remix/vite` to your `vite.config.ts`. The plugin: - Parameterizes client-side transaction names with your route patterns, for example `/users/:id`. @@ -351,46 +233,6 @@ export default defineConfig({ }); ``` - - - - -Add two Sentry plugins to your `vite.config.ts`, next to the Remix plugin: - -- `sentryRemixVitePlugin` from `@sentry/remix/vite` parameterizes transaction names with your route patterns, for example `/users/:id`. -- `sentryCloudflareVitePlugin` from `@sentry/cloudflare/vite` instruments supported bundled dependencies at build time, so you get spans for database clients like `mysql`. Without it, database calls produce no spans and no warning. - -Set `ssr.target` to `webworker` and bundle the Sentry packages and any database client you want traced with `ssr.noExternal`. Setting `noExternal: true` bundles every dependency, which works too. - -```typescript {filename:vite.config.ts} {2-3, 11-12, 14-17} -import { vitePlugin as remix } from "@remix-run/dev"; -import { sentryCloudflareVitePlugin } from "@sentry/cloudflare/vite"; -import { sentryRemixVitePlugin } from "@sentry/remix/vite"; -import { defineConfig } from "vite"; - -export default defineConfig({ - plugins: [ - remix({ - // ... your Remix plugin options - }), - sentryRemixVitePlugin(), - sentryCloudflareVitePlugin(), - ], - ssr: { - target: "webworker", - noExternal: ["mysql", /^@sentry\//, "@opentelemetry/api"], - }, -}); -``` - -Build your app with `remix vite:build`. Under Vite 6, a plain `vite build` only builds the client and skips `build/server`, without an error. - -```bash -npx remix vite:build -``` - - - ### Add Readable Stack Traces With Source Maps (Optional) To upload source maps for clear error stack traces, pass your Sentry organization, project, and auth token to `sentryRemixVitePlugin` from the previous step. It injects debug IDs, uploads the source maps during your production build, and deletes them from your build output afterwards. @@ -437,13 +279,10 @@ SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ - ### Avoid Ad Blockers With Tunneling (Optional) - - ### Control the Data You Send to Sentry (Optional) @@ -519,17 +358,8 @@ Open the page in a browser and click the button to trigger the frontend error an Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). - - - - - - - - - ## Next Steps At this point, you should have integrated Sentry into your Remix application and should already be sending error and performance data to your Sentry project. @@ -541,7 +371,6 @@ Now's a good time to customize your setup and look into more advanced topics. Ou - Continue to customize your configuration - Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts - - If you encountered issues with the manual setup, try our installation wizard @@ -549,14 +378,3 @@ Now's a good time to customize your setup and look into more advanced topics. Ou - [Get support](https://www.sentry.help/en/) - - - - - -- If you encountered issues with the manual setup, try our installation wizard -- Find various support topics in Cloudflare troubleshooting and [Remix troubleshooting](/platforms/javascript/guides/remix/troubleshooting/) -- [Get support](https://www.sentry.help/en/) - - - diff --git a/platform-includes/getting-started-complete/javascript.sveltekit.mdx b/platform-includes/getting-started-complete/javascript.sveltekit.mdx index c37251053054d..52fc145582743 100644 --- a/platform-includes/getting-started-complete/javascript.sveltekit.mdx +++ b/platform-includes/getting-started-complete/javascript.sveltekit.mdx @@ -20,18 +20,12 @@ This means that Sentry can now follow the official best practice for how the SDK SvelteKit observability is still an experimental feature in SvelteKit 2.x, but we recommend giving it a try. The Sentry wizard, as well as this guide, will use it as the default way of setting up the SDK. - - If you've already set up the SDK and don't want to migrate to the new setup, or don't want to upgrade to SvelteKit `2.31.0` or higher, that's fine too. Just follow this guide instead. However, note that auto instrumentation (e.g. for database queries) will not work. - -
- - The SvelteKit Sentry SDK is designed to work out of the box with several SvelteKit adapters and their underlying server runtimes. Here's an overview of the current support: @@ -41,7 +35,7 @@ Here's an overview of the current support: - [Adapter-vercel](https://kit.svelte.dev/docs/adapter-vercel) when used with Vercel's Node.js Lambda runtime - [Adapter-node](https://kit.svelte.dev/docs/adapter-node) - **Supported non-Node.js runtimes** - - [Adapter-cloudflare](https://kit.svelte.dev/docs/adapter-cloudflare) requires [additional setup](/platforms/javascript/guides/cloudflare/frameworks/sveltekit/) + - [Adapter-cloudflare](https://kit.svelte.dev/docs/adapter-cloudflare) requires [additional setup](/platforms/javascript/guides/sveltekit/cloudflare/) - **Currently not supported** - Non-Node.js server runtimes, such as Vercel's edge runtime, are not yet supported. - **Other adapters** @@ -49,8 +43,6 @@ Here's an overview of the current support: - - ## Install @@ -66,17 +58,8 @@ Choose the features you want to configure, and this guide will show you how: ]} /> - - - - - - - - - ### Install the Sentry SDK Run the command for your preferred package manager to add the Sentry SDK to your application: @@ -152,18 +135,8 @@ export const handleError = Sentry.handleErrorWithSentry(myErrorHandler); ### Configure Server-Side Sentry - - _Requires SvelteKit `2.31.0` or higher and `@sentry/sveltekit` `10.8.0` or higher._ If you're using older versions, check out [this guide](../manual-setup__v10.7.0#configure-server-side-sentry) instead. - - - - -_Requires SvelteKit `2.31.0` or higher and `@sentry/sveltekit` `10.8.0` or higher._ - - - Configure server-side instrumentation and tracing. Where this config lives depends on your SvelteKit version — SvelteKit 2 uses `svelte.config.js`, while SvelteKit 3 moved it into the `sveltekit()` Vite plugin options in `vite.config.(js|ts)` instead (see [Configure Vite](#configure-vite) below). SvelteKit 3 no longer needs an instrumentation flag, so the only option to set there is `tracing`. ```js {tabTitle:SvelteKit 2} {mdExpandTabs} {filename:svelte.config.js} {3-12} @@ -204,8 +177,6 @@ export default defineConfig({ }); ``` - - Create a `src/instrumentation.server.(js|ts)` file (if you don't have one already) to initialize the server-side SDK: ```js {filename:src/instrumentation.server.(js|ts)} {1, 3-15} @@ -250,49 +221,6 @@ If you're using SvelteKit versions older than `2.16.0` and encounter Content Sec
- - - - -Create a server hooks file `src/hooks.server.(js|ts)` in your project if you don't have one already. In this file, import and initialize the Sentry SDK and add the `handleErrorWithSentry` function to the [`handleError` hook](https://svelte.dev/docs/kit/hooks#Shared-hooks-handleError) and Sentry's Cloudflare request handler to the [`handle` hook](https://kit.svelte.dev/docs/hooks#server-hooks-handle). - -```javascript {filename:src/hooks.server.(js|ts)} -import { - handleErrorWithSentry, - sentryHandle, - initCloudflareSentryHandle, -} from "@sentry/sveltekit"; -import { sequence } from "@sveltejs/kit/hooks"; -import * as Sentry from "@sentry/sveltekit"; - -export const handle = sequence( - initCloudflareSentryHandle({ - dsn: "___PUBLIC_DSN___", - - // ___PRODUCT_OPTION_START___ performance - - // Set tracesSampleRate to 1.0 to capture 100% - // of transactions for tracing. - // We recommend adjusting this value in production - // Learn more at - // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate - tracesSampleRate: 1.0, - // ___PRODUCT_OPTION_END___ performance - }), - sentryHandle() -); - -const myErrorHandler = ({ error, event }) => { - console.error("An error occurred on the server side:", error, event); -}; - -export const handleError = Sentry.handleErrorWithSentry(myErrorHandler); -// or alternatively, if you don't have a custom error handler: -// export const handleError = handleErrorWithSentry(); -``` - - - ### Configure Vite Add the `sentrySvelteKit` plugin **before** `sveltekit` in your `vite.config.(js|ts)` file to automatically upload source maps to Sentry and instrument `load` functions for tracing if it's configured. @@ -308,17 +236,6 @@ export default defineConfig({ }); ``` - - -### Configure Cloudflare for Sentry - - - - - ### Add Readable Stack Traces With Source Maps (Optional) To upload source maps for clear error stack traces, add your Sentry auth token, organization, and project slug in your `vite.config.(js|ts)` file: @@ -351,7 +268,6 @@ SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ - ### Override Adapter Detection `sentrySvelteKit` tries to auto-detect your SvelteKit adapter to configure source maps upload correctly. If you're using an unsupported adapter or the wrong one is detected, set it using the `adapter` option: @@ -371,15 +287,10 @@ export default { }; ``` - - - ### Avoid Ad Blockers With Tunneling (Optional) - - ### Control the Data You Send to Sentry (Optional) @@ -466,17 +377,8 @@ Additionally, this starts a trace to measure the time it takes for the API reque Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). - - - - - - - - - ## Next Steps At this point, you should have integrated Sentry into your SvelteKit application and should already be sending data to your Sentry project. @@ -484,12 +386,11 @@ At this point, you should have integrated Sentry into your SvelteKit application Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are: - - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup - Learn how to [manually capture errors](/platforms/javascript/guides/sveltekit/usage/) - Continue to [customize your configuration](/platforms/javascript/guides/sveltekit/configuration/) - Learn how to [manually instrument](/platforms/javascript/guides/sveltekit/apis/#load-function-instrumentation) SvelteKit-specific features -- Learn more about [deploying SvelteKit apps to Cloudflare Workers and Pages](/platforms/javascript/guides/cloudflare/frameworks/sveltekit/) +- Learn more about [deploying SvelteKit apps to Cloudflare Workers and Pages](/platforms/javascript/guides/sveltekit/cloudflare/) - Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts @@ -500,21 +401,4 @@ Our next recommended steps for you are: - - - -- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup -- Learn how to [manually capture errors](/platforms/javascript/guides/cloudflare/usage/) -- Continue to [customize your configuration](/platforms/javascript/guides/cloudflare/configuration/) -- Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts -- Learn how to [manually instrument](/platforms/javascript/guides/sveltekit/apis/#load-function-instrumentation) SvelteKit-specific features - - - -- Find various support topics in Cloudflare troubleshooting and [SvelteKit troubleshooting](/platforms/javascript/guides/sveltekit/troubleshooting/) -- [Get support](https://www.sentry.help/en/) - - - - diff --git a/platform-includes/getting-started-install/javascript.koa.mdx b/platform-includes/getting-started-install/javascript.koa.mdx deleted file mode 100644 index d0c4e2e161466..0000000000000 --- a/platform-includes/getting-started-install/javascript.koa.mdx +++ /dev/null @@ -1,31 +0,0 @@ - - -```bash {tabTitle:npm} -npm install @sentry/node -``` - -```bash {tabTitle:yarn} -yarn add @sentry/node -``` - -```bash {tabTitle:pnpm} -pnpm add @sentry/node -``` - - - - - -```bash {tabTitle:npm} -npm install @sentry/node @sentry/profiling-node --save -``` - -```bash {tabTitle:yarn} -yarn add @sentry/node @sentry/profiling-node -``` - -```bash {tabTitle:pnpm} -pnpm add @sentry/node @sentry/profiling-node -``` - - diff --git a/platform-includes/getting-started-node/javascript.mdx b/platform-includes/getting-started-node/javascript.mdx index 6494a33f2dd07..339f211dd3356 100644 --- a/platform-includes/getting-started-node/javascript.mdx +++ b/platform-includes/getting-started-node/javascript.mdx @@ -1,4 +1,4 @@ - + @@ -6,7 +6,7 @@ Run the command for your preferred package manager to add the Sentry SDK to your application: - + ## Configure @@ -23,7 +23,7 @@ The snippet also turns on: - Tracing: via `tracesSampleRate` - Profiling: via `profileSessionSampleRate` and `nodeProfilingIntegration()` - + Then, use the [--import](https://nodejs.org/api/cli.html#--importmodule) command line option and point it to your `instrument.(js|mjs)` file to load the module before the application starts: @@ -37,15 +37,15 @@ node --import ./instrument.mjs app.mjs If you are using a bundler like vite, you can also follow the bundler setup docs instead. - + ### Add Readable Stack Traces With Source Maps - + ### Control the Data You Send to Sentry - + ## Send Logs @@ -66,7 +66,7 @@ On Node.js, ` Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. - + ### View Captured Data in Sentry diff --git a/platform-includes/getting-started-node/javascript.nextjs.mdx b/platform-includes/getting-started-node/javascript.nextjs.mdx new file mode 100644 index 0000000000000..09ba61db96a2d --- /dev/null +++ b/platform-includes/getting-started-node/javascript.nextjs.mdx @@ -0,0 +1,110 @@ + + + + +## Install + +### Run the Installation Wizard + +Run the Sentry wizard to automatically install the SDK and configure Sentry in your Next.js application: + +```bash +npx @sentry/wizard@latest -i nextjs +``` + +The wizard asks whether you want to enable **Tracing** and **Session Replay**, route browser requests through your server to avoid ad blockers, and create an example page. To match the configuration in this guide, answer **Yes** to each. + +Prefer to set things up yourself? Check out the [Manual Setup](/platforms/javascript/guides/nextjs/manual-setup/) guide. + +## Configure + +**Error Monitoring** starts working as soon as you call `Sentry.init()`. **Logs** and **Application Metrics** need no extra configuration, and you'll learn how to send them in steps [#3](#send-logs) and [#4](#send-application-metrics-). +This guide also enables **Tracing**, **Session Replay**, and **User Feedback**. + + + + + +### Control the Data You Send to Sentry + + + +## Send Logs + + + +If you're already logging with another library, use an integration to capture those logs as Sentry Logs automatically: + +- `consoleLoggingIntegration` for `console` calls +- Consola +- Pino +- Winston + +## Send Application Metrics + + + +In the Node.js runtime, `nodeRuntimeMetricsIntegration` also collects runtime health metrics automatically. + +## Verify Your Setup + +Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. + +The wizard created an example page that sends a test error from both your frontend and your backend: + +1. Start your development server: + + ```bash + npm run dev + ``` + +2. Open [localhost:3000/sentry-example-page](http://localhost:3000/sentry-example-page) in your browser. +3. Click **Throw Sample Error**. + +If you skipped the example page, add a test button to one of your pages instead. Clicking it will trigger an error for Sentry to capture. + +```tsx {filename:app/page.tsx} +"use client"; + +export default function Page() { + return ( + + ); +} +``` + + + +### View Captured Data in Sentry + +Now, head over to your project on [Sentry.io](https://sentry.io/) to view the collected data (it takes a couple of moments for the data to appear). + + + +## Next Steps + +At this point, you should have integrated Sentry into your Next.js application. Here's what to explore next: + +- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup +- Set up Agent Tracing to monitor agents built with the Vercel AI SDK, LangChain, and more +- Set up tunneling to avoid ad blockers blocking Sentry events, if you didn't enable it in the wizard + + + +- If you encountered issues with our installation wizard, try [setting up Sentry manually](/platforms/javascript/guides/nextjs/manual-setup/) +- Find various topics in Troubleshooting +- [Get support](https://www.sentry.help/en/) + + + + diff --git a/platform-includes/getting-started-node/javascript.nuxt.mdx b/platform-includes/getting-started-node/javascript.nuxt.mdx new file mode 100644 index 0000000000000..dbf7c4ea86950 --- /dev/null +++ b/platform-includes/getting-started-node/javascript.nuxt.mdx @@ -0,0 +1,130 @@ + + + + +## Install + + + + + + + + + +## Avoid Ad Blockers With Tunneling (Optional) + + + +## Control the Data You Send to Sentry (Optional) + + + +## Verify Your Setup + +The `sentry init` command checks the integration files it creates or modifies before it finishes. To confirm runtime events are reaching Sentry, start your Nuxt app, exercise the parts of your app that should send events, and then check your Sentry project. + +If you used the Nuxt installation wizard instead, you can also verify your setup with the example page or component it creates. + + +The wizard creates a `SentryErrorButton` component when it fails to add an example page to your project. This usually happens if you don't have a `app.vue` file or if that file does not contain the `NuxtPage` component. To verify your setup, follow these steps before continuing with the next section, "View Captured Data in Sentry": + +1. Add the `SentryErrorButton` component to a page and open it in your browser. For most Nuxt applications, this will be at localhost. +2. Click the "Throw Sample Error" button, which triggers an error and starts a performance trace on the client side. + +To test the server side as well, refer to the "Verify" section in the [Manual setup guide](/platforms/javascript/guides/nuxt/manual-setup/). + + + +To test Sentry, you can run your Nuxt application in either production or development mode. +We **recommend testing in production mode** as it most closely resembles your deployed application's environment. + +The SDK bundles `sentry.server.config.ts` into the Nitro server build and initializes Sentry when the server starts. To learn more, see Server-Side Installation. + +### Run in Production Mode (Recommended) + +Build your project with `nuxi build`, then start the server. + +```bash +# Start your app after building your project with `nuxi build` +node .output/server/index.mjs +``` + +### Run in Development Mode + +Sentry also monitors the server side during development. Start the dev server as usual. + +Spans from some libraries, such as database clients, can be missing in development mode. +Errors and request traces always work. To learn more, see Development Mode. + +```bash +nuxt dev +``` + +If you used the Nuxt installation wizard, after building and running your project: + +1. Open the example page `/sentry-example-page` in your browser. For most Nuxt applications, this will be at localhost. +2. Click the "Throw sample error" button. This triggers two errors: + - a frontend error + - an error within the API route + +Sentry captures both of these errors for you. Additionally, the button click starts a performance trace to measure the time it takes for the API request to complete. + + + +### View Captured Data in Sentry + +Now, head over to your project on [Sentry.io](https://sentry.io/) to view the collected data (it takes a couple of moments for the data to appear). + + + + + +## Next Steps + +At this point, you should have integrated Sentry into your Nuxt application and should already be sending error and performance data to your Sentry project. + +Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are: + +- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup +- Learn how to [manually capture errors](/platforms/javascript/guides/nuxt/usage/) +- Continue to [customize your configuration](/platforms/javascript/guides/nuxt/configuration/) +- Get familiar with [Sentry's product features](/product/) like tracing, insights, and alerts +- Learn how to [track your Vue components or your Pinia store](/platforms/javascript/guides/nuxt/features/) +- Learn how to [add support for different Nitro deployment presets](/platforms/javascript/guides/nuxt/features/nitro-deployment-presets/) (like Cloudflare) + + + +- If you encountered issues with our installation wizard, try [setting up Sentry manually](/platforms/javascript/guides/nuxt/manual-setup/) +- [Get support](https://www.sentry.help/en/) + + + + diff --git a/platform-includes/getting-started-prerequisites/dart.mdx b/platform-includes/getting-started-prerequisites/dart.mdx new file mode 100644 index 0000000000000..9675f9bacf075 --- /dev/null +++ b/platform-includes/getting-started-prerequisites/dart.mdx @@ -0,0 +1,8 @@ +## Prerequisites + +These instructions use Sentry Dart SDK v10. You need: + +- A Sentry [account](https://sentry.io/signup/) and [project](/product/projects/) +- An application using **Dart 3.12.0** or later + +For an existing Sentry integration, review the [v10 breaking changes](https://github.com/getsentry/sentry-dart/releases/tag/10.0.0) before upgrading. diff --git a/platform-includes/getting-started-prerequisites/javascript.sveltekit.mdx b/platform-includes/getting-started-prerequisites/javascript.sveltekit.mdx index d042a382ab607..8d099e46eb8d6 100644 --- a/platform-includes/getting-started-prerequisites/javascript.sveltekit.mdx +++ b/platform-includes/getting-started-prerequisites/javascript.sveltekit.mdx @@ -36,7 +36,7 @@ Here's an overview of the current support: - [Adapter-vercel](https://kit.svelte.dev/docs/adapter-vercel) when used with Vercel's Node.js Lambda runtime - [Adapter-node](https://kit.svelte.dev/docs/adapter-node) - **Supported non-Node.js runtimes** - - [Adapter-cloudflare](https://kit.svelte.dev/docs/adapter-cloudflare) requires [additional setup](/platforms/javascript/guides/cloudflare/frameworks/sveltekit/) + - [Adapter-cloudflare](https://kit.svelte.dev/docs/adapter-cloudflare) requires [additional setup](/platforms/javascript/guides/sveltekit/cloudflare/) - **Currently not supported** - Non-Node.js server runtimes, such as Vercel's edge runtime, are not yet supported. - **Other adapters** diff --git a/platform-includes/getting-started-tunneling/javascript.astro.mdx b/platform-includes/getting-started-tunneling/javascript.astro.mdx new file mode 100644 index 0000000000000..9ba227ed3b6f7 --- /dev/null +++ b/platform-includes/getting-started-tunneling/javascript.astro.mdx @@ -0,0 +1,9 @@ +To keep ad blockers from dropping Sentry events, send them through a tunnel on your own origin. The SDK serves the tunnel and forwards the events to Sentry. + +Set `tunnel: true` in your client `Sentry.init`, and add `serveTunnelIntegration` to your server `Sentry.init`: + + + + + +Learn more about the options in `serveTunnelIntegration`. To set up your own tunnel endpoint instead, see the Tunneling page. diff --git a/platform-includes/getting-started-tunneling/javascript.mdx b/platform-includes/getting-started-tunneling/javascript.mdx index 12c290d10e01f..538a67c144210 100644 --- a/platform-includes/getting-started-tunneling/javascript.mdx +++ b/platform-includes/getting-started-tunneling/javascript.mdx @@ -1,10 +1,10 @@ -You can prevent ad blockers from blocking Sentry events using tunneling. Use the `tunnel` option in `Sentry.init` to add an API endpoint in your application that forwards Sentry events to Sentry servers. - -This will send all events to the `tunnel` endpoint. However, the events need to be parsed and redirected to Sentry, so you'll need to do additional configuration on the server. The endpoint must forward only the request body to Sentry and accept only your own DSN. You can find a detailed explanation on how to do this on our Troubleshooting page. +To keep ad blockers from dropping Sentry events, send them through a tunnel on your own origin. Set `tunnel: true` in `Sentry.init`, and your server forwards the events to Sentry: ```javascript {3} Sentry.init({ dsn: "___PUBLIC_DSN___", - tunnel: "/tunnel", + tunnel: true, }); ``` + +Learn how to serve the tunnel on your server, or how to write your own tunnel endpoint, on the Tunneling page. diff --git a/platform-includes/getting-started-tunneling/javascript.nuxt.mdx b/platform-includes/getting-started-tunneling/javascript.nuxt.mdx new file mode 100644 index 0000000000000..9ba227ed3b6f7 --- /dev/null +++ b/platform-includes/getting-started-tunneling/javascript.nuxt.mdx @@ -0,0 +1,9 @@ +To keep ad blockers from dropping Sentry events, send them through a tunnel on your own origin. The SDK serves the tunnel and forwards the events to Sentry. + +Set `tunnel: true` in your client `Sentry.init`, and add `serveTunnelIntegration` to your server `Sentry.init`: + + + + + +Learn more about the options in `serveTunnelIntegration`. To set up your own tunnel endpoint instead, see the Tunneling page. diff --git a/platform-includes/getting-started-tunneling/javascript.sveltekit.mdx b/platform-includes/getting-started-tunneling/javascript.sveltekit.mdx index 3b1ef2770c630..9ba227ed3b6f7 100644 --- a/platform-includes/getting-started-tunneling/javascript.sveltekit.mdx +++ b/platform-includes/getting-started-tunneling/javascript.sveltekit.mdx @@ -1,10 +1,9 @@ -You can prevent ad blockers from blocking Sentry events using tunneling. Use the `tunnel` option inside your `hooks.client.(js|ts)` file's `Sentry.init` to add an API endpoint in your application that forwards Sentry events to Sentry servers. +To keep ad blockers from dropping Sentry events, send them through a tunnel on your own origin. The SDK serves the tunnel and forwards the events to Sentry. -This will send all events to the `tunnel` endpoint. However, the events need to be parsed and redirected to Sentry, so you'll need to do additional configuration on the server. The endpoint must forward only the request body to Sentry and accept only your own DSN. You can find a detailed explanation on how to do this on our [Troubleshooting page](/platforms/javascript/guides/sveltekit/troubleshooting/#using-the-tunnel-option). +Set `tunnel: true` in your client `Sentry.init`, and add `serveTunnelIntegration` to your server `Sentry.init`: -```javascript {filename:hooks.client.(js|ts)} {3} -Sentry.init({ - dsn: "___PUBLIC_DSN___", - tunnel: "/tunnel", -}); -``` + + + + +Learn more about the options in `serveTunnelIntegration`. To set up your own tunnel endpoint instead, see the Tunneling page. diff --git a/platform-includes/getting-started-verify-data/dotnet.mdx b/platform-includes/getting-started-verify-data/dotnet.mdx new file mode 100644 index 0000000000000..9580025e958ee --- /dev/null +++ b/platform-includes/getting-started-verify-data/dotnet.mdx @@ -0,0 +1,9 @@ +Run any log and metric examples you've added after SDK initialization. To verify automatic tracing, exercise an instrumented operation, such as an incoming HTTP request or a supported UI interaction. + +Logs and metrics are batched. In an async test method, flush pending data before a short-lived test exits: + +```csharp +await SentrySdk.FlushAsync(); +``` + +Check **Issues** for the captured error, **Logs** for log messages, **Metrics** for application metrics, and **Traces** for sampled transactions. Error capture alone doesn't verify the other features. diff --git a/platform-includes/getting-started-verify-issues-tracing/javascript.bun.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.bun.mdx new file mode 100644 index 0000000000000..3f64ed54344fb --- /dev/null +++ b/platform-includes/getting-started-verify-issues-tracing/javascript.bun.mdx @@ -0,0 +1,7 @@ +Add an intentional error to your main application file: + +```javascript +setTimeout(() => { + throw new Error("Sentry Test Error"); +}, 0); +``` diff --git a/platform-includes/getting-started-verify-issues-tracing/javascript.deno.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.deno.mdx new file mode 100644 index 0000000000000..d65d054a8eb1d --- /dev/null +++ b/platform-includes/getting-started-verify-issues-tracing/javascript.deno.mdx @@ -0,0 +1,7 @@ +Add an intentional error to your application: + +```javascript +setTimeout(() => { + throw new Error("Sentry Test Error"); +}, 0); +``` diff --git a/platform-includes/getting-started-verify/javascript.express.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.express.mdx similarity index 100% rename from platform-includes/getting-started-verify/javascript.express.mdx rename to platform-includes/getting-started-verify-issues-tracing/javascript.express.mdx diff --git a/platform-includes/getting-started-verify/javascript.fastify.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.fastify.mdx similarity index 100% rename from platform-includes/getting-started-verify/javascript.fastify.mdx rename to platform-includes/getting-started-verify-issues-tracing/javascript.fastify.mdx diff --git a/platform-includes/getting-started-verify/javascript.hapi.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.hapi.mdx similarity index 100% rename from platform-includes/getting-started-verify/javascript.hapi.mdx rename to platform-includes/getting-started-verify-issues-tracing/javascript.hapi.mdx diff --git a/platform-includes/getting-started-verify/javascript.koa.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.koa.mdx similarity index 100% rename from platform-includes/getting-started-verify/javascript.koa.mdx rename to platform-includes/getting-started-verify-issues-tracing/javascript.koa.mdx diff --git a/platform-includes/getting-started-verify-issues-tracing/javascript.mdx b/platform-includes/getting-started-verify-issues-tracing/javascript.mdx new file mode 100644 index 0000000000000..736f01a457988 --- /dev/null +++ b/platform-includes/getting-started-verify-issues-tracing/javascript.mdx @@ -0,0 +1,11 @@ +Add an intentional error to your main application file that Sentry will capture: + +```javascript +setTimeout(() => { + try { + foo(); + } catch (e) { + Sentry.captureException(e); + } +}, 99); +``` diff --git a/platform-includes/getting-started-verify-tracing/dotnet.mdx b/platform-includes/getting-started-verify-tracing/dotnet.mdx new file mode 100644 index 0000000000000..eca84a6033c5f --- /dev/null +++ b/platform-includes/getting-started-verify-tracing/dotnet.mdx @@ -0,0 +1,10 @@ +To verify tracing for code without automatic instrumentation, create and finish a test transaction after initializing Sentry: + +```csharp +var transaction = SentrySdk.StartTransaction("quickstart-test", "test"); +transaction.Finish(); +``` + +`TracesSampleRate` controls sampling; it doesn't create transactions by itself. See Custom Instrumentation to trace work in your application. + +If you enabled profiling, run a longer sampled transaction after the profiler has initialized. A short verification transaction might finish before the profiler collects any samples. diff --git a/platform-includes/getting-started-verify/javascript.node.mdx b/platform-includes/getting-started-verify/javascript.node.mdx index 736f01a457988..11d461b54dfc7 100644 --- a/platform-includes/getting-started-verify/javascript.node.mdx +++ b/platform-includes/getting-started-verify/javascript.node.mdx @@ -1,11 +1 @@ -Add an intentional error to your main application file that Sentry will capture: - -```javascript -setTimeout(() => { - try { - foo(); - } catch (e) { - Sentry.captureException(e); - } -}, 99); -``` + diff --git a/platform-includes/getting-started-wizard-files/javascript.nextjs.mdx b/platform-includes/getting-started-wizard-files/javascript.nextjs.mdx new file mode 100644 index 0000000000000..d3b92a08b86ab --- /dev/null +++ b/platform-includes/getting-started-wizard-files/javascript.nextjs.mdx @@ -0,0 +1,143 @@ +### Initialize the SDK + +Next.js runs code in different environments, so the wizard creates a separate initialization file for each in your project's root directory (or `src` folder): + +- `instrumentation-client.ts`: runs in the browser +- `sentry.server.config.ts`: runs in the Node.js runtime +- `sentry.edge.config.ts`: runs in the Edge runtime + +Use the tabs in the code box below to view each file. + +The snippets also turn on: + +- Tracing: via `tracesSampleRate` in all three files +- Session Replay: via `replayIntegration()`, sampled with `replaysSessionSampleRate` and `replaysOnErrorSampleRate` +- User Feedback: via `feedbackIntegration()`. The wizard doesn't add this integration, so add it to `instrumentation-client.ts` yourself. + +Don't need a feature? Remove its integration and options from the snippets. + +```typescript {tabTitle:Client} {mdExpandTabs} {filename:instrumentation-client.ts} +import * as Sentry from "@sentry/nextjs"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + integrations: [ + // enables Session Replay + Sentry.replayIntegration(), + // enables User Feedback + Sentry.feedbackIntegration({ + // Additional integration configuration goes in here + colorScheme: "system", + }), + ], + + // Enables Tracing. + // Set to 1.0 to capture 100% of spans for tracing. + // We recommend reducing this value in production. + tracesSampleRate: 1.0, + + // Capture replays for 10% of all sessions, + // plus for 100% of sessions with an error + // Requires Sentry.replayIntegration() + replaysSessionSampleRate: 0.1, + replaysOnErrorSampleRate: 1.0, +}); + +// Instruments client-side navigations +export const onRouterTransitionStart = Sentry.captureRouterTransitionStart; +``` + +```typescript {tabTitle:Server} {filename:sentry.server.config.ts} +import * as Sentry from "@sentry/nextjs"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + + // Enables Tracing. + // Set to 1.0 to capture 100% of spans for tracing. + // We recommend reducing this value in production. + tracesSampleRate: 1.0, +}); +``` + +```typescript {tabTitle:Edge} {filename:sentry.edge.config.ts} +import * as Sentry from "@sentry/nextjs"; + +Sentry.init({ + dsn: "___PUBLIC_DSN___", + + // Enables Tracing. + // Set to 1.0 to capture 100% of spans for tracing. + // We recommend reducing this value in production. + tracesSampleRate: 1.0, +}); +``` + +### Register the Server-Side Configuration + +The wizard creates a [Next.js instrumentation file](https://nextjs.org/docs/app/guides/instrumentation) named `instrumentation.ts`. It loads your server and edge configurations, and exports `onRequestError` to capture errors from Server Components, route handlers, and middleware. + +```typescript {filename:instrumentation.ts} +import * as Sentry from "@sentry/nextjs"; + +export async function register() { + if (process.env.NEXT_RUNTIME === "nodejs") { + await import("./sentry.server.config"); + } + + if (process.env.NEXT_RUNTIME === "edge") { + await import("./sentry.edge.config"); + } +} + +export const onRequestError = Sentry.captureRequestError; +``` + +### Capture React Render Errors + +If you use the App Router, the wizard adds Sentry to `app/global-error.tsx` to capture React rendering errors. If you use the Pages Router, it adds Sentry to `pages/_error.tsx` instead. + + + +### Apply Instrumentation to Your App + +The wizard wraps your Next.js configuration with `withSentryConfig`. This instruments your app at build time, uploads source maps, and, if you said yes in the wizard, routes browser requests to Sentry through your server to avoid ad blockers. + +To forward only the request body to Sentry, add a tunnel route handler (SDK version `10.77.1` and later on v10, `11.9.0` and later on v11). Use the handler if Vercel Deployment Protection or another login protects your app. +Learn more about the [`tunnelRoute` option](/platforms/javascript/guides/nextjs/configuration/build/#tunnelRoute). + +```typescript {filename:next.config.ts} +import type { NextConfig } from "next"; +import { withSentryConfig } from "@sentry/nextjs/config"; + +const nextConfig: NextConfig = { + // Your existing Next.js configuration +}; + +export default withSentryConfig(nextConfig, { + org: "___ORG_SLUG___", + project: "___PROJECT_SLUG___", + + // Only print logs for uploading source maps in CI + silent: !process.env.CI, + + // Upload a larger set of source maps for prettier stack traces (increases build time) + widenClientFileUpload: true, + + // Route browser requests to Sentry through a Next.js rewrite to avoid ad blockers. + // This can increase your server load as well as your hosting bill. + tunnelRoute: "/monitoring", +}); +``` + +### Add Readable Stack Traces With Source Maps + +The wizard stores your auth token in `.env.sentry-build-plugin` and adds the file to `.gitignore`. The Sentry build plugin uses this token to upload source maps when you build your app locally. + +For CI/CD builds, set the `SENTRY_AUTH_TOKEN` environment variable in your build system instead. + + + +```bash {filename:.env.sentry-build-plugin} +SENTRY_AUTH_TOKEN=___ORG_AUTH_TOKEN___ +``` diff --git a/platform-includes/logs/integrations/dotnet.mdx b/platform-includes/logs/integrations/dotnet.mdx index 59ccbcc7930f4..ec150ea6469a3 100644 --- a/platform-includes/logs/integrations/dotnet.mdx +++ b/platform-includes/logs/integrations/dotnet.mdx @@ -2,6 +2,7 @@ Available integrations:
    ASP.NET Core .NET Multi-platform App UI (.NET MAUI) +Generic Host Microsoft.Extensions.Logging Serilog NLog diff --git a/platform-includes/logs/options/dotnet.mdx b/platform-includes/logs/options/dotnet.mdx index ed7e850819e0d..8801a6d9f9e33 100644 --- a/platform-includes/logs/options/dotnet.mdx +++ b/platform-includes/logs/options/dotnet.mdx @@ -1,33 +1,24 @@ + + #### EnableLogs - -Set to `true` to send logs captured by logging integrations, such as `Microsoft.Extensions.Logging`, Serilog, NLog, and log4net. Defaults to `false`. +Set to `true` to send the entries your app writes through the `ILogger` API to Sentry as logs. Defaults to `false`. -Since version 6.10.0, this option doesn't apply to logs sent through the `SentrySdk.Logger` APIs. Those logs are always sent. - +This option doesn't apply to logs sent through the `SentrySdk.Logger` APIs or through the Serilog, NLog, and log4net integrations. Those logs are always sent. - -Set to `true` in order to enable the logging integration via the `ILogger` API. - + - -Set to `true` in order to enable the logging integration via the `Log`/`Logger` APIs. - +In earlier versions, `EnableLogs` was an option on `SentryOptions`, and the Serilog, NLog, and log4net integrations only sent logs when it was `true`. - -Set to `true` in order to enable the logging integration via the NLog `Logger` APIs. - + - -Set to `true` in order to enable the logging integration via the log4net `ILog` APIs. - + #### Configure Microsoft.Extensions.Logging Filters -In apps that use `Microsoft.Extensions.Logging`, setting `EnableLogs = true` enables Sentry's `Microsoft.Extensions.Logging` integration. -Sentry's provider defines the alias `Sentry`. +Sentry's `Microsoft.Extensions.Logging` provider defines the alias `Sentry`. Logs emitted through `ILogger` are sent to Sentry according to your configured provider/category filters and log levels. @@ -51,7 +42,7 @@ Use standard `Microsoft.Extensions.Logging` filtering to reduce noisy categories Setting `Logging:Sentry:LogLevel:Default` to `None` disables logs sent through the `Microsoft.Extensions.Logging` provider for all categories. Logs sent through the `SentrySdk.Logger` APIs aren't affected by these filters and are still sent. -Example with `EnableLogs = true` and `Logging:Sentry:LogLevel:Default = None`: +Example with `Logging:Sentry:LogLevel:Default = None`: ```csharp logger.LogInformation("Will not be sent to Sentry through Microsoft.Extensions.Logging"); @@ -72,6 +63,22 @@ For background on provider/category filtering, see [Logging in C# and .NET](http + + +#### MinimumLogLevel + +The NLog target sends entries at `Info` or higher as logs. To also send `Debug` entries, lower `MinimumLogLevel` when you add the target: + +```csharp +var config = new LoggingConfiguration(); +config.AddSentry(options => options.MinimumLogLevel = NLog.LogLevel.Debug); +LogManager.Configuration = config; +``` + +In `NLog.config`, set the `minimumLogLevel` attribute on the target instead. Set it to `Off` to send no logs from NLog. + + + #### SetBeforeSendLog To filter logs or update them before they are sent to Sentry, you can use the `SetBeforeSendLog(Func)` option. @@ -80,7 +87,6 @@ To filter logs or update them before they are sent to Sentry, you can use the `S options => { options.Dsn = "___PUBLIC_DSN___"; - options.EnableLogs = true; // a callback that is invoked before sending a log to Sentry options.SetBeforeSendLog(static log => { diff --git a/platform-includes/logs/options/unity.mdx b/platform-includes/logs/options/unity.mdx index 142a0715537e1..1e30ac0c9e9ca 100644 --- a/platform-includes/logs/options/unity.mdx +++ b/platform-includes/logs/options/unity.mdx @@ -2,11 +2,11 @@ The following configuration options are available for Sentry Logs in Unity: | Option | Description | Default | |--------|-------------|------------| -| **Enable Structured Logging** | Master toggle for the structured logging feature | `false` | +| **EnableLogs** (**Enable Structured Logging** in the editor) | Master toggle for the structured logging feature | `false` | | **CaptureStructuredLogsForLogType[`LogType.Log`]** | Forward `Debug.Log` calls to Sentry | `false` | -| **CaptureStructuredLogsForLogType[`LogType.Warning`]** | Forward `Debug.Warning` calls to Sentry | `true` | -| **CaptureStructuredLogsForLogType[`LogType.Assert`]** | Forward `Debug.Assert` calls to Sentry | `true` | -| **CaptureStructuredLogsForLogType[`LogType.Error`]** | Forward `Debug.Error` calls to Sentry | `true` | -| **CaptureStructuredLogsForLogType[`LogType.Exception`]** | Forward `Debug.Exception` calls to Sentry | `true` | +| **CaptureStructuredLogsForLogType[`LogType.Warning`]** | Forward `Debug.LogWarning` calls to Sentry | `true` | +| **CaptureStructuredLogsForLogType[`LogType.Assert`]** | Forward `Debug.LogAssertion` calls and failed `Debug.Assert` checks to Sentry (editor and development builds only) | `true` | +| **CaptureStructuredLogsForLogType[`LogType.Error`]** | Forward `Debug.LogError` calls to Sentry | `true` | +| **CaptureStructuredLogsForLogType[`LogType.Exception`]** | Forward `Debug.LogException` calls to Sentry | `true` | | **AddBreadcrumbsWithStructuredLogs** | Send `Debug` calls BOTH as Logs and as Breadcrumbs, instead of just Logs | `false` | | **Before Log Callback** | Handler to modify or filter log events before sending | None | diff --git a/platform-includes/logs/requirements/dotnet.mdx b/platform-includes/logs/requirements/dotnet.mdx index 33859401902c3..082e175707d43 100644 --- a/platform-includes/logs/requirements/dotnet.mdx +++ b/platform-includes/logs/requirements/dotnet.mdx @@ -1,7 +1,11 @@ - + Logs for are supported in Sentry SDK version `5.14.0` and above. + +Logs for are supported in Sentry SDK version `7.0.0` and above. + + Logs for are supported in Sentry SDK version `5.16.0` and above. diff --git a/platform-includes/logs/setup/dotnet.mdx b/platform-includes/logs/setup/dotnet.mdx index 8cbc3217063c1..2bf9fd9b4d0d3 100644 --- a/platform-includes/logs/setup/dotnet.mdx +++ b/platform-includes/logs/setup/dotnet.mdx @@ -1,6 +1,6 @@ -Logs sent through the `SentrySdk.Logger` APIs are always sent, so they don't need any extra configuration. To send logs captured by logging integrations, initialize the SDK with the `EnableLogs` option set to `true`. +Logs sent through the `SentrySdk.Logger` APIs are always sent, so they don't need any extra configuration. - + ```csharp SentrySdk.Init(options => @@ -9,99 +9,166 @@ SentrySdk.Init(options => }); ``` -You don't need a logs-specific option to use the `SentrySdk.Logger` APIs. Set `EnableLogs = true` only if you also send logs through a logging integration. +The Serilog, NLog, log4net, and `Microsoft.Extensions.Logging` integrations also send logs without a logs-specific option. + + + +In earlier versions, these integrations only sent logs when `EnableLogs` was `true`. + + - + + +To also send the entries your app writes through `ILogger`, set `EnableLogs` to `true`: ```csharp {tabTitle:Builder} .UseSentry(options => { options.Dsn = "___PUBLIC_DSN___"; - // Enable logs to be sent to Sentry + // Send ILogger entries to Sentry as logs options.EnableLogs = true; }); ``` + + + -This enables the `Microsoft.Extensions.Logging` integration. The `SentrySdk.Logger` APIs don't depend on `EnableLogs`. +```json {tabTitle:Configuration} {filename:appsettings.json} +{ + "Sentry": { + "Dsn": "___PUBLIC_DSN___", + "EnableLogs": true + } +} +``` + + + + + +If your app also sends `ILogger` entries through Serilog, NLog, or log4net, leave `EnableLogs` off and set up the framework as shown below, so each entry reaches Sentry once. + + + + + + + + + + + + + + + + + + -```csharp {tabTitle:Factory} -.AddSentry(options => +Initialize the SDK with `SentrySdk.Init`, then add Sentry to your logging builder. Entries your app writes through `ILogger` are then sent as logs, without a logs-specific option. + +```csharp +SentrySdk.Init(options => { options.Dsn = "___PUBLIC_DSN___"; - // Enable logs to be sent to Sentry - options.EnableLogs = true; }); + +builder.Logging.AddSentry(); ``` - +Apps on the .NET Generic Host, such as worker services, use `UseSentry` from the `Sentry.Extensions.Hosting` package instead, and set `EnableLogs = true` to send their `ILogger` entries as logs. See [Generic Host](/platforms/dotnet/guides/extensions-hosting/logs/). - + -```json {tabTitle:Configuration} {filename:appsettings.json} -{ - "Sentry": { - "Dsn": "___PUBLIC_DSN___", - "EnableLogs": true - } -} -``` +In earlier versions, `AddSentry` initialized the SDK itself and only sent logs when `EnableLogs` was `true`. On those versions, set the DSN and `EnableLogs` in `AddSentry(options => ...)` instead of calling `SentrySdk.Init`. + + +Initialize the SDK, then add the Sentry sink. The sink sends logs as soon as you add it. + ```csharp -.WriteTo.Sentry(options => +SentrySdk.Init(options => { options.Dsn = "___PUBLIC_DSN___"; - // Enable logs to be sent to Sentry - options.EnableLogs = true; }); -``` +Log.Logger = new LoggerConfiguration() + .WriteTo.Sentry() + .CreateLogger(); +``` +Initialize the SDK, then add the Sentry target, in code or in your `NLog.config`. As soon as you add the target, it sends entries at `Info` or higher as logs. To change that level, set [`MinimumLogLevel`](/platforms/dotnet/guides/nlog/#minimumloglevel). + ```csharp -LogManager.Configuration = new LoggingConfiguration(); -LogManager.Configuration - .AddSentry(options => - { - options.Dsn = "___PUBLIC_DSN___"; - // Enable logs to be sent to Sentry - options.EnableLogs = true; - }); -``` +SentrySdk.Init(options => +{ + options.Dsn = "___PUBLIC_DSN___"; +}); -If the SDK is initialized elsewhere (for example, through ASP.NET Core), enable `EnableLogs` on those options instead. The NLog target then captures logs without initializing the SDK itself. +var config = new LoggingConfiguration(); +config.AddSentry(); +LogManager.Configuration = config; +``` -`EnableLogs` isn't exposed as a log4net appender setting, so initialize the SDK with `SentrySdk.Init` and leave the DSN out of your log4net appender configuration. +Initialize the SDK. The `SentryAppender` in your log4net configuration then sends logs. ```csharp SentrySdk.Init(options => { options.Dsn = "___PUBLIC_DSN___"; - // Enable logs to be sent to Sentry - options.EnableLogs = true; }); ``` -The `SentryAppender` configured in your log4net configuration then captures logs without initializing the SDK itself. If the SDK is initialized elsewhere (for example, through ASP.NET Core), enable `EnableLogs` on those options instead. + + + + +If the SDK is initialized elsewhere, for example by `UseSentry`, skip `SentrySdk.Init`. + + + +In earlier versions, this integration only sent logs when `EnableLogs` was set to `true` on the options used to initialize the SDK. + + -It does _not_ capture the `Console.WriteLine()` standard output stream. + + + + + + + + + + + + + + + + + +It does _not_ capture the `Console.WriteLine()` standard output stream. diff --git a/platform-includes/logs/setup/unity.mdx b/platform-includes/logs/setup/unity.mdx index 7b2dc0a85f608..45aa10d1aa361 100644 --- a/platform-includes/logs/setup/unity.mdx +++ b/platform-includes/logs/setup/unity.mdx @@ -77,6 +77,6 @@ The log object of type `SentryLog` has the following members: - `Message` Property: (`string`) The formatted log message. - `Template` Property: (`string?`) The parameterized template string. - `Parameters` Property: (`ImmutableArray>`) The parameters to the template string. -- `ParentSpanId` Property: (`SpanId?`) The span id of the span that was active when the log was collected. +- `SpanId` Property: (`SpanId?`) The span id of the span that was active when the log was collected. - `TryGetAttribute(string key, out object value)` Method: Gets the attribute value associated with the specified key. Returns `true` if the log contains an attribute with the specified key and it's value is not `null`, otherwise `false`. - `SetAttribute(string key, object value)` Method: Sets a key-value pair of data attached to the log. Supported types are `string`, `bool`, integers up to a size of 64-bit signed, and floating-point numbers up to a size of 64-bit. diff --git a/platform-includes/logs/usage/dotnet.mdx b/platform-includes/logs/usage/dotnet.mdx index 794c46b4a8ee3..84f61fedc237c 100644 --- a/platform-includes/logs/usage/dotnet.mdx +++ b/platform-includes/logs/usage/dotnet.mdx @@ -1,4 +1,4 @@ - + Once the SDK is initialized, you can send logs using the `SentrySdk.Logger` APIs. @@ -13,7 +13,7 @@ SentrySdk.Logger.LogError("A {0} log message", "formatted"); - + Once the feature is enabled and the SDK is initialized, you can send logs using instances of the [ILogger](https://learn.microsoft.com/dotnet/api/microsoft.extensions.logging.ilogger-1) interface, resolved through [.NET dependency injection](https://learn.microsoft.com/dotnet/core/extensions/dependency-injection/overview). @@ -53,7 +53,7 @@ Sentry Structured Logs also work with [High-performance logging in .NET](https:/ -Once the feature is enabled on the SDK and the SDK is initialized, you can send logs using the _Serilog_ APIs. +Once the SDK is initialized and the Sentry sink is added, you can send logs using the _Serilog_ APIs. The static `Log` and instance `Logger` types expose various methods that you can use to log messages at six different log levels automatically mapped to Sentry's severity: @@ -83,7 +83,7 @@ The _Enrichments_ of _log events_ are attached as attributes to the logs, alongs -Once the feature is enabled on the SDK and the SDK is initialized, you can send logs using the _NLog_ APIs. +Once the SDK is initialized and the Sentry target is added, you can send logs using the _NLog_ APIs. The `Logger` type exposes various methods that you can use to log messages at six different log levels automatically mapped to Sentry's severity: @@ -112,7 +112,7 @@ The _properties_ of _log events_ are attached as attributes to the logs, alongsi -Once the feature is enabled on the SDK and the SDK is initialized, you can send logs using the _log4net_ APIs, for example through the `ILog` methods (`Debug`, `Info`, `Warn`, `Error`, and `Fatal`). +Once the SDK is initialized and the `SentryAppender` is configured, you can send logs using the _log4net_ APIs, for example through the `ILog` methods (`Debug`, `Info`, `Warn`, `Error`, and `Fatal`). log4net levels are automatically mapped to Sentry's severity: @@ -139,13 +139,13 @@ Log.Warn("Message with a custom property"); The log4net _properties_ (from the log event, `ThreadContext`, and `GlobalContext`) are attached as `property.` attributes to the logs, alongside a set of default attributes automatically provided by the SDK. The logger name is attached as the `category.name` attribute. -The `SentryAppender`'s `Environment` and `SendIdentity` settings also apply to structured logs: when configured, `Environment` sets the log's environment and `SendIdentity` attaches the log4net identity as the user. +The `SentryAppender`'s `SendIdentity` setting also applies to structured logs: when configured, it attaches the log4net identity as the user. Because log4net renders each message before it reaches the appender, structured logs from log4net carry the fully-formatted message but no message template or parameters. - + The SDK automatically provides a set of default attributes attached to your logs. Additionally, you can attach custom attributes via a delegate. diff --git a/platform-includes/metrics/options/dotnet.mdx b/platform-includes/metrics/options/dotnet.mdx index 66cf538065ca1..b895616385f38 100644 --- a/platform-includes/metrics/options/dotnet.mdx +++ b/platform-includes/metrics/options/dotnet.mdx @@ -1,6 +1,6 @@ #### EnableMetrics -This option is obsolete and ignored since version 6.10.0, and will be removed in version 7.0.0. Metrics sent through the `SentrySdk.Metrics` APIs are always sent, even if you set `EnableMetrics` to `false`. To drop metrics, use `SetBeforeSendMetric` and return `null`. +This option was removed in version 7.0.0, and has been ignored since version 6.10.0. Metrics sent through the `SentrySdk.Metrics` APIs are now always sent. To drop metrics, use `SetBeforeSendMetric` and return `null`. #### SetBeforeSendMetric diff --git a/platform-includes/metrics/options/unity.mdx b/platform-includes/metrics/options/unity.mdx index 18e60a8db51b9..871db46b8ced7 100644 --- a/platform-includes/metrics/options/unity.mdx +++ b/platform-includes/metrics/options/unity.mdx @@ -1,7 +1,3 @@ -#### EnableMetrics - -Metrics are enabled by default. Set to `false` to stop the SDK from sending metrics emitted through the `SentrySdk.Metrics` APIs. You can also toggle this in the editor under **Tools > Sentry > Advanced > Metrics**. - #### SetBeforeSendMetric To filter metrics, or update them before they are sent to Sentry, you can use the `SetBeforeSendMetric(Func)` option. If the callback returns `null`, the metric is not emitted. Attributes can also be updated in the callback delegate. diff --git a/platform-includes/metrics/setup/unity.mdx b/platform-includes/metrics/setup/unity.mdx index 6748c5bba9b10..4ca65c7e4066e 100644 --- a/platform-includes/metrics/setup/unity.mdx +++ b/platform-includes/metrics/setup/unity.mdx @@ -1,3 +1,3 @@ -Metrics are enabled by default. Once the SDK is initialized, no additional setup is required before you can start emitting metrics. +Metrics are always on. Once the SDK is initialized, you can start emitting metrics without any additional setup. -To turn metrics off, uncheck **Enable Metrics** under **Tools > Sentry > Advanced > Metrics** in the editor, or set `EnableMetrics` to `false` programmatically. See [Options](#options) below. +To drop metrics before they're sent, return `null` from the `SetBeforeSendMetric` callback. See [Options](#options) below. diff --git a/platform-includes/performance/add-spans-example/dotnet.mdx b/platform-includes/performance/add-spans-example/dotnet.mdx index b348f4e8a06a2..23a8809822544 100644 --- a/platform-includes/performance/add-spans-example/dotnet.mdx +++ b/platform-includes/performance/add-spans-example/dotnet.mdx @@ -28,7 +28,7 @@ public async Task PerformCheckoutAsync() var processSpan = transaction.StartChild( "process", // operation "processing shopping cart" // description - ) + ); await ProcessShoppingCartAsync(); diff --git a/platform-includes/performance/custom-sampling-context/dotnet.mdx b/platform-includes/performance/custom-sampling-context/dotnet.mdx index 262b06668a7aa..8dccdf72802fc 100644 --- a/platform-includes/performance/custom-sampling-context/dotnet.mdx +++ b/platform-includes/performance/custom-sampling-context/dotnet.mdx @@ -7,7 +7,7 @@ var samplingContext = new Dictionary }; var transaction = SentrySdk.StartTransaction( - new TransactionContext("GET /search", "http") + new TransactionContext("GET /search", "http"), samplingContext ); diff --git a/platform-includes/performance/force-sampling-decision/dotnet.mdx b/platform-includes/performance/force-sampling-decision/dotnet.mdx index 9da3c20ea4822..4fb26553f9e05 100644 --- a/platform-includes/performance/force-sampling-decision/dotnet.mdx +++ b/platform-includes/performance/force-sampling-decision/dotnet.mdx @@ -1,6 +1,6 @@ ```csharp // IsSampled -> true -var transactionContext = new TransactionContext("GET /search", "http", true); +var transactionContext = new TransactionContext("GET /search", "http", isSampled: true); var transaction = SentrySdk.StartTransaction(transactionContext); ``` diff --git a/platform-includes/performance/opentelemetry-install/dotnet.mdx b/platform-includes/performance/opentelemetry-install/dotnet.mdx index 1521e12a96ef1..f86ec2cb48fb0 100644 --- a/platform-includes/performance/opentelemetry-install/dotnet.mdx +++ b/platform-includes/performance/opentelemetry-install/dotnet.mdx @@ -1,6 +1,6 @@ -The `Sentry.OpenTelemetry` package requires `OpenTelemetry` package `1.5.0` or higher. +The `Sentry.OpenTelemetry` package requires `OpenTelemetry` package `1.12.0` or higher. diff --git a/platform-includes/performance/traces-sampler-config-option/python.mdx b/platform-includes/performance/traces-sampler-config-option/python.mdx index 3f9a0f5f22e5d..198ae0385f190 100644 --- a/platform-includes/performance/traces-sampler-config-option/python.mdx +++ b/platform-includes/performance/traces-sampler-config-option/python.mdx @@ -1,6 +1,6 @@ -A function responsible for determining the percentage chance a given transaction (or service span in stream mode) will be sent to Sentry. This configuration option accepts a function, which takes one parameter (the `sampling_context`). The given `sampling_context` contains information about the transaction and the context in which it's being created. The function must return a number between `0` (0% chance of being sent) and `1` (100% chance of being sent). Can also be used for filtering transactions, by returning `0` for those that are unwanted. +A function responsible for determining the percentage chance a given trace will be sent to Sentry. The SDK calls it when a service span starts (in SDK versions prior to `3.0`, when a transaction starts in transaction mode). This configuration option accepts a function, which takes one parameter (the `sampling_context`). The given `sampling_context` contains information about the span and the context in which it's being created. The function must return a number between `0` (0% chance of being sent) and `1` (100% chance of being sent). Can also be used for filtering traces, by returning `0` for those that are unwanted. Either this or `traces_sample_rate` must be defined to enable tracing. diff --git a/platform-includes/set-environment/dotnet.mdx b/platform-includes/set-environment/dotnet.mdx index 64dfa87a70e72..55510ca6316d3 100644 --- a/platform-includes/set-environment/dotnet.mdx +++ b/platform-includes/set-environment/dotnet.mdx @@ -7,3 +7,23 @@ options.Environment = "production"; // Add this to the SDK initialization callback options.Environment <- "production" ``` + +If you don't set it, the SDK uses `SENTRY_ENVIRONMENT`, the .NET host environment or a default. The Environment option describes the order. + +To change the environment at runtime, set it on the scope: + +```csharp +SentrySdk.ConfigureScope(scope => scope.Environment = "staging"); +``` + +```fsharp +SentrySdk.ConfigureScope(fun scope -> scope.Environment <- "staging") +``` + +Everything captured with that scope uses this environment, including logs, metrics, sessions, check-ins and trace propagation. Sessions and traces use the environment from when they start, so changes to `Scope.Environment` don't affect a session or trace that's already running. + + + +In earlier versions, `Scope.Environment` applied only to events and transactions. + + diff --git a/platform-includes/set-environment/dotnet.nlog.mdx b/platform-includes/set-environment/dotnet.nlog.mdx deleted file mode 100644 index 9b31a70582387..0000000000000 --- a/platform-includes/set-environment/dotnet.nlog.mdx +++ /dev/null @@ -1,40 +0,0 @@ - - -For more information on how to dynamically set event data via `NLog.config`, see NLog's [layout renderer documentation](https://nlog-project.org/config/?tab=layout-renderers). - - - - -```xml {tabTitle:NLog.config} - - - - - - - - - - - - - - - -``` - -```csharp -// Add this to the SDK initialization callback -options.Environment = "production"; -``` - -```fsharp -// Add this to the SDK initialization callback -options.Environment <- "production" -``` diff --git a/platform-includes/set-environment/unity.mdx b/platform-includes/set-environment/unity.mdx index 3872f0436db8b..5ecab79ecdf92 100644 --- a/platform-includes/set-environment/unity.mdx +++ b/platform-includes/set-environment/unity.mdx @@ -1,7 +1,7 @@ ```csharp using Sentry.Unity; -SentryUnity.Init(o => +SentrySdk.Init(o => { o.Environment = "production"; }); diff --git a/platform-includes/set-fingerprint/basic/unity.mdx b/platform-includes/set-fingerprint/basic/unity.mdx new file mode 100644 index 0000000000000..90231258145cb --- /dev/null +++ b/platform-includes/set-fingerprint/basic/unity.mdx @@ -0,0 +1,13 @@ +```csharp +// Add this to the SDK initialization callback +options.SetBeforeSend(@event => +{ + // SaveFileCorruptedException is an exception defined by your game + if (@event.Exception is SaveFileCorruptedException) + { + @event.SetFingerprint(new[] { "save-file-corrupted" }); + } + + return @event; +}); +``` diff --git a/platform-includes/set-fingerprint/database-connection/unity.mdx b/platform-includes/set-fingerprint/database-connection/unity.mdx new file mode 100644 index 0000000000000..efe513da58045 --- /dev/null +++ b/platform-includes/set-fingerprint/database-connection/unity.mdx @@ -0,0 +1,13 @@ +```csharp +// Add this to the SDK initialization callback +options.SetBeforeSend(@event => +{ + // BackendConnectionException is an exception defined by your game + if (@event.Exception is BackendConnectionException) + { + @event.SetFingerprint(new[] { "backend-connection-error" }); + } + + return @event; +}); +``` diff --git a/platform-includes/set-fingerprint/rpc/unity.mdx b/platform-includes/set-fingerprint/rpc/unity.mdx new file mode 100644 index 0000000000000..628d077c2d0b7 --- /dev/null +++ b/platform-includes/set-fingerprint/rpc/unity.mdx @@ -0,0 +1,31 @@ +```csharp +using System; +using System.Net; + +public class MyRpcException : Exception +{ + // The name of the RPC function that was called (e.g. "getPlayerInventory") + public string Function { get; set; } + + // For example a HTTP status code returned by the server. + public HttpStatusCode Code { get; set; } +} + +// Add this to the SDK initialization callback +options.SetBeforeSend(@event => +{ + if (@event.Exception is MyRpcException ex) + { + @event.SetFingerprint( + new[] + { + "{{ default }}", + ex.Function, + ex.Code.ToString(), + } + ); + } + + return @event; +}); +``` diff --git a/platform-includes/set-release/dotnet.mdx b/platform-includes/set-release/dotnet.mdx index 75cae89bc97ca..414f9197cdf82 100644 --- a/platform-includes/set-release/dotnet.mdx +++ b/platform-includes/set-release/dotnet.mdx @@ -12,7 +12,17 @@ The SDK attempts to locate the release to attach to events sent to Sentry. The SDK will first check if there's a version set on the environment via `SENTRY_RELEASE` and use it as-is. -If no version is found, the SDK will look at the [entry assembly's]() `AssemblyInformationalVersionAttribute`, which accepts a string value and is often used to set a GIT commit hash. If that returns null, then the SDK will look at the default `AssemblyVersionAttribute`, which accepts the numeric version number. The resulting release will be in the format `@`. +On Android, iOS and Mac Catalyst, if no version is found, the SDK uses the app package's ID, version and build number, in the format `@+`. + +On Android, these values are the package name, `versionName` and `versionCode`. On iOS and Mac Catalyst, they're `CFBundleIdentifier`, `CFBundleShortVersionString` and `CFBundleVersion`. The `ApplicationId`, `ApplicationDisplayVersion` and `ApplicationVersion` properties in your project file set them. + + + +In earlier versions, the release from the app package took precedence over `SENTRY_RELEASE`. + + + +On other platforms, if no version is found, the SDK will look at the [entry assembly's](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getentryassembly) `AssemblyInformationalVersionAttribute`, which accepts a string value and is often used to set a GIT commit hash. If that returns null, then the SDK will look at the default `AssemblyVersionAttribute`, which accepts the numeric version number. The resulting release will be in the format `@`. An `AssemblyInformationalVersionAttribute` is included automatically in SDK-style projects with a default value of `"1.0.0.0"`. You can set the `Version` property in your project file to override this value or [disable it entirely](https://learn.microsoft.com/en-us/dotnet/standard/assembly/set-attributes-project-file#use-package-properties-as-assembly-attributes) by setting the `GenerateAssemblyInformationalVersionAttribute` property to `false`. diff --git a/platform-includes/set-release/dotnet.nlog.mdx b/platform-includes/set-release/dotnet.nlog.mdx deleted file mode 100644 index 7972d4f355bd3..0000000000000 --- a/platform-includes/set-release/dotnet.nlog.mdx +++ /dev/null @@ -1,46 +0,0 @@ - - -For more information on how to dynamically set event data via `NLog.config`, see NLog's [layout renderer documentation](https://nlog-project.org/config/?tab=layout-renderers). - - - - -```xml {tabTitle:NLog.config} - - - - - - - - - - - - - - -``` - -```csharp -// Add this to the SDK initialization callback -options.Release = "my-project-name@2.3.12"; -``` - -```fsharp -// Add this to the SDK initialization callback -options.Release <- "my-project-name@2.3.12" -``` - -The SDK attempts to locate the release to add to events sent to Sentry. - -The SDK will first look at the [entry assembly's]() `AssemblyInformationalVersionAttribute`, which accepts a string as -value and is often used to set a GIT commit hash. - -If that returns null, it'll look at the default `AssemblyVersionAttribute` which accepts the numeric version number. diff --git a/platform-includes/set-release/unity.mdx b/platform-includes/set-release/unity.mdx index 61ece839244ee..c5046233cab66 100644 --- a/platform-includes/set-release/unity.mdx +++ b/platform-includes/set-release/unity.mdx @@ -1,7 +1,7 @@ ```csharp using Sentry.Unity; -SentryUnity.Init(o => +SentrySdk.Init(o => { o.Release = "my-project-name@2.3.12"; }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be0bb14b16151..9a9cb9e5ffe10 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -102,12 +102,18 @@ importers: '@sentry-internal/global-search': specifier: ^1.3.0 version: 1.3.0(react-dom@19.2.4(react@19.2.4))(react@19.2.4) + '@sentry/api': + specifier: 2.7.0 + version: 2.7.0(typescript@5.9.3) '@sentry/browser': - specifier: 11.6.0 - version: 11.6.0 + specifier: 11.12.0 + version: 11.12.0 + '@sentry/conventions': + specifier: ^0.33.0 + version: 0.33.0 '@sentry/nextjs': - specifier: 11.6.0 - version: 11.6.0(@babel/core@7.29.7)(next@15.5.24(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@22.19.11)(babel-plugin-macros@3.1.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(sass@1.98.0))(react@19.2.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23)) + specifier: 11.12.0 + version: 11.12.0(next@15.5.24(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@22.19.11)(babel-plugin-macros@3.1.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(sass@1.98.0))(react@19.2.4)(vite@7.3.5(@types/node@22.19.11)(jiti@1.21.7)(sass@1.98.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.0))(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23)) '@types/mdx': specifier: ^2.0.9 version: 2.0.13 @@ -298,9 +304,6 @@ importers: '@babel/preset-typescript': specifier: ^7.15.0 version: 7.28.5(@babel/core@7.29.7) - '@codecov/nextjs-webpack-plugin': - specifier: ^1.9.0 - version: 1.9.1(next@15.5.24(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@22.19.11)(babel-plugin-macros@3.1.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(sass@1.98.0))(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23)) '@eslint/js': specifier: ^9.26.0 version: 9.39.4 @@ -412,21 +415,6 @@ importers: packages: - '@actions/core@1.11.1': - resolution: {integrity: sha512-hXJCSrkwfA46Vd9Z3q4cpEpHB1rL5NG04+/rbqW9d3+CSvtB1tYe8UTpAlixa1vj0m/ULglfEK2UKxMGxCxv5A==} - - '@actions/exec@1.1.1': - resolution: {integrity: sha512-+sCcHHbVdk93a0XT19ECtO/gIXoxvdsgQLzb2fE2/5sIZmWQuluYyjPQtrtTHdU1YzTZ7bAPN4sITq2xi1679w==} - - '@actions/github@6.0.1': - resolution: {integrity: sha512-xbZVcaqD4XnQAe35qSQqskb3SqIAfRyLBrHMd/8TuL7hJSz2QtbDwnNM8zWx4zO5l2fnGtseNE3MbEvD7BxVMw==} - - '@actions/http-client@2.2.3': - resolution: {integrity: sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==} - - '@actions/io@1.1.3': - resolution: {integrity: sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q==} - '@algolia/cache-browser-local-storage@4.26.0': resolution: {integrity: sha512-z5oJK50poA6TujwqRCMcevZC3CjqhjAv3mOXde6bZVMroe1PqYuKXbN/bSUTZRAMtKkMJLeVt/WXkneTThRQRA==} @@ -925,23 +913,6 @@ packages: '@chevrotain/types@11.1.2': resolution: {integrity: sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==} - '@codecov/bundler-plugin-core@1.9.1': - resolution: {integrity: sha512-dt3ic7gMswz4p/qdkYPVJwXlLiLsz55rBBn2I7mr0HTG8pCoLRqnANJIwo5WrqGBZgPyVSMPBqBra6VxLWfDyA==} - engines: {node: '>=18.0.0'} - - '@codecov/nextjs-webpack-plugin@1.9.1': - resolution: {integrity: sha512-putRt+22vw+CVtigzVMpTl3B96MxZNC1IkTm5OmZujY4HY/tZt9Qn55rOoa0xQsV4ur3nNN1uiIoPGmJn4ZvVQ==} - engines: {node: '>=18.0.0'} - peerDependencies: - next: 14.x || 15.x - webpack: 5.x - - '@codecov/webpack-plugin@1.9.1': - resolution: {integrity: sha512-isyETXPJfhuG+UOteElc1X/IHpBG0dZNAa7loquA9N6lcu4szwNkwHvLdnMJ49kjVwcIpZBjUD2eZPhneBcDYQ==} - engines: {node: '>=18.0.0'} - peerDependencies: - webpack: 5.x - '@cspotcode/source-map-support@0.8.1': resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} @@ -1786,54 +1757,6 @@ packages: resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} engines: {node: '>= 8'} - '@octokit/auth-token@4.0.0': - resolution: {integrity: sha512-tY/msAuJo6ARbK6SPIxZrPBms3xPbfwBrulZe0Wtr/DIY9lje2HeV1uoebShn6mx7SjCHif6EjMvoREj+gZ+SA==} - engines: {node: '>= 18'} - - '@octokit/core@5.2.2': - resolution: {integrity: sha512-/g2d4sW9nUDJOMz3mabVQvOGhVa4e/BN/Um7yca9Bb2XTzPPnfTWHWQg+IsEYO7M3Vx+EXvaM/I2pJWIMun1bg==} - engines: {node: '>= 18'} - - '@octokit/endpoint@9.0.6': - resolution: {integrity: sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==} - engines: {node: '>= 18'} - - '@octokit/graphql@7.1.1': - resolution: {integrity: sha512-3mkDltSfcDUoa176nlGoA32RGjeWjl3K7F/BwHwRMJUW/IteSa4bnSV8p2ThNkcIcZU2umkZWxwETSSCJf2Q7g==} - engines: {node: '>= 18'} - - '@octokit/openapi-types@20.0.0': - resolution: {integrity: sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==} - - '@octokit/openapi-types@24.2.0': - resolution: {integrity: sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg==} - - '@octokit/plugin-paginate-rest@9.2.2': - resolution: {integrity: sha512-u3KYkGF7GcZnSD/3UP0S7K5XUFT2FkOQdcfXZGZQPGv3lm4F2Xbf71lvjldr8c1H3nNbF+33cLEkWYbokGWqiQ==} - engines: {node: '>= 18'} - peerDependencies: - '@octokit/core': '5' - - '@octokit/plugin-rest-endpoint-methods@10.4.1': - resolution: {integrity: sha512-xV1b+ceKV9KytQe3zCVqjg+8GTGfDYwaT1ATU5isiUyVtlVAO3HNdzpS4sr4GBx4hxQ46s7ITtZrAsxG22+rVg==} - engines: {node: '>= 18'} - peerDependencies: - '@octokit/core': '5' - - '@octokit/request-error@5.1.1': - resolution: {integrity: sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==} - engines: {node: '>= 18'} - - '@octokit/request@8.4.1': - resolution: {integrity: sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==} - engines: {node: '>= 18'} - - '@octokit/types@12.6.0': - resolution: {integrity: sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==} - - '@octokit/types@13.10.0': - resolution: {integrity: sha512-ifLaO34EbbPj0Xgro4G5lP5asESjwHracYJvVaPIyXMuiuXLlhic3S47cBdTb+jfODkTE5YtGCLt3Ay3+J97sA==} - '@opentelemetry/api@1.9.1': resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==} engines: {node: '>=8.0.0'} @@ -3076,71 +2999,90 @@ packages: react: '>=16' react-dom: '>=16' - '@sentry/browser-utils@11.6.0': - resolution: {integrity: sha512-s4zuuE71NORfyNd6ciS27/o97qgfu70qDRdPCkLK8UOcs1REsaAQPgmvNBSADRYm4eeFwWejKBCQKjL5kOzLqw==} + '@sentry/api@2.7.0': + resolution: {integrity: sha512-+h97u3e/VT66jWjgEHL4j7ooOikotjOPMgYAUiFuO4C+E3xCtCysGgtv0niZnPYWCQQygLDr6o9ecCzPCNF8Mw==} + engines: {node: '>=22'} + peerDependencies: + typescript: '*' + valibot: '*' + zod: ^4.6.6 + peerDependenciesMeta: + typescript: + optional: true + valibot: + optional: true + zod: + optional: true + + '@sentry/browser-utils@11.12.0': + resolution: {integrity: sha512-OttAHqf557R1gfLQRqb/dpGUK1UQd21qkeeN0KA/ThuymYXTNY+qTpJIOqmzgpk6fOmE922mTT6xmnMEiGYZBQ==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} - '@sentry/browser@11.6.0': - resolution: {integrity: sha512-zkqUIbRc9HCBMsoL67HOAr6PSfNzJSMw4JhytCHuDZ5O7KuOwwgBENGhVh3mr5lj2D47Bhv01MpwCJMP3yBnZQ==} + '@sentry/browser@11.12.0': + resolution: {integrity: sha512-oiSs0ZZQGVLVLASxTk/Z+MW4cGOHhC65IKc3B//M54eaZEa4p6JqP2DM++ta4IqDQx8+lSD6+TglAIsHBdSyVQ==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} - '@sentry/bundler-plugins@11.6.0': - resolution: {integrity: sha512-qHKQgOQaayRuwDCWWoAkEMkJe13RZwrpAH5Y5edL3d5XD2Gd7uenA6lPdXFw3qP1slezeSYErV0GAdcVYMo8fg==} + '@sentry/bundler-plugins@11.12.0': + resolution: {integrity: sha512-7vBXoHMoYKjYu08anYv5I0nplSWOfQyl7BqV0VOrLxEtGoOpk1+DxL2dyBiaWoAtISkaqJEV/ft813OsCGuuMg==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} peerDependencies: - '@babel/core': ^7.18.5 rollup: ^4.59.0 webpack: '>=5.1.0' peerDependenciesMeta: - '@babel/core': - optional: true rollup: optional: true webpack: optional: true - '@sentry/cloudflare@11.6.0': - resolution: {integrity: sha512-FOwluoZmgE60JLxQBKUw0smiz3FaVsmtuvslkgLb+9pUbxGsjnLf1RX8F99vPSCB724Q916asImCHTlWRynUSQ==} + '@sentry/cloudflare@11.12.0': + resolution: {integrity: sha512-m/nls+rx8NTCfxqgIMsw57lit5Rbo8VKbbrGDEZF65qsG12uV7wORDrUV6PnGi/MCjXx1Cc+tfdc90ljAlamwQ==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} peerDependencies: '@cloudflare/workers-types': ^4.x || ^5.x + vite: ^7.3.5 wrangler: ^4.x peerDependenciesMeta: '@cloudflare/workers-types': optional: true + vite: + optional: true wrangler: optional: true - '@sentry/conventions@0.26.0': - resolution: {integrity: sha512-ttSRcoLf2kIENDIFzH12aJaVMdxnidMYLvVNwEX/JjXfXaQot8u5M47QmgAFOOhVJ4nQ2uU8wTCh+fwSPrrCfg==} + '@sentry/conventions@0.32.0': + resolution: {integrity: sha512-WkSQcDhUUsz1SwxR23LpmyPKba+dgxxiH0DWV4VSM9yaAvhhl87ppW2Ts3g4piIKCVflc31aJeWy+biUbYfsMQ==} + engines: {node: '>=14'} + + '@sentry/conventions@0.33.0': + resolution: {integrity: sha512-5aa3g/VOnMoL8yHbfkYIWBYC3BLgMudgRNBTKNMrcMEj1mE9aKIt/CYCG7sasijhiSU4nTcSEzyM2voIVzLCng==} engines: {node: '>=14'} - '@sentry/core@11.6.0': - resolution: {integrity: sha512-PbITT1kfJYKJiS9fH4ZtOcwIONKyt+tUsTZSPtcAjPdkUDOzMKT61MkUa1Ze07VzNtLALT24ZdUOc6d9K4YoKA==} + '@sentry/core@11.12.0': + resolution: {integrity: sha512-HKER7EcRpPPgC8mLRe5BzP6njfRYFZ53BFLZxVp1whWbY6lp/b2mvTBk4q6+rKsUFhLhRDsd6jL8y/8ddEWv6A==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} - '@sentry/feedback@11.6.0': - resolution: {integrity: sha512-V52/+SkMcPdlldExPC9TWS2sZ+CC+8BSzvVbRtkQxvy+jTOXFAJfInaVLPAAVt8W4WbPw9iAxVMzwHGaZ2muBw==} + '@sentry/feedback@11.12.0': + resolution: {integrity: sha512-vYOIeby3tVoKZ/q70D1NJ48D4APMVcojyvCjlaZkFOQR6DIEsOjF/uC9MkhnCP3cpa4oADdMatsIpkhlPM+qng==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} - '@sentry/nextjs@11.6.0': - resolution: {integrity: sha512-M2dzWC4f/irc1PKVyo/2HRc6cdXiGriHns1HGxWtkwtUmIIhvPEvEuvFTYCyFxNjKZY2fYMtU33rhwvKDUW0AA==} + '@sentry/nextjs@11.12.0': + resolution: {integrity: sha512-IFmUbw8J+hrJTN3SoFG+CilZ8kMiRpA7G2Or8frCER3kfB+ZxkYJdYf0PJf/OMd0xKmSyfAozcqXJAfkEXIHIw==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} peerDependencies: next: ^14.0 || ^15.0.0-rc.0 || ^16.0.0-0 - '@sentry/node@11.6.0': - resolution: {integrity: sha512-5uHdUSACyodmtar+LxhFl4/MdICJ1/38mrp5lrMpDKfWSV/7tu/KRmr5gD2J9Nm47I/xxbghSz+oinJ4EtJatQ==} + '@sentry/node@11.12.0': + resolution: {integrity: sha512-MNSZDOd92Twrq5Z4ZAkxZdIfhr3YGytFb1T+vh5bNXVHkqByWpI/P2VtTSrzBR4Pi1IDRMz0i8t/OWNOsuAuBg==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} - '@sentry/opentelemetry@11.6.0': - resolution: {integrity: sha512-W6b+/8TVejHSCSOWMGsU2wVQY+d7FH/kI2zIFYXmIcxJCd7A/ULhOXe29UYeh+VX9wObR23LvEcEUmgsFVqf6A==} + '@sentry/opentelemetry@11.12.0': + resolution: {integrity: sha512-oWJwUdc2OSSvyOPXn/E1nWkC3GV5KNTWfR5prbw/0XxlKJepdlBsW19y+FAE9n3QznZ52aMZmetWEAFMsPJ0KQ==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} peerDependencies: '@opentelemetry/api': ^1.9.0 - '@sentry/react@11.6.0': - resolution: {integrity: sha512-z9UScxzkfXjz7dGJW/or1ADiEStFPIsiv7u14vHonOPPFzQS3XClWafcS7AKc4g/9x6LUqGY4mMbHLC6Dfxq8A==} + '@sentry/react@11.12.0': + resolution: {integrity: sha512-tNr2yyfj//7Wrn0scoauR8D9FG93PWSRPQakWuvlVXGIXEAx/pwVkOjWYKUD1Xhyo8Hbvu5f6ddQ0+StsL3zyw==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} peerDependencies: react: 17.x || 18.x || 19.x @@ -3149,24 +3091,24 @@ packages: react-router: optional: true - '@sentry/replay-canvas@11.6.0': - resolution: {integrity: sha512-cRuiC8N9xXDoaKEDpMPRDtmGAr0G2YMx1m2JrnrmTnMt9z/VcIKNwaiURTTW8W8u96/RyRQfflMHYARX7FG8YQ==} + '@sentry/replay-canvas@11.12.0': + resolution: {integrity: sha512-kx9Q3TY8pMp0b12fpcR0tziGoEW7Z8PpFKncmzD9XYWE3YzMt//B+cjkR+vmmZSUVxOuQATYDFp9c1jRTnbrug==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} - '@sentry/replay@11.6.0': - resolution: {integrity: sha512-cJyPYnF6QJA8ADRfAW06YoU7EVIebtWezBOCU9Vag5+W1VLBkXEvH7C4LbeMUiDmrqw92sumq06NgqipIxA7BA==} + '@sentry/replay@11.12.0': + resolution: {integrity: sha512-SF1064TKmOvIQTKo8WelVB34IZWtYtrflInsydPeB9jMTpy2iE3LqKRizDJr3YivjMUPDgIGn67b+0kaxiwQ4g==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} - '@sentry/server-runtime-injection@11.6.0': - resolution: {integrity: sha512-3plQzwQfvz4HJkXLDfr5VuQQL5vyjar7RKn7UwFne3jc+9OSXRkxkZ6S0Z3RdBgbaFO1GkFwf/mFNX4H8nNcuw==} + '@sentry/server-runtime-injection@11.12.0': + resolution: {integrity: sha512-fAZjCFyEfhvyfEdbav0/X13Yqbom5Ka1+hG0Nyl6bd7GxkQIWd68unSIw/Rvzfj/DSO8A1JidezST3D6omALkw==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} - '@sentry/server-utils@11.6.0': - resolution: {integrity: sha512-pVpGqwxBOXDMSngxTVARRlYyEXEfKA3WU1ENCdgLCeJ4xJ4vNRf4ODGXYPvXBk0zkt2NZZFvray2JHXIeYG+tg==} + '@sentry/server-utils@11.12.0': + resolution: {integrity: sha512-gAP5FLhXSiMs9vsU7guc54QNY1OzUJmhqyXMjhiP4SYlhQltoKtipcyo8pFWVsmylIzIkA8e2eGR6e0YA6YF3A==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} - '@sentry/vercel-edge@11.6.0': - resolution: {integrity: sha512-+yLRb6lqV7Rdi2zOoUGAk0sO752MDxFOU0eMGCtMkSrJWzJ4yV4wEpOeZb6WipAZb22pTkjyzN6j4sMpZS0SEQ==} + '@sentry/vercel-edge@11.12.0': + resolution: {integrity: sha512-+s+XyGtncoeQQd0f1hjdXbjIORcAt5IdhmcV1mz0vwBlyilfq3bB40bCg1j91g2L4xTlVmTm01X2ofGeKkZuew==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} '@sinclair/typebox@0.27.10': @@ -3313,6 +3255,9 @@ packages: '@smithy/smithy-client@4.12.7': resolution: {integrity: sha512-q3gqnwml60G44FECaEEsdQMplYhDMZYCtYhMCzadCnRnnHIobZJjegmdoUo6ieLQlPUzvrMdIJUpx6DoPmzANQ==} engines: {node: '>=18.0.0'} + deprecated: |- + Deprecated due to a bug in custom logger data redaction. Upgrade to the latest version. If you used a custom logger with + this version, review your logs and rotate any credentials or other secrets. See https://github.com/aws/aws-sdk-js-v3/issues/8393. '@smithy/types@4.13.1': resolution: {integrity: sha512-787F3yzE2UiJIQ+wYW1CVg2odHjmaWLGksnKQHUrK/lYZSEcy1msuLVvxaR/sI2/aDe9U+TBuLsXnr3vod1g0g==} @@ -4036,9 +3981,6 @@ packages: bcp-47@2.1.0: resolution: {integrity: sha512-9IIS3UPrvIa1Ej+lVDdDwO7zLehjqsaByECw0bu2RRGP73jALm6FYbzI5gWbgHLvNdkvfXB5YrSbocZdOS0c0w==} - before-after-hook@2.2.3: - resolution: {integrity: sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==} - bignumber.js@9.3.1: resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==} @@ -4506,9 +4448,6 @@ packages: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} - deprecation@2.3.1: - resolution: {integrity: sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==} - dequal@2.0.3: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} @@ -5050,8 +4989,8 @@ packages: glob-to-regexp@0.4.1: resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} - glob@13.0.6: - resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==} + glob@14.0.6: + resolution: {integrity: sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==} engines: {node: 18 || 20 || >=22} glob@7.2.3: @@ -5248,6 +5187,9 @@ packages: htmlparser2@4.1.0: resolution: {integrity: sha512-4zDq1a1zhE4gQso/c5LP1OtrhYTncXNSpvJYtWJBtXAETPlMfi3IFNjGuQbYLuVY4ZR0QMqRVvo4Pdy9KLyP8Q==} + http-cache-semantics@4.3.0: + resolution: {integrity: sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA==} + http-proxy-agent@5.0.0: resolution: {integrity: sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==} engines: {node: '>= 6'} @@ -6218,6 +6160,10 @@ packages: resolution: {integrity: sha512-kuUqqHNUqoIWp/c467RI4X6mmyuojY5jGutNU0wVTmEOOfcuwLqyMVoAi9MKi2Ak+5i9+nhmrK4ufZE8069kHA==} engines: {node: '>=18'} + p-limit@7.3.3: + resolution: {integrity: sha512-SKgVvDU5TNIxQ4r30U75BNLC6a+6GOEjngrk/ysM5+Zu3oJuk1SC5ApzIzY/7PjCEjoVPMWJ0zho/4QUiEB7TQ==} + engines: {node: '>=20'} + p-locate@4.1.0: resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==} engines: {node: '>=8'} @@ -6275,8 +6221,8 @@ packages: path-parse@1.0.7: resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} - path-scurry@2.0.2: - resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} + path-scurry@3.0.0: + resolution: {integrity: sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==} engines: {node: 18 || 20 || >=22} path-type@4.0.0: @@ -6813,8 +6759,8 @@ packages: engines: {node: '>=10'} hasBin: true - sentry@0.45.0: - resolution: {integrity: sha512-kgmEbLlC22lL7uneeUm9Sjz65rp5cvwYOMTxXbZCmBum4sbVre/lLT3zTV3kwXHJ9/BM8ZS0/GhZe9Cl1t6WyA==} + sentry@0.49.0: + resolution: {integrity: sha512-9tjS0jTx5FQzhwAGhpcnwvqE0MlQiwJtunsIUNqGkw6E9CBOMbijlamIDUqvZTDtJAveVwa9L5ziP44bOJUzcQ==} engines: {node: '>=20.0'} hasBin: true @@ -7234,10 +7180,6 @@ packages: engines: {node: '>=18.0.0'} hasBin: true - tunnel@0.0.6: - resolution: {integrity: sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==} - engines: {node: '>=0.6.11 <=0.7.0 || >=0.7.3'} - type-check@0.4.0: resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} engines: {node: '>= 0.8.0'} @@ -7287,10 +7229,6 @@ packages: undici-types@6.21.0: resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} - undici@6.27.0: - resolution: {integrity: sha512-YmfV3YnEDzXRC5lZ2jWtWWHKGUm1zIt8AhesR1tens+HTNv+YZlN/dp6G727LOvMJ8xjP9Be7Y2Sdr96LDm+pg==} - engines: {node: '>=18.17'} - unified@10.1.2: resolution: {integrity: sha512-pUSWAi/RAnVy1Pif2kAoeWNBa3JVrx0MId2LASj8G+7AiHWoKZNTomq6LG326T68U7/e263X6fTdcXIy7XnF7Q==} @@ -7345,17 +7283,10 @@ packages: unist-util-visit@5.1.0: resolution: {integrity: sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==} - universal-user-agent@6.0.1: - resolution: {integrity: sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ==} - universalify@0.2.0: resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==} engines: {node: '>= 4.0.0'} - unplugin@1.16.1: - resolution: {integrity: sha512-4/u/j4FrCKdi17jaxuJA0jClGxB1AvU2hw/IuayPc4ay1XGaJs/rbb4v5WKwAjNifjmXK9PIFyuPiaK8azyR9w==} - engines: {node: '>=14.0.0'} - update-browserslist-db@1.2.3: resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} hasBin: true @@ -7578,9 +7509,6 @@ packages: resolution: {integrity: sha512-jyuiGJdtvY434z5bUZrjz67v76/ePNvFZTp9Mdz29IlH4+GPsgyGjiv0fKI+M7BdkU6ADjulUcKAd3tUK3WlEw==} engines: {node: '>=10.13.0'} - webpack-virtual-modules@0.6.2: - resolution: {integrity: sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==} - webpack@5.105.2: resolution: {integrity: sha512-dRXm0a2qcHPUBEzVk8uph0xWSjV/xZxenQQbLwnwP7caQCYpqG1qddwlyEkIDkYn0K8tvmcrZ+bOrzoQ3HxCDw==} engines: {node: '>=10.13.0'} @@ -7710,40 +7638,11 @@ packages: resolution: {integrity: sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==} engines: {node: '>=12.20'} - zod@3.25.76: - resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} - zwitch@2.0.4: resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} snapshots: - '@actions/core@1.11.1': - dependencies: - '@actions/exec': 1.1.1 - '@actions/http-client': 2.2.3 - - '@actions/exec@1.1.1': - dependencies: - '@actions/io': 1.1.3 - - '@actions/github@6.0.1': - dependencies: - '@actions/http-client': 2.2.3 - '@octokit/core': 5.2.2 - '@octokit/plugin-paginate-rest': 9.2.2(@octokit/core@5.2.2) - '@octokit/plugin-rest-endpoint-methods': 10.4.1(@octokit/core@5.2.2) - '@octokit/request': 8.4.1 - '@octokit/request-error': 5.1.1 - undici: 6.27.0 - - '@actions/http-client@2.2.3': - dependencies: - tunnel: 0.0.6 - undici: 6.27.0 - - '@actions/io@1.1.3': {} - '@algolia/cache-browser-local-storage@4.26.0': dependencies: '@algolia/cache-common': 4.26.0 @@ -8621,29 +8520,6 @@ snapshots: '@chevrotain/types@11.1.2': {} - '@codecov/bundler-plugin-core@1.9.1': - dependencies: - '@actions/core': 1.11.1 - '@actions/github': 6.0.1 - chalk: 4.1.2 - semver: 7.8.5 - unplugin: 1.16.1 - zod: 3.25.76 - - '@codecov/nextjs-webpack-plugin@1.9.1(next@15.5.24(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@22.19.11)(babel-plugin-macros@3.1.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(sass@1.98.0))(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23))': - dependencies: - '@codecov/bundler-plugin-core': 1.9.1 - '@codecov/webpack-plugin': 1.9.1(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23)) - next: 15.5.24(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@22.19.11)(babel-plugin-macros@3.1.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(sass@1.98.0) - unplugin: 1.16.1 - webpack: 5.105.2(esbuild@0.28.1)(postcss@8.5.23) - - '@codecov/webpack-plugin@1.9.1(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23))': - dependencies: - '@codecov/bundler-plugin-core': 1.9.1 - unplugin: 1.16.1 - webpack: 5.105.2(esbuild@0.28.1)(postcss@8.5.23) - '@cspotcode/source-map-support@0.8.1': dependencies: '@jridgewell/trace-mapping': 0.3.9 @@ -9320,6 +9196,7 @@ snapshots: dependencies: '@jridgewell/gen-mapping': 0.3.13 '@jridgewell/trace-mapping': 0.3.31 + optional: true '@jridgewell/sourcemap-codec@1.6.0': {} @@ -9440,64 +9317,6 @@ snapshots: '@nodelib/fs.scandir': 2.1.5 fastq: 1.20.1 - '@octokit/auth-token@4.0.0': {} - - '@octokit/core@5.2.2': - dependencies: - '@octokit/auth-token': 4.0.0 - '@octokit/graphql': 7.1.1 - '@octokit/request': 8.4.1 - '@octokit/request-error': 5.1.1 - '@octokit/types': 13.10.0 - before-after-hook: 2.2.3 - universal-user-agent: 6.0.1 - - '@octokit/endpoint@9.0.6': - dependencies: - '@octokit/types': 13.10.0 - universal-user-agent: 6.0.1 - - '@octokit/graphql@7.1.1': - dependencies: - '@octokit/request': 8.4.1 - '@octokit/types': 13.10.0 - universal-user-agent: 6.0.1 - - '@octokit/openapi-types@20.0.0': {} - - '@octokit/openapi-types@24.2.0': {} - - '@octokit/plugin-paginate-rest@9.2.2(@octokit/core@5.2.2)': - dependencies: - '@octokit/core': 5.2.2 - '@octokit/types': 12.6.0 - - '@octokit/plugin-rest-endpoint-methods@10.4.1(@octokit/core@5.2.2)': - dependencies: - '@octokit/core': 5.2.2 - '@octokit/types': 12.6.0 - - '@octokit/request-error@5.1.1': - dependencies: - '@octokit/types': 13.10.0 - deprecation: 2.3.1 - once: 1.4.0 - - '@octokit/request@8.4.1': - dependencies: - '@octokit/endpoint': 9.0.6 - '@octokit/request-error': 5.1.1 - '@octokit/types': 13.10.0 - universal-user-agent: 6.0.1 - - '@octokit/types@12.6.0': - dependencies: - '@octokit/openapi-types': 20.0.0 - - '@octokit/types@13.10.0': - dependencies: - '@octokit/openapi-types': 24.2.0 - '@opentelemetry/api@1.9.1': {} '@oxc-parser/binding-android-arm-eabi@0.152.0': @@ -10581,133 +10400,141 @@ snapshots: react-dom: 19.2.4(react@19.2.4) title-case: 3.0.3 - '@sentry/browser-utils@11.6.0': + '@sentry/api@2.7.0(typescript@5.9.3)': dependencies: - '@sentry/conventions': 0.26.0 - '@sentry/core': 11.6.0 + http-cache-semantics: 4.3.0 + p-limit: 7.3.3 + optionalDependencies: + typescript: 5.9.3 + + '@sentry/browser-utils@11.12.0': + dependencies: + '@sentry/conventions': 0.32.0 + '@sentry/core': 11.12.0 web-vitals: 6.2.3 - '@sentry/browser@11.6.0': + '@sentry/browser@11.12.0': dependencies: - '@sentry/browser-utils': 11.6.0 - '@sentry/conventions': 0.26.0 - '@sentry/core': 11.6.0 - '@sentry/feedback': 11.6.0 - '@sentry/replay': 11.6.0 - '@sentry/replay-canvas': 11.6.0 + '@sentry/browser-utils': 11.12.0 + '@sentry/conventions': 0.32.0 + '@sentry/core': 11.12.0 + '@sentry/feedback': 11.12.0 + '@sentry/replay': 11.12.0 + '@sentry/replay-canvas': 11.12.0 - '@sentry/bundler-plugins@11.6.0(@babel/core@7.29.7)(rollup@4.63.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23))': + '@sentry/bundler-plugins@11.12.0(rollup@4.63.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23))': dependencies: - '@sentry/core': 11.6.0 + '@sentry/core': 11.12.0 dotenv: 17.4.2 - glob: 13.0.6 + glob: 14.0.6 magic-string: 0.30.21 oxc-parser: 0.152.0 - sentry: 0.45.0 - supports-color: 8.1.1 + sentry: 0.49.0 optionalDependencies: - '@babel/core': 7.29.7 rollup: 4.63.4 webpack: 5.105.2(esbuild@0.28.1)(postcss@8.5.23) - '@sentry/cloudflare@11.6.0': + '@sentry/cloudflare@11.12.0(vite@7.3.5(@types/node@22.19.11)(jiti@1.21.7)(sass@1.98.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.0))': dependencies: '@opentelemetry/api': 1.9.1 - '@sentry/conventions': 0.26.0 - '@sentry/core': 11.6.0 - '@sentry/opentelemetry': 11.6.0(@opentelemetry/api@1.9.1) - '@sentry/server-utils': 11.6.0 + '@sentry/conventions': 0.32.0 + '@sentry/core': 11.12.0 + '@sentry/opentelemetry': 11.12.0(@opentelemetry/api@1.9.1) + '@sentry/server-utils': 11.12.0 magic-string: 0.30.21 + optionalDependencies: + vite: 7.3.5(@types/node@22.19.11)(jiti@1.21.7)(sass@1.98.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.0) + + '@sentry/conventions@0.32.0': {} - '@sentry/conventions@0.26.0': {} + '@sentry/conventions@0.33.0': {} - '@sentry/core@11.6.0': + '@sentry/core@11.12.0': dependencies: - '@sentry/conventions': 0.26.0 + '@sentry/conventions': 0.32.0 - '@sentry/feedback@11.6.0': + '@sentry/feedback@11.12.0': dependencies: - '@sentry/core': 11.6.0 + '@sentry/core': 11.12.0 - '@sentry/nextjs@11.6.0(@babel/core@7.29.7)(next@15.5.24(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@22.19.11)(babel-plugin-macros@3.1.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(sass@1.98.0))(react@19.2.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23))': + '@sentry/nextjs@11.12.0(next@15.5.24(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@22.19.11)(babel-plugin-macros@3.1.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(sass@1.98.0))(react@19.2.4)(vite@7.3.5(@types/node@22.19.11)(jiti@1.21.7)(sass@1.98.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.0))(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23))': dependencies: '@opentelemetry/api': 1.9.1 '@rollup/plugin-commonjs': 28.0.1(rollup@4.63.4) - '@sentry/browser-utils': 11.6.0 - '@sentry/bundler-plugins': 11.6.0(@babel/core@7.29.7)(rollup@4.63.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23)) - '@sentry/cloudflare': 11.6.0 - '@sentry/conventions': 0.26.0 - '@sentry/core': 11.6.0 - '@sentry/node': 11.6.0(@babel/core@7.29.7)(rollup@4.63.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23)) - '@sentry/opentelemetry': 11.6.0(@opentelemetry/api@1.9.1) - '@sentry/react': 11.6.0(react@19.2.4) - '@sentry/server-runtime-injection': 11.6.0 - '@sentry/server-utils': 11.6.0 - '@sentry/vercel-edge': 11.6.0 + '@sentry/browser-utils': 11.12.0 + '@sentry/bundler-plugins': 11.12.0(rollup@4.63.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23)) + '@sentry/cloudflare': 11.12.0(vite@7.3.5(@types/node@22.19.11)(jiti@1.21.7)(sass@1.98.0)(terser@5.51.2)(tsx@4.22.0)(yaml@2.9.0)) + '@sentry/conventions': 0.32.0 + '@sentry/core': 11.12.0 + '@sentry/node': 11.12.0(rollup@4.63.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23)) + '@sentry/opentelemetry': 11.12.0(@opentelemetry/api@1.9.1) + '@sentry/react': 11.12.0(react@19.2.4) + '@sentry/server-runtime-injection': 11.12.0 + '@sentry/server-utils': 11.12.0 + '@sentry/vercel-edge': 11.12.0 next: 15.5.24(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@22.19.11)(babel-plugin-macros@3.1.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(sass@1.98.0) rollup: 4.63.4 stacktrace-parser: 0.1.11 transitivePeerDependencies: - - '@babel/core' - '@cloudflare/workers-types' - react - react-router + - vite - webpack - wrangler - '@sentry/node@11.6.0(@babel/core@7.29.7)(rollup@4.63.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23))': + '@sentry/node@11.12.0(rollup@4.63.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23))': dependencies: '@opentelemetry/api': 1.9.1 - '@sentry/bundler-plugins': 11.6.0(@babel/core@7.29.7)(rollup@4.63.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23)) - '@sentry/conventions': 0.26.0 - '@sentry/core': 11.6.0 - '@sentry/opentelemetry': 11.6.0(@opentelemetry/api@1.9.1) - '@sentry/server-runtime-injection': 11.6.0 - '@sentry/server-utils': 11.6.0 + '@sentry/bundler-plugins': 11.12.0(rollup@4.63.4)(webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23)) + '@sentry/conventions': 0.32.0 + '@sentry/core': 11.12.0 + '@sentry/opentelemetry': 11.12.0(@opentelemetry/api@1.9.1) + '@sentry/server-runtime-injection': 11.12.0 + '@sentry/server-utils': 11.12.0 transitivePeerDependencies: - - '@babel/core' - rollup - webpack - '@sentry/opentelemetry@11.6.0(@opentelemetry/api@1.9.1)': + '@sentry/opentelemetry@11.12.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 - '@sentry/conventions': 0.26.0 - '@sentry/core': 11.6.0 + '@sentry/conventions': 0.32.0 + '@sentry/core': 11.12.0 - '@sentry/react@11.6.0(react@19.2.4)': + '@sentry/react@11.12.0(react@19.2.4)': dependencies: - '@sentry/browser': 11.6.0 - '@sentry/conventions': 0.26.0 - '@sentry/core': 11.6.0 + '@sentry/browser': 11.12.0 + '@sentry/conventions': 0.32.0 + '@sentry/core': 11.12.0 react: 19.2.4 - '@sentry/replay-canvas@11.6.0': + '@sentry/replay-canvas@11.12.0': dependencies: - '@sentry/core': 11.6.0 - '@sentry/replay': 11.6.0 + '@sentry/core': 11.12.0 + '@sentry/replay': 11.12.0 - '@sentry/replay@11.6.0': + '@sentry/replay@11.12.0': dependencies: - '@sentry/browser-utils': 11.6.0 - '@sentry/core': 11.6.0 + '@sentry/browser-utils': 11.12.0 + '@sentry/core': 11.12.0 - '@sentry/server-runtime-injection@11.6.0': + '@sentry/server-runtime-injection@11.12.0': dependencies: - '@sentry/core': 11.6.0 - '@sentry/server-utils': 11.6.0 + '@sentry/core': 11.12.0 + '@sentry/server-utils': 11.12.0 - '@sentry/server-utils@11.6.0': + '@sentry/server-utils@11.12.0': dependencies: '@opentelemetry/api': 1.9.1 - '@sentry/conventions': 0.26.0 - '@sentry/core': 11.6.0 + '@sentry/conventions': 0.32.0 + '@sentry/core': 11.12.0 - '@sentry/vercel-edge@11.6.0': + '@sentry/vercel-edge@11.12.0': dependencies: '@opentelemetry/api': 1.9.1 - '@sentry/core': 11.6.0 - '@sentry/server-utils': 11.6.0 + '@sentry/core': 11.12.0 + '@sentry/server-utils': 11.12.0 '@sinclair/typebox@0.27.10': {} @@ -11239,11 +11066,13 @@ snapshots: dependencies: '@types/eslint': 9.6.1 '@types/estree': 1.0.9 + optional: true '@types/eslint@9.6.1': dependencies: '@types/estree': 1.0.9 '@types/json-schema': 7.0.15 + optional: true '@types/estree-jsx@1.0.5': dependencies: @@ -11495,20 +11324,26 @@ snapshots: dependencies: '@webassemblyjs/helper-numbers': 1.13.2 '@webassemblyjs/helper-wasm-bytecode': 1.13.2 + optional: true - '@webassemblyjs/floating-point-hex-parser@1.13.2': {} + '@webassemblyjs/floating-point-hex-parser@1.13.2': + optional: true - '@webassemblyjs/helper-api-error@1.13.2': {} + '@webassemblyjs/helper-api-error@1.13.2': + optional: true - '@webassemblyjs/helper-buffer@1.14.1': {} + '@webassemblyjs/helper-buffer@1.14.1': + optional: true '@webassemblyjs/helper-numbers@1.13.2': dependencies: '@webassemblyjs/floating-point-hex-parser': 1.13.2 '@webassemblyjs/helper-api-error': 1.13.2 '@xtuc/long': 4.2.2 + optional: true - '@webassemblyjs/helper-wasm-bytecode@1.13.2': {} + '@webassemblyjs/helper-wasm-bytecode@1.13.2': + optional: true '@webassemblyjs/helper-wasm-section@1.14.1': dependencies: @@ -11516,16 +11351,20 @@ snapshots: '@webassemblyjs/helper-buffer': 1.14.1 '@webassemblyjs/helper-wasm-bytecode': 1.13.2 '@webassemblyjs/wasm-gen': 1.14.1 + optional: true '@webassemblyjs/ieee754@1.13.2': dependencies: '@xtuc/ieee754': 1.2.0 + optional: true '@webassemblyjs/leb128@1.13.2': dependencies: '@xtuc/long': 4.2.2 + optional: true - '@webassemblyjs/utf8@1.13.2': {} + '@webassemblyjs/utf8@1.13.2': + optional: true '@webassemblyjs/wasm-edit@1.14.1': dependencies: @@ -11537,6 +11376,7 @@ snapshots: '@webassemblyjs/wasm-opt': 1.14.1 '@webassemblyjs/wasm-parser': 1.14.1 '@webassemblyjs/wast-printer': 1.14.1 + optional: true '@webassemblyjs/wasm-gen@1.14.1': dependencies: @@ -11545,6 +11385,7 @@ snapshots: '@webassemblyjs/ieee754': 1.13.2 '@webassemblyjs/leb128': 1.13.2 '@webassemblyjs/utf8': 1.13.2 + optional: true '@webassemblyjs/wasm-opt@1.14.1': dependencies: @@ -11552,6 +11393,7 @@ snapshots: '@webassemblyjs/helper-buffer': 1.14.1 '@webassemblyjs/wasm-gen': 1.14.1 '@webassemblyjs/wasm-parser': 1.14.1 + optional: true '@webassemblyjs/wasm-parser@1.14.1': dependencies: @@ -11561,19 +11403,23 @@ snapshots: '@webassemblyjs/ieee754': 1.13.2 '@webassemblyjs/leb128': 1.13.2 '@webassemblyjs/utf8': 1.13.2 + optional: true '@webassemblyjs/wast-printer@1.14.1': dependencies: '@webassemblyjs/ast': 1.14.1 '@xtuc/long': 4.2.2 + optional: true '@xml-tools/parser@1.0.11': dependencies: chevrotain: 7.1.1 - '@xtuc/ieee754@1.2.0': {} + '@xtuc/ieee754@1.2.0': + optional: true - '@xtuc/long@4.2.2': {} + '@xtuc/long@4.2.2': + optional: true abab@2.0.6: {} @@ -11589,6 +11435,7 @@ snapshots: acorn-import-phases@1.0.4(acorn@8.18.0): dependencies: acorn: 8.18.0 + optional: true acorn-jsx@5.3.2(acorn@8.15.0): dependencies: @@ -11606,7 +11453,8 @@ snapshots: acorn@8.16.0: {} - acorn@8.18.0: {} + acorn@8.18.0: + optional: true agent-base@6.0.2: dependencies: @@ -11619,11 +11467,13 @@ snapshots: ajv-formats@3.0.1(ajv@8.20.0): optionalDependencies: ajv: 8.20.0 + optional: true ajv-keywords@5.1.0(ajv@8.20.0): dependencies: ajv: 8.20.0 fast-deep-equal: 3.1.3 + optional: true ajv@6.14.0: dependencies: @@ -11638,6 +11488,7 @@ snapshots: fast-uri: 3.1.8 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 + optional: true algoliasearch@4.26.0: dependencies: @@ -11870,8 +11721,6 @@ snapshots: is-alphanumerical: 2.0.1 is-decimal: 2.0.1 - before-after-hook@2.2.3: {} - bignumber.js@9.3.1: {} binary-extensions@2.3.0: {} @@ -11980,7 +11829,8 @@ snapshots: dependencies: readdirp: 4.1.2 - chrome-trace-event@1.0.4: {} + chrome-trace-event@1.0.4: + optional: true ci-info@3.9.0: {} @@ -12018,7 +11868,8 @@ snapshots: comma-separated-tokens@2.0.3: {} - commander@2.20.3: {} + commander@2.20.3: + optional: true commander@4.1.1: {} @@ -12354,8 +12205,6 @@ snapshots: delayed-stream@1.0.0: {} - deprecation@2.3.1: {} - dequal@2.0.3: {} detect-libc@2.1.2: {} @@ -12463,6 +12312,7 @@ snapshots: dependencies: graceful-fs: 4.2.11 tapable: 2.3.3 + optional: true entities@2.2.0: {} @@ -12746,6 +12596,7 @@ snapshots: dependencies: esrecurse: 4.3.0 estraverse: 4.3.0 + optional: true eslint-scope@8.4.0: dependencies: @@ -12815,7 +12666,8 @@ snapshots: dependencies: estraverse: 5.3.0 - estraverse@4.3.0: {} + estraverse@4.3.0: + optional: true estraverse@5.3.0: {} @@ -12862,7 +12714,8 @@ snapshots: event-target-shim@5.0.1: {} - events@3.3.0: {} + events@3.3.0: + optional: true execa@5.1.1: dependencies: @@ -12916,7 +12769,8 @@ snapshots: fast-levenshtein@2.0.6: {} - fast-uri@3.1.8: {} + fast-uri@3.1.8: + optional: true fast-xml-builder@1.2.0: dependencies: @@ -13087,13 +12941,14 @@ snapshots: dependencies: is-glob: 4.0.3 - glob-to-regexp@0.4.1: {} + glob-to-regexp@0.4.1: + optional: true - glob@13.0.6: + glob@14.0.6: dependencies: minimatch: 9.0.9 minipass: 7.1.3 - path-scurry: 2.0.2 + path-scurry: 3.0.0 glob@7.2.3: dependencies: @@ -13438,6 +13293,8 @@ snapshots: domutils: 2.8.0 entities: 2.2.0 + http-cache-semantics@4.3.0: {} + http-proxy-agent@5.0.0: dependencies: '@tootallnate/once': 2.0.1 @@ -14016,6 +13873,7 @@ snapshots: '@types/node': 22.20.4 merge-stream: 2.0.0 supports-color: 8.1.1 + optional: true jest-worker@29.7.0: dependencies: @@ -14096,7 +13954,8 @@ snapshots: json-schema-traverse@0.4.1: {} - json-schema-traverse@1.0.0: {} + json-schema-traverse@1.0.0: + optional: true json-stable-stringify-without-jsonify@1.0.1: {} @@ -14153,7 +14012,8 @@ snapshots: lines-and-columns@1.2.4: {} - loader-runner@4.3.2: {} + loader-runner@4.3.2: + optional: true locate-path@5.0.0: dependencies: @@ -14741,7 +14601,8 @@ snapshots: natural-compare@1.4.0: {} - neo-async@2.6.2: {} + neo-async@2.6.2: + optional: true next-plausible@3.12.5(next@15.5.24(@babel/core@7.29.7)(@opentelemetry/api@1.9.1)(@types/node@22.19.11)(babel-plugin-macros@3.1.0)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(sass@1.98.0))(react-dom@19.2.4(react@19.2.4))(react@19.2.4): dependencies: @@ -14927,6 +14788,10 @@ snapshots: dependencies: yocto-queue: 1.2.2 + p-limit@7.3.3: + dependencies: + yocto-queue: 1.2.2 + p-locate@4.1.0: dependencies: p-limit: 2.3.0 @@ -14980,7 +14845,7 @@ snapshots: path-parse@1.0.7: {} - path-scurry@2.0.2: + path-scurry@3.0.0: dependencies: lru-cache: 11.5.3 minipass: 7.1.3 @@ -15640,7 +15505,8 @@ snapshots: require-directory@2.1.1: {} - require-from-string@2.0.2: {} + require-from-string@2.0.2: + optional: true requires-port@1.0.0: {} @@ -15812,6 +15678,7 @@ snapshots: ajv: 8.20.0 ajv-formats: 3.0.1(ajv@8.20.0) ajv-keywords: 5.1.0(ajv@8.20.0) + optional: true search-insights@2.17.3: {} @@ -15824,7 +15691,7 @@ snapshots: semver@7.8.5: {} - sentry@0.45.0: {} + sentry@0.49.0: {} server-only@0.0.1: {} @@ -15940,6 +15807,7 @@ snapshots: dependencies: buffer-from: 1.1.2 source-map: 0.6.1 + optional: true source-map@0.5.7: {} @@ -16135,7 +16003,8 @@ snapshots: - tsx - yaml - tapable@2.3.3: {} + tapable@2.3.3: + optional: true teeny-request@9.0.0: dependencies: @@ -16158,6 +16027,7 @@ snapshots: optionalDependencies: esbuild: 0.28.1 postcss: 8.5.23 + optional: true terser@5.51.2: dependencies: @@ -16165,6 +16035,7 @@ snapshots: acorn: 8.18.0 commander: 2.20.3 source-map-support: 0.5.21 + optional: true test-exclude@6.0.0: dependencies: @@ -16275,8 +16146,6 @@ snapshots: optionalDependencies: fsevents: 2.3.3 - tunnel@0.0.6: {} - type-check@0.4.0: dependencies: prelude-ls: 1.2.1 @@ -16333,8 +16202,6 @@ snapshots: undici-types@6.21.0: {} - undici@6.27.0: {} - unified@10.1.2: dependencies: '@types/unist': 2.0.11 @@ -16428,15 +16295,8 @@ snapshots: unist-util-is: 6.0.1 unist-util-visit-parents: 6.0.2 - universal-user-agent@6.0.1: {} - universalify@0.2.0: {} - unplugin@1.16.1: - dependencies: - acorn: 8.15.0 - webpack-virtual-modules: 0.6.2 - update-browserslist-db@1.2.3(browserslist@4.28.1): dependencies: browserslist: 4.28.1 @@ -16612,6 +16472,7 @@ snapshots: watchpack@2.5.2: dependencies: graceful-fs: 4.2.11 + optional: true web-namespaces@2.0.1: {} @@ -16621,9 +16482,8 @@ snapshots: webidl-conversions@7.0.0: {} - webpack-sources@3.5.1: {} - - webpack-virtual-modules@0.6.2: {} + webpack-sources@3.5.1: + optional: true webpack@5.105.2(esbuild@0.28.1)(postcss@8.5.23): dependencies: @@ -16665,6 +16525,7 @@ snapshots: - lightningcss - postcss - uglify-js + optional: true whatwg-encoding@2.0.0: dependencies: @@ -16783,6 +16644,4 @@ snapshots: yocto-queue@1.2.2: {} - zod@3.25.76: {} - zwitch@2.0.4: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000000000..a073cf5994cd3 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,6 @@ +# Settings only: this repo is a single package, so there is no `packages` list. +# scripts/bump-sentry-api.sh pins every new @sentry/api release within the hour. +# Exclude it from pnpm's minimumReleaseAge so those installs aren't held back +# once pnpm applies a release-age default. +minimumReleaseAgeExclude: + - '@sentry/api' diff --git a/public/img/tunnel-flow.svg b/public/img/tunnel-flow.svg new file mode 100644 index 0000000000000..b8885014ad173 --- /dev/null +++ b/public/img/tunnel-flow.svg @@ -0,0 +1 @@ +WITHOUT A TUNNELexample.comyour app in the browsersentry.ioSentry's ingestblocked by ad blockersWITH A TUNNELexample.comyour app in the browserexample.com/tunnelsame origin, forwards itsentry.ioSentry's ingest \ No newline at end of file diff --git a/redirects.js b/redirects.js index b047758e4359a..597821d1a0681 100644 --- a/redirects.js +++ b/redirects.js @@ -1046,7 +1046,38 @@ const userDocsRedirects = [ { // The Nuxt SDK links to this path in its Cloudflare build warning source: '/platforms/javascript/guides/nuxt/install/cloudflare-workers/', - destination: '/platforms/javascript/guides/cloudflare/frameworks/nuxt/', + destination: '/platforms/javascript/guides/nuxt/cloudflare/', + }, + // The Cloudflare quick starts of these frameworks moved from the Cloudflare guide into the framework guides. + { + source: + '/platforms/javascript/guides/cloudflare/frameworks/:framework(astro|hono|nextjs|nuxt|remix|sveltekit)/', + destination: '/platforms/javascript/guides/:framework/cloudflare/', + }, + { + source: '/platforms/javascript/guides/cloudflare/frameworks/tanstack-start/', + destination: '/platforms/javascript/guides/tanstackstart-react/cloudflare/', + }, + { + source: '/platforms/javascript/guides/remix/frameworks/', + destination: '/platforms/javascript/guides/remix/cloudflare/', + }, + { + source: '/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router/', + destination: '/platforms/javascript/guides/react-router/hydrogen/', + }, + { + source: '/platforms/javascript/guides/cloudflare/frameworks/hydrogen-remix/', + destination: '/platforms/javascript/guides/remix/hydrogen/', + }, + { + // The Cloudflare quick start links to every framework page. + source: '/platforms/javascript/guides/cloudflare/frameworks/', + destination: '/platforms/javascript/guides/cloudflare/', + }, + { + source: '/platforms/javascript/guides/nextjs/best-practices/deploying-on-cloudflare/', + destination: '/platforms/javascript/guides/nextjs/cloudflare/', }, { source: '/platforms/javascript/guides/connect/', @@ -1064,17 +1095,17 @@ const userDocsRedirects = [ { source: '/platforms/javascript/guides/express/install/lightweight/', destination: - '/platforms/javascript/guides/express/configuration/integrations/opentelemetry/', + '/platforms/javascript/guides/node/configuration/integrations/opentelemetry/', }, { source: '/platforms/javascript/guides/fastify/install/lightweight/', destination: - '/platforms/javascript/guides/fastify/configuration/integrations/opentelemetry/', + '/platforms/javascript/guides/node/configuration/integrations/opentelemetry/', }, { source: '/platforms/javascript/guides/hapi/install/lightweight/', destination: - '/platforms/javascript/guides/hapi/configuration/integrations/opentelemetry/', + '/platforms/javascript/guides/node/configuration/integrations/opentelemetry/', }, { source: '/platforms/javascript/guides/hono/install/lightweight/', @@ -1084,7 +1115,7 @@ const userDocsRedirects = [ { source: '/platforms/javascript/guides/koa/install/lightweight/', destination: - '/platforms/javascript/guides/koa/configuration/integrations/opentelemetry/', + '/platforms/javascript/guides/node/configuration/integrations/opentelemetry/', }, { source: @@ -1096,6 +1127,20 @@ const userDocsRedirects = [ '/platforms/javascript/guides/:guide(node|express|fastify|hapi|hono|koa|nestjs)/install/commonjs/', destination: '/platforms/javascript/guides/:guide/', }, + // Express, Fastify, Hapi and Koa are single landing pages, their subpages moved to Node.js. + { + source: '/platforms/javascript/guides/fastify/features/:path*', + destination: '/platforms/javascript/guides/node/configuration/integrations/fastify/', + }, + { + source: + '/platforms/javascript/guides/:guide(express|fastify|hapi|koa)__v:version/:path*', + destination: '/platforms/javascript/guides/node/', + }, + { + source: '/platforms/javascript/guides/:guide(express|fastify|hapi|koa)/:path+', + destination: '/platforms/javascript/guides/node/:path+/', + }, { source: '/platforms/javascript/guides/nestjs/install/esm-without-import/', destination: '/platforms/javascript/guides/nestjs/', @@ -2107,13 +2152,11 @@ const userDocsRedirects = [ }, { source: '/platforms/javascript/guides/remix/frameworks/hydrogen/', - destination: - '/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router/', + destination: '/platforms/javascript/guides/react-router/hydrogen/', }, { source: '/platforms/javascript/guides/cloudflare/frameworks/hydrogen/', - destination: - '/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router/', + destination: '/platforms/javascript/guides/react-router/hydrogen/', }, // Removed /product/onboarding/ section (content was orphaned and duplicated elsewhere) { diff --git a/scripts/bump-sentry-api.sh b/scripts/bump-sentry-api.sh new file mode 100755 index 0000000000000..0c5f6b0f80b5b --- /dev/null +++ b/scripts/bump-sentry-api.sh @@ -0,0 +1,69 @@ +#!/bin/sh +# Pin @sentry/api, which the API reference is built from, to its newest npm +# release, then open and merge a PR for it. +# +# Environment: +# GITHUB_TOKEN A token that can push branches and merge PRs. A GitHub +# App token, unlike github.token, also starts CI on the +# new PR. +# GITHUB_EVENT_NAME Set by GitHub Actions. getsentry/sentry dispatches this +# workflow right after it publishes a release, and npm can +# take a few minutes to serve it, so a dispatched run +# waits for a new version before it gives up. +set -eu + +package=@sentry/api +# A dispatched run checks npm up to this many times, this many seconds apart. +dispatch_attempts=20 +dispatch_delay=30 + +latest_version() { + version=$(timeout 60 npm view "$package" version) || return 1 + case $version in + '' | *[!0-9.]*) + echo "::error::Expected a release version of $package from npm, got: $version" >&2 + return 1 + ;; + esac + printf '%s\n' "$version" +} + +current=$(node -p 'require("./package.json").dependencies[process.argv[1]]' "$package") +attempts=1 +if [ "${GITHUB_EVENT_NAME:-}" = workflow_dispatch ]; then + attempts=$dispatch_attempts +fi +attempt=1 +while :; do + latest=$(latest_version) + if [ "$current" != "$latest" ]; then + break + fi + if [ "$attempt" -ge "$attempts" ]; then + echo "$package is already $latest, skipping." + exit 0 + fi + echo "npm still has $package $latest; checking again in ${dispatch_delay}s ($attempt of $attempts)." + attempt=$((attempt + 1)) + sleep "$dispatch_delay" +done +echo "Bumping $package from $current to $latest" + +timeout 600 pnpm add --save-exact --lockfile-only "$package@$latest" + +git config user.email "271575301+sentry-api-schema-updater[bot]@users.noreply.github.com" +git config user.name "sentry-api-schema-updater[bot]" + +# A run that stopped before the merge leaves this branch, and maybe its PR, +# behind. Overwrite the branch and reuse an open PR so the next run finishes. +branch="bot/bump-sentry-api-to-$latest" +git checkout -B "$branch" +git add package.json pnpm-lock.yaml +git commit -m "Bump $package to $latest" +timeout 120 git push --force --set-upstream origin "$branch" + +open_prs=$(timeout 60 gh pr list --head "$branch" --state open --json number --jq length) +if [ "$open_prs" = 0 ]; then + timeout 60 gh pr create --fill --head "$branch" +fi +timeout 120 gh pr merge "$branch" --squash --admin -d diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json index 58d3f2f750e90..c2564eca9b420 100644 --- a/scripts/tsconfig.json +++ b/scripts/tsconfig.json @@ -1,16 +1,18 @@ { // Used only when running scripts/algolia.ts via `tsx` (see .github/workflows/algolia-index.yml). // tsx loads .ts files through Node's CJS resolver. `rehype-prism-diff` (imported transitively - // via src/mdx.ts) only declares an "import" condition in its package.json `exports` map, so the - // CJS resolver fails with ERR_PACKAGE_PATH_NOT_EXPORTED. Aliasing the bare specifier to the - // package's real dist file makes tsx resolve it as a plain file and bypass the exports map. + // via src/mdx.ts) and `@sentry/api/docs` (via src/build/resolveOpenAPI.ts) only declare an + // "import" condition in their package.json `exports` maps, so the CJS resolver fails with + // ERR_PACKAGE_PATH_NOT_EXPORTED. Aliasing each bare specifier to the package's real dist file + // makes tsx resolve it as a plain file and bypass the exports map. // Bun (the previous runner) tolerated the import-only exports map; tsx does not. "extends": "../tsconfig.json", "compilerOptions": { "baseUrl": "..", "paths": { "sentry-docs/*": ["src/*"], - "rehype-prism-diff": ["node_modules/rehype-prism-diff/dist/index.js"] + "rehype-prism-diff": ["node_modules/rehype-prism-diff/dist/index.js"], + "@sentry/api/docs": ["node_modules/@sentry/api/dist/docs.js"] } } } diff --git a/src/build/open-api/types.ts b/src/build/open-api/types.ts deleted file mode 100644 index 20d07a6947d26..0000000000000 --- a/src/build/open-api/types.ts +++ /dev/null @@ -1,125 +0,0 @@ -export type RequestBodySchema = { - properties: { - [key: string]: {description: string; type: string}; - }; - required: string[]; - type: string; -}; - -export type Parameter = { - description: string; - in: string; - name: string; - required: boolean; - schema: { - enum: string[]; - format: string; - type: string; - items?: {[key: string]: unknown}; - }; - 'x-sentry-experimental'?: boolean; -}; - -type Markdown = { - childMdx: { - body: string; - }; -}; - -type Tag = { - description: string; - externalDocs: { - description: string; - url: string; - }; - name: string; - 'x-display-description': boolean; - 'x-sidebar-name': string; -}; - -type ServerMeta = { - description: string; - url: string; -}; - -export type DeRefedOpenAPI = { - paths: { - [key: string]: { - [key: string]: { - operationId: string; - parameters: Parameter[] | undefined; - requestBody: { - content: { - 'application/json': { - example: any; - schema: RequestBodySchema; - }; - }; - required: boolean; - }; - responses: { - [key: string]: { - content: { - 'application/json': { - example: any; - schema: any; - }; - }; - description: string; - }; - }; - summary: string; - tags: string[]; - description?: string; - security?: any; - servers?: ServerMeta[]; - 'x-sentry-experimental'?: boolean; - }; - }; - }; - tags: Tag[]; -}; - -export type ResponseContent = { - content_type: string; - example: string; - examples: string; - schema: string; -}; - -export type Response = { - content: ResponseContent | null; - description: string; - status_code: string; -}; - -export type RequestBody = { - content: { - content_type: string; - example: string; - schema: string; - }; - required: boolean; -}; - -export type OpenApiPath = { - apiPath: string; - description: string; - method: string; - operationId: string; - parameters: Parameter[]; - readableUrl: string; - requestBody: RequestBody | null; - responses: Response[]; - security: {[key: string]: string[]}[]; - summary: string | null; - tags: string[]; -}; - -export type OpenAPI = { - childOpenApiPathDescription: Markdown; - childrenOpenApiBodyParameter: (Parameter & Markdown)[]; - childrenOpenApiPathParameter: (Parameter & Markdown)[]; - id: string; - path: OpenApiPath; -}; diff --git a/src/build/resolveOpenAPI.ts b/src/build/resolveOpenAPI.ts index 1856093f7545c..b67cf8f847389 100644 --- a/src/build/resolveOpenAPI.ts +++ b/src/build/resolveOpenAPI.ts @@ -1,36 +1,38 @@ /* eslint import/no-nodejs-modules:0 */ +import { + API_BASE_PATH, + type ApiDocs, + type ApiDocsOperation, + type ApiDocsParameter, + extractDocs, + operations, + tags, +} from '@sentry/api/docs'; import {promises as fs} from 'fs'; -import {DeRefedOpenAPI, Parameter} from './open-api/types'; - -// SENTRY_API_SCHEMA_SHA is used in the sentry-docs GHA workflow in getsentry/sentry-api-schema. -// DO NOT change variable name unless you change it in the sentry-docs GHA workflow in getsentry/sentry-api-schema. -const SENTRY_API_SCHEMA_SHA = 'd3da6979e213d75071f154a31e671870ace17084'; - const activeEnv = process.env.GATSBY_ENV || process.env.NODE_ENV || 'development'; -async function resolveOpenAPI(): Promise { +// The API reference comes from the pinned `@sentry/api` version. In development, +// OPENAPI_LOCAL_PATH previews a local `make build-api-docs` spec instead. +async function resolveApiDocs(): Promise { if (activeEnv === 'development' && process.env.OPENAPI_LOCAL_PATH) { try { console.log(`Fetching from ${process.env.OPENAPI_LOCAL_PATH}`); const data = await fs.readFile(process.env.OPENAPI_LOCAL_PATH, 'utf8'); - return JSON.parse(data); + return extractDocs(JSON.parse(data)); } catch (error) { console.log( - `Failed to connect to ${process.env.OPENAPI_LOCAL_PATH}. Continuing to fetch versioned schema from GitHub. + `Failed to read ${process.env.OPENAPI_LOCAL_PATH}. Continuing with the API reference from @sentry/api. ${error}` ); } } - const response = await fetch( - `https://raw.githubusercontent.com/getsentry/sentry-api-schema/${SENTRY_API_SCHEMA_SHA}/openapi-derefed.json` - ); - return await response.json(); + return {apiBasePath: API_BASE_PATH, tags, operations}; } export type APIParameter = { - description: string; + description?: string; experimental: boolean; name: string; required: boolean; @@ -61,8 +63,6 @@ type APIResponse = { }; }; -type APIData = DeRefedOpenAPI['paths'][string][string]; - export type API = { apiPath: string; bodyParameters: APIParameter[]; @@ -78,7 +78,8 @@ export type API = { bodyContentType?: string; descriptionMarkdown?: string; requestBodyContent?: any; - security?: {[key: string]: string[]}; + /** Accepted security requirements: each maps a scheme to the scopes it needs. */ + security?: ApiDocsOperation['security']; summary?: string; }; @@ -145,76 +146,62 @@ export function apiCategories(): Promise { } async function apiCategoriesUncached(): Promise { - const data = await resolveOpenAPI(); + const data = await resolveApiDocs(); const categoryMap: {[name: string]: APICategory} = {}; data.tags.forEach(tag => { categoryMap[tag.name] = { - name: tag['x-sidebar-name'] || tag.name, + name: tag.sidebarName || tag.name, slug: slugify(tag.name), - description: tag['x-display-description'] ? tag.description : undefined, + description: tag.displayDescription ? tag.description : undefined, apis: [], }; }); - Object.entries(data.paths).forEach(([apiPath, methods]) => { - Object.entries(methods).forEach(([method, apiData]) => { - // Detect deprecation from either field independently — the (DEPRECATED) - // marker may sit on operationId even when a summary is present. - const isDeprecated = - isDeprecatedOperationId(apiData.operationId) || - isDeprecatedOperationId(apiData.summary); - const isExperimental = apiData['x-sentry-experimental'] === true; - const titleSource = apiData.summary || apiData.operationId || ''; - const cleanName = stripDeprecatedPrefix(titleSource); + data.operations.forEach(operation => { + // Detect deprecation from either field independently — the (DEPRECATED) + // marker may sit on operationId even when a summary is present. + const isDeprecated = + isDeprecatedOperationId(operation.operationId) || + isDeprecatedOperationId(operation.summary); + const isExperimental = operation.experimental; + const titleSource = operation.summary || operation.operationId || ''; + const cleanName = stripDeprecatedPrefix(titleSource); + const description = operation.description || undefined; - let server = 'https://sentry.io'; - if (apiData.servers && apiData.servers[0]) { - server = apiData.servers[0].url; - } - apiData.tags.forEach(tag => { - categoryMap[tag].apis.push({ - apiPath, - method, - name: cleanName, - deprecated: isDeprecated, - experimental: isExperimental, - server, - slug: slugify(cleanName), - summary: apiData.summary - ? stripDeprecatedPrefix(apiData.summary) - : apiData.summary, - descriptionMarkdown: isExperimental - ? apiData.description?.replace(EXPERIMENTAL_NOTICE_REGEX, '') - : apiData.description, - pathParameters: documentedParameters(apiData.parameters, 'path'), - queryParameters: documentedParameters(apiData.parameters, 'query'), - requestBodyContent: { - example: - apiData.requestBody?.content && - Object.values(apiData.requestBody.content)[0].example, - }, - bodyContentType: getBodyContentType(apiData), - bodyParameters: getBodyParameters(apiData), - security: apiData.security, - responses: Object.entries(apiData.responses) - .map(([status_code, response]) => ({ - status_code, - ...response, - })) - .map(response => { - const {content, ...rest} = response; - return { - content: - content && - Object.entries(content).map(([content_type, contentData]) => ({ - content_type, - ...contentData, - }))[0], - ...rest, - }; - }), - }); + operation.tags.forEach(tag => { + categoryMap[tag].apis.push({ + // Operation paths are relative to the spec's API base path, such as + // `/api/0`; pages show the full path after the origin. + apiPath: `${data.apiBasePath}${operation.path}`, + method: operation.method.toLowerCase(), + name: cleanName, + deprecated: isDeprecated, + experimental: isExperimental, + server: operation.servers[0] ?? 'https://sentry.io', + slug: slugify(cleanName), + summary: operation.summary + ? stripDeprecatedPrefix(operation.summary) + : operation.summary, + descriptionMarkdown: isExperimental + ? description?.replace(EXPERIMENTAL_NOTICE_REGEX, '') + : description, + pathParameters: documentedParameters(operation.parameters, 'path'), + queryParameters: documentedParameters(operation.parameters, 'query'), + requestBodyContent: {example: operation.requestBody?.example}, + bodyContentType: operation.requestBody?.contentType, + bodyParameters: getBodyParameters(operation), + // An operation without requirements has no Scopes section. + security: operation.security.length ? operation.security : undefined, + responses: operation.responses.map( + ({status, description: responseDescription, contentType, ...content}) => ({ + status_code: status, + description: responseDescription, + content: contentType + ? ({content_type: contentType, ...content} as APIResponse['content']) + : undefined, + }) + ), }); }); }); @@ -228,33 +215,31 @@ async function apiCategoriesUncached(): Promise { } function documentedParameters( - parameters: Parameter[] | undefined, + parameters: readonly ApiDocsParameter[], location: 'path' | 'query' ): APIParameter[] { - return (parameters || []) + return parameters .filter(param => param.in === location) - .map(param => { - const documented = toDocumentedParameter(param); - return { - name: documented.name, - description: documented.description, - required: documented.required, - experimental: documented.experimental, - // OpenAPI item schemas are an open record; the page only reads type and enum. - schema: documented.schema as APIParameter['schema'], - }; - }); + .map(param => ({ + name: param.name, + description: param.description, + required: param.required, + experimental: param.experimental, + // OpenAPI item schemas are an open record; the page only reads type and enum. + schema: param.schema as APIParameter['schema'], + })); } -function getBodyParameters(apiData: APIData): APIParameter[] { - const content = apiData.requestBody?.content; - const contentType = content && Object.values(content)[0]; - const properties = contentType?.schema?.properties; +function getBodyParameters(operation: ApiDocsOperation): APIParameter[] { + const schema = operation.requestBody?.schema as + | {properties?: {[name: string]: any}; required?: string[]} + | undefined; + const properties = schema?.properties; if (!properties) { return []; } - const required: string[] = contentType?.schema?.required || []; + const required: string[] = schema?.required || []; return Object.entries(properties).map(([name, props]: [string, any]) => toDocumentedParameter({ @@ -270,12 +255,3 @@ function getBodyParameters(apiData: APIData): APIParameter[] { }) ); } - -function getBodyContentType(apiData: APIData): string | undefined { - const content = apiData.requestBody?.content; - const types = content && Object.keys(content); - if (!types?.length) { - return undefined; - } - return types[0]; -} diff --git a/src/components/agentSetupCallout/index.tsx b/src/components/agentSetupCallout/index.tsx index 5c8043f2f412f..668e334cd4cf1 100644 --- a/src/components/agentSetupCallout/index.tsx +++ b/src/components/agentSetupCallout/index.tsx @@ -1,15 +1,15 @@ 'use client'; -import {ChevronDownIcon, ChevronRightIcon} from '@radix-ui/react-icons'; import * as Sentry from '@sentry/nextjs'; -import Link from 'next/link'; -import {useCallback, useState} from 'react'; +import {Fragment, useCallback, useState} from 'react'; import {Copy} from 'react-feather'; import {usePlausibleEvent} from 'sentry-docs/hooks/usePlausibleEvent'; import {DocMetrics} from 'sentry-docs/metrics'; -import {CodeBlock} from '../codeBlock'; -import {buildPrompt} from './shared'; +import {CliInstallCommand} from '../cliInstallCommand'; +import {ExternalLink} from '../externalLink'; +import {CliSetupMarkdown, InstructionMarkdown} from './markdown'; +import {SENTRY_CLI_URL} from './shared'; import styles from './style.module.scss'; type Props = { @@ -17,7 +17,7 @@ type Props = { platformName?: string; /** Skill package name, e.g. "sentry-nextjs-sdk". Omit for generic/all skills. */ skill?: string; - /** Custom instructions for tasks other than SDK setup. */ + /** Custom instructions for tasks other than SDK setup, such as migrations. */ instructions?: { title: string; prompt: string; @@ -26,13 +26,36 @@ type Props = { }; export function AgentSetupCallout({skill, platformName, instructions}: Props) { + if (instructions) { + return ; + } + + return ( + +
    +
    + Set up with Sentry CLI + +
    +
    + + Learn more about the Sentry CLI + +
    +
    + +
    + ); +} + +function InstructionPrompt({ + instructions, +}: { + instructions: NonNullable; +}) { const [copied, setCopied] = useState(false); - const [isExpanded, setIsExpanded] = useState(false); const {emit} = usePlausibleEvent(); - const prompt = instructions?.prompt ?? buildPrompt(platformName); - const title = instructions?.title ?? 'Agent-Assisted Setup'; - const copyPrompt = useCallback( async (event: React.MouseEvent) => { event.stopPropagation(); @@ -41,87 +64,52 @@ export function AgentSetupCallout({skill, platformName, instructions}: Props) { emit('Copy AI Prompt', { props: { page: window.location.pathname, - title: instructions?.title ?? 'Agent Setup Callout', + title: instructions.title, }, }); try { setCopied(false); - await navigator.clipboard.writeText(prompt); + await navigator.clipboard.writeText(instructions.prompt); setCopied(true); - DocMetrics.copyAIPrompt(window.location.pathname, skill, true); + DocMetrics.copyAIPrompt(window.location.pathname, undefined, true); setTimeout(() => setCopied(false), 1500); } catch (error) { Sentry.logger.warn('clipboard.writeText failed', { error: (error as Error)?.message, errorName: (error as Error)?.name, }); - DocMetrics.copyAIPrompt(window.location.pathname, skill, false); + DocMetrics.copyAIPrompt(window.location.pathname, undefined, false); setCopied(false); } }, - [prompt, emit, skill, instructions?.title] + [emit, instructions.prompt, instructions.title] ); - const description = - instructions?.description ?? - (platformName - ? `Your agent will set up Sentry in your ${platformName} app automatically.` - : 'Your agent will set up Sentry automatically.'); - return ( -
    -
    -
    - {title} + +
    +
    +
    + {instructions.title} +
    +
    + {instructions.prompt} +
    +
    -
    - {prompt} +
    + {instructions.description}
    -
    - -
    - - {description} Works with Cursor, Claude Code, Codex, and more. - - {!instructions && ( - - View docs ↗ - - )} -
    - - {!instructions && ( -
    setIsExpanded(e.currentTarget.open)} - > - - {isExpanded ? ( - - ) : ( - - )} - Install the full plugin - -
    -

    - Install the Sentry plugin to give your assistant every skill. See the{' '} - installation docs for more details. -

    - -
    -                npx @sentry/agent-plugin install
    -              
    -
    -
    -
    - )} -
    + +
    ); } diff --git a/src/components/agentSetupCallout/markdown.spec.tsx b/src/components/agentSetupCallout/markdown.spec.tsx new file mode 100644 index 0000000000000..ff93672a88190 --- /dev/null +++ b/src/components/agentSetupCallout/markdown.spec.tsx @@ -0,0 +1,79 @@ +import {Fragment} from 'react'; +import {renderToStaticMarkup} from 'react-dom/server'; +import rehypeParse from 'rehype-parse'; +import rehypeRemark from 'rehype-remark'; +import remarkGfm from 'remark-gfm'; +import remarkStringify from 'remark-stringify'; +import {unified} from 'unified'; +import {describe, expect, it} from 'vitest'; + +import {CliSetupMarkdown, InstructionMarkdown} from './markdown'; + +function htmlToMarkdown(html: string) { + return String( + unified() + .use(rehypeParse, {fragment: true}) + .use(rehypeRemark, { + document: false, + handlers: { + button() {}, + }, + }) + .use(remarkGfm) + .use(remarkStringify) + .processSync(html) + ); +} + +describe('CLI setup markdown export', () => { + it('keeps the install commands and drops the interactive card', () => { + const html = renderToStaticMarkup( + +
    interactive card
    + +
    + ); + + const markdown = htmlToMarkdown(html); + + expect(markdown).not.toContain('interactive card'); + expect(markdown).toContain('## Set up with Sentry CLI'); + expect(markdown).toContain('the Sentry Next.js SDK'); + expect(markdown).toContain( + '```bash\ncurl https://cli.sentry.dev/install -fsS | bash' + ); + expect(markdown).toContain( + '```powershell\nirm https://cli.sentry.dev/install.ps1 | iex' + ); + expect(markdown).toContain('```bash\nbrew install getsentry/tools/sentry'); + expect(markdown).toContain('```bash\nnpx sentry@latest'); + expect(markdown).toContain( + '[Learn more about the Sentry CLI](https://cli.sentry.dev/)' + ); + }); + + it('names Sentry when the page has no platform', () => { + const markdown = htmlToMarkdown(renderToStaticMarkup()); + + expect(markdown).toContain('Set up Sentry with the Sentry CLI.'); + expect(markdown).not.toContain('SDK'); + }); + + it('includes custom instruction prompts', () => { + const markdown = htmlToMarkdown( + renderToStaticMarkup( + + ) + ); + + expect(markdown).toContain('## Agent-Assisted Migration'); + expect(markdown).toContain('Read the migration guide before changing the SDK.'); + expect(markdown).toContain( + 'Copy this prompt into your AI agent to migrate your Sentry SDK.' + ); + }); +}); diff --git a/src/components/agentSetupCallout/markdown.tsx b/src/components/agentSetupCallout/markdown.tsx new file mode 100644 index 0000000000000..cd6e77204ff2d --- /dev/null +++ b/src/components/agentSetupCallout/markdown.tsx @@ -0,0 +1,56 @@ +import {CLI_INSTALL_METHODS, SENTRY_CLI_URL, setupTarget} from './shared'; +import styles from './style.module.scss'; + +type SetupProps = { + platformName?: string; +}; + +function commandLanguage(id: string) { + return id === 'powershell' ? 'language-powershell' : 'language-bash'; +} + +/** + * Semantic copy of the CLI setup card. The interactive card is omitted from + * markdown exports, so this block is what those pages include instead. + */ +export function CliSetupMarkdown({platformName}: SetupProps) { + return ( + + ); +} + +type InstructionProps = { + title: string; + prompt: string; + description: string; +}; + +/** Semantic copy of a custom instruction prompt, included in markdown exports. */ +export function InstructionMarkdown({title, prompt, description}: InstructionProps) { + return ( + + ); +} diff --git a/src/components/agentSetupCallout/shared.ts b/src/components/agentSetupCallout/shared.ts index 9fde0fb5383b8..aa539a15fb7b4 100644 --- a/src/components/agentSetupCallout/shared.ts +++ b/src/components/agentSetupCallout/shared.ts @@ -1,14 +1,45 @@ /** - * Shared constants and utilities for agent skills prompt building. - * Used by AgentSetupCallout (full banner) and inline copy-prompt buttons. + * Shared constants for the Sentry CLI setup prompt. + * Used by the setup callout, the homepage card, and inline copy buttons. */ -export const SKILLS_BASE_URL = 'https://skills.sentry.dev'; +export const SENTRY_CLI_URL = 'https://cli.sentry.dev/'; -/** Single entrypoint skill that instruments any SDK; the SDK is named in prose. */ -export const INSTRUMENT_SKILL_URL = `${SKILLS_BASE_URL}/instrument`; +/** + * Install commands from https://cli.sentry.dev/. + * curl, PowerShell, Homebrew, and npx cover the common paths. + * npm, pnpm, and bun are the same global Node install as each other, so npx stands in for them. + */ +export const CLI_INSTALL_METHODS = [ + { + id: 'curl', + label: 'cURL', + command: 'curl https://cli.sentry.dev/install -fsS | bash', + }, + { + id: 'powershell', + label: 'PowerShell', + command: 'irm https://cli.sentry.dev/install.ps1 | iex', + }, + { + id: 'brew', + label: 'Homebrew', + command: 'brew install getsentry/tools/sentry', + }, + { + id: 'npx', + label: 'npx', + command: 'npx sentry@latest', + }, +] as const; + +export type CliInstallMethodId = (typeof CLI_INSTALL_METHODS)[number]['id']; + +export function setupTarget(sdkName?: string): string { + return sdkName ? `the Sentry ${sdkName} SDK` : 'Sentry'; +} export function buildPrompt(sdkName?: string): string { - const target = sdkName ? `the Sentry ${sdkName} SDK` : 'Sentry'; - return `Use curl to download, read and follow ${INSTRUMENT_SKILL_URL} to set up ${target}.`; + const install = CLI_INSTALL_METHODS[0].command; + return `Set up ${setupTarget(sdkName)} with the Sentry CLI. Install the CLI with \`${install}\`, then follow ${SENTRY_CLI_URL} to finish setup.`; } diff --git a/src/components/agentSetupCallout/style.module.scss b/src/components/agentSetupCallout/style.module.scss index 045ff363e84bc..930f133e08422 100644 --- a/src/components/agentSetupCallout/style.module.scss +++ b/src/components/agentSetupCallout/style.module.scss @@ -5,10 +5,6 @@ border: 1px solid color-mix(in srgb, var(--accent-purple), transparent 60%); background: color-mix(in srgb, var(--accent-purple), transparent 92%); color: var(--gray-500); - - @media (max-width: 768px) { - display: none; - } } :global(.dark) .wrapper { @@ -29,10 +25,20 @@ flex-shrink: 0; } +.setup { + display: flex; + flex-direction: column; + gap: 0.45rem; +} + .title { font-weight: 600; font-size: 0.9rem; - white-space: nowrap; +} + +/* Present in the HTML so markdown export can read it. Hidden on the page. */ +.mdOnly { + display: none; } .promptArea { @@ -132,51 +138,3 @@ :global(.dark) .viewDocs { color: var(--accent-purple-light); } - -.expandSection { - margin-top: 0.35rem; - border-top: 1px solid color-mix(in srgb, var(--accent-purple), transparent 70%); - margin-bottom: -0.5rem; -} - -.expandSummary { - display: flex; - align-items: center; - gap: 0.3rem; - cursor: pointer; - font-size: 0.78rem; - font-weight: 500; - opacity: 0.6; - list-style: none; - user-select: none; - padding: 0.4rem 0; - - &::-webkit-details-marker { - display: none; - } - - &::marker { - display: none; - content: ''; - } - - &:hover { - opacity: 1; - } -} - -.expandIcon { - width: 13px; - height: 13px; - flex-shrink: 0; -} - -.expandBody { - padding-left: 0.25rem; - padding-bottom: 0.25rem; - - & p { - font-size: 0.8rem; - margin-bottom: 0.5rem; - } -} diff --git a/src/components/cliInstallCommand/index.tsx b/src/components/cliInstallCommand/index.tsx new file mode 100644 index 0000000000000..d77c3f1bb27ba --- /dev/null +++ b/src/components/cliInstallCommand/index.tsx @@ -0,0 +1,174 @@ +'use client'; + +import {ChevronDownIcon} from '@radix-ui/react-icons'; +import * as Sentry from '@sentry/nextjs'; +import {type KeyboardEvent, useCallback, useEffect, useId, useRef, useState} from 'react'; +import {Check, Copy} from 'react-feather'; +import {usePlausibleEvent} from 'sentry-docs/hooks/usePlausibleEvent'; +import {DocMetrics} from 'sentry-docs/metrics'; + +import {CLI_INSTALL_METHODS, type CliInstallMethodId} from '../agentSetupCallout/shared'; +import styles from './style.module.scss'; + +type Props = { + platformName?: string; + skill?: string; + source: 'callout' | 'homepage_card'; +}; + +export function CliInstallCommand({platformName, skill, source}: Props) { + const [methodId, setMethodId] = useState('curl'); + const [copied, setCopied] = useState(false); + const [open, setOpen] = useState(false); + const [activeIndex, setActiveIndex] = useState(0); + const {emit} = usePlausibleEvent(); + const rootRef = useRef(null); + const triggerRef = useRef(null); + const listRef = useRef(null); + const listId = useId(); + + const method = + CLI_INSTALL_METHODS.find(item => item.id === methodId) ?? CLI_INSTALL_METHODS[0]; + + const copyCommand = useCallback(async () => { + const title = platformName + ? `Set up ${platformName} with the CLI` + : 'Set up with the CLI'; + + emit('Copy AI Prompt', { + props: {page: window.location.pathname, title}, + }); + + try { + setCopied(false); + await navigator.clipboard.writeText(method.command); + setCopied(true); + DocMetrics.copyAIPrompt(window.location.pathname, skill, true, source); + setTimeout(() => setCopied(false), 1500); + } catch (error) { + Sentry.logger.warn('clipboard.writeText failed', { + error: (error as Error)?.message, + errorName: (error as Error)?.name, + }); + DocMetrics.copyAIPrompt(window.location.pathname, skill, false, source); + setCopied(false); + } + }, [emit, method.command, platformName, skill, source]); + + const closeMenu = useCallback((restoreFocus = false) => { + setOpen(false); + if (restoreFocus) triggerRef.current?.focus(); + }, []); + + const selectMethod = useCallback( + (id: CliInstallMethodId) => { + setMethodId(id); + closeMenu(true); + }, + [closeMenu] + ); + + useEffect(() => { + if (!open) return undefined; + + const selectedIndex = CLI_INSTALL_METHODS.findIndex(item => item.id === methodId); + setActiveIndex(selectedIndex === -1 ? 0 : selectedIndex); + listRef.current?.focus(); + + const onPointerDown = (event: PointerEvent) => { + if (!rootRef.current?.contains(event.target as Node)) closeMenu(); + }; + + document.addEventListener('pointerdown', onPointerDown); + return () => document.removeEventListener('pointerdown', onPointerDown); + }, [closeMenu, methodId, open]); + + const onListKeyDown = (event: KeyboardEvent) => { + const lastIndex = CLI_INSTALL_METHODS.length - 1; + + if (event.key === 'ArrowDown') { + event.preventDefault(); + setActiveIndex(index => (index >= lastIndex ? 0 : index + 1)); + } else if (event.key === 'ArrowUp') { + event.preventDefault(); + setActiveIndex(index => (index <= 0 ? lastIndex : index - 1)); + } else if (event.key === 'Home') { + event.preventDefault(); + setActiveIndex(0); + } else if (event.key === 'End') { + event.preventDefault(); + setActiveIndex(lastIndex); + } else if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + const next = CLI_INSTALL_METHODS[activeIndex]; + if (next) selectMethod(next.id); + } else if (event.key === 'Escape') { + event.preventDefault(); + closeMenu(true); + } else if (event.key === 'Tab') { + closeMenu(); + } + }; + + return ( +
    +
    + + {open ? ( +
    + {CLI_INSTALL_METHODS.map((item, index) => ( +
    setActiveIndex(index)} + onClick={() => selectMethod(item.id)} + > + {item.label} +
    + ))} +
    + ) : null} +
    + {method.command} + +
    + ); +} diff --git a/src/components/cliInstallCommand/style.module.scss b/src/components/cliInstallCommand/style.module.scss new file mode 100644 index 0000000000000..68dfc36d53545 --- /dev/null +++ b/src/components/cliInstallCommand/style.module.scss @@ -0,0 +1,173 @@ +.bar { + display: flex; + align-items: stretch; + min-width: 0; + flex: 1; + border: 1px solid var(--gray-6); + border-radius: 6px; + background: var(--gray-1); + color: var(--gray-12); +} + +.barOpen { + border-bottom-left-radius: 0; +} + +.method { + position: relative; + display: flex; + flex-shrink: 0; +} + +.methodTrigger { + display: inline-flex; + align-items: center; + justify-content: space-between; + gap: 0.4rem; + flex-shrink: 0; + min-width: 8.25rem; + margin: 0; + padding: 0.4rem 0.7rem; + border: none; + border-right: 1px solid var(--gray-6); + border-radius: 5px 0 0 5px; + background: var(--gray-3); + color: inherit; + font-family: var(--font-rubik), sans-serif; + font-size: 0.8125rem; + font-weight: 600; + line-height: 1.3; + white-space: nowrap; + cursor: pointer; + + &:hover { + background: var(--gray-4); + } + + &:focus-visible { + outline: none; + box-shadow: inset 0 0 0 2px var(--accent-purple); + } + + &[aria-expanded='true'] { + border-bottom-left-radius: 0; + } + + &[aria-expanded='true'] .chevron { + transform: rotate(180deg); + } +} + +@media (max-width: 640px) { + .methodTrigger { + min-width: 6.25rem; + padding-right: 0.5rem; + padding-left: 0.55rem; + } +} + +.chevron { + width: 14px; + height: 14px; + flex-shrink: 0; + transition: transform 150ms ease; +} + +.command { + flex: 1; + min-width: 0; + margin: 0; + padding: 0.45rem 0.75rem; + overflow-x: auto; + background: none; + border: none; + color: inherit; + font-family: var(--font-family-monospace); + font-size: 0.8125rem; + line-height: 1.45; + white-space: nowrap; + scrollbar-width: thin; +} + +.copyButton { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 2.25rem; + margin: 0; + padding: 0; + border: none; + border-left: 1px solid var(--gray-6); + border-radius: 0 5px 5px 0; + background: transparent; + color: var(--gray-12); + cursor: pointer; + + &:hover { + background: var(--gray-3); + color: var(--gray-12); + } + + &:focus-visible { + outline: none; + box-shadow: inset 0 0 0 2px var(--accent-purple); + } +} + +.menu { + position: absolute; + z-index: 40; + top: calc(100% + 1px); + left: -1px; + width: calc(100% + 1px); + padding: 0.25rem; + border: 1px solid var(--gray-6); + border-top: none; + border-radius: 0 0 6px 6px; + background: var(--gray-1); + color: var(--gray-12); + font-family: var(--font-rubik), sans-serif; + font-weight: 600; + box-shadow: 0 10px 16px -12px var(--gray-12); + outline: none; +} + +.option { + display: flex; + align-items: center; + width: 100%; + padding: 0.4rem 0.65rem; + border: none; + border-radius: 4px; + background: transparent; + color: inherit; + font-family: inherit; + font-size: 0.8125rem; + font-weight: 600; + line-height: 1.3; + text-align: left; + cursor: pointer; + user-select: none; + + &[data-active='true'] { + outline: none; + background: var(--gray-3); + } + + &[aria-selected='true'] { + background: var(--gray-4); + } +} + +.srOnly { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} diff --git a/src/components/conventionAttributes/index.spec.tsx b/src/components/conventionAttributes/index.spec.tsx new file mode 100644 index 0000000000000..8738f8c95b440 --- /dev/null +++ b/src/components/conventionAttributes/index.spec.tsx @@ -0,0 +1,79 @@ +import {ATTRIBUTE_METADATA} from '@sentry/conventions/attributes'; +import React from 'react'; +import {renderToStaticMarkup} from 'react-dom/server'; +import {describe, expect, it, vi} from 'vitest'; + +import {ConventionAttributes} from './index'; + +// Vitest compiles JSX with the classic runtime here (tsconfig `jsx: preserve`). +vi.stubGlobal('React', React); + +describe('ConventionAttributes', () => { + it('renders attributes from the conventions package', () => { + const html = renderToStaticMarkup( + + ); + + expect(html).toContain('gen_ai.tool.name'); + expect(html).toContain(ATTRIBUTE_METADATA['gen_ai.tool.name'].type); + expect(html).toContain(ATTRIBUTE_METADATA['gen_ai.tool.name'].brief); + }); + + it('appends page-specific notes to the description', () => { + const html = renderToStaticMarkup( + + ); + + expect(html).toContain('[2]'); + }); + + it('throws on unknown attributes so the build fails', () => { + expect(() => + renderToStaticMarkup() + ).toThrow('unknown attribute "gen_ai.not.a.thing"'); + }); + + it('throws on keys inherited from Object.prototype', () => { + expect(() => + renderToStaticMarkup() + ).toThrow('unknown attribute "constructor"'); + }); + + it('single-quotes stringified JSON examples', () => { + const html = renderToStaticMarkup( + + ); + + expect(html).toContain( + `'${ATTRIBUTE_METADATA['gen_ai.tool.call.arguments'].example}'`.replaceAll( + '"', + '"' + ) + ); + expect(html).toContain( + `"${ATTRIBUTE_METADATA['gen_ai.tool.name'].example}"` + ); + }); + + it('renders the example at the given index', () => { + const html = renderToStaticMarkup( + + ); + const examples = ATTRIBUTE_METADATA['gen_ai.input.messages'].examples!; + + expect(html).toContain(`'${examples[1]}'`.replaceAll('"', '"')); + expect(html).not.toContain(`'${examples[0]}'`.replaceAll('"', '"')); + }); + + it('throws on an example index that does not exist', () => { + expect(() => + renderToStaticMarkup( + + ) + ).toThrow('attribute "gen_ai.tool.name" has no example at index 99'); + }); +}); diff --git a/src/components/conventionAttributes/index.tsx b/src/components/conventionAttributes/index.tsx new file mode 100644 index 0000000000000..507132c28bcf5 --- /dev/null +++ b/src/components/conventionAttributes/index.tsx @@ -0,0 +1,83 @@ +import { + ATTRIBUTE_METADATA, + type AttributeMetadata, + type AttributeValue, +} from '@sentry/conventions/attributes'; +import {micromark} from 'micromark'; + +type Props = { + attributes: (string | {key: string; example?: number; notes?: string})[]; +}; + +const metadata: Record = ATTRIBUTE_METADATA; + +/** + * Renders attribute details from `@sentry/conventions`, so pages don't copy + * types, descriptions, and examples that drift from the source of truth. + */ +export function ConventionAttributes({attributes}: Props) { + const rows = attributes.map(row => { + const { + key, + notes, + example: exampleIndex, + } = typeof row === 'string' ? {key: row} : row; + // `Object.hasOwn` so keys like `constructor` don't pass as known attributes. + const attribute = Object.hasOwn(metadata, key) ? metadata[key] : undefined; + if (!attribute) { + throw new Error(`: unknown attribute "${key}"`); + } + const description = micromark([attribute.brief, notes].filter(Boolean).join(' ')) + .replace(/^

    /, '') + .replace(/<\/p>$/, ''); + // Pick one of `examples` by index when the page asks for it, so a page can + // show the example that fits its context. + let example = attribute.example; + if (exampleIndex !== undefined) { + if (!attribute.examples || !Object.hasOwn(attribute.examples, exampleIndex)) { + throw new Error( + `: attribute "${key}" has no example at index ${exampleIndex}` + ); + } + example = attribute.examples[exampleIndex]; + } + return {key, attribute, description, example}; + }); + + return ( + + + + + + + + + + + {rows.map(({key, attribute, description, example}) => ( + + + + {/* Briefs are long; override the site's nowrap rule for non-last columns. */} + + + ))} + +
    AttributeTypeDescriptionExample
    + {key} + {attribute.type} + {example !== undefined && {formatExample(example)}}
    + ); +} + +function formatExample(example: AttributeValue) { + if (typeof example !== 'string') { + return JSON.stringify(example); + } + // Single-quote stringified JSON so its inner double quotes stay readable. + return /^[[{]/.test(example) ? `'${example}'` : `"${example}"`; +} diff --git a/src/components/copyPromptButton/index.tsx b/src/components/copyPromptButton/index.tsx index 21455df35cc22..af109c853fdac 100644 --- a/src/components/copyPromptButton/index.tsx +++ b/src/components/copyPromptButton/index.tsx @@ -4,12 +4,17 @@ import * as Tooltip from '@radix-ui/react-tooltip'; import {Theme} from '@radix-ui/themes'; import * as Sentry from '@sentry/nextjs'; import {useTheme} from 'next-themes'; -import {useCallback, useMemo, useState} from 'react'; +import {Fragment, useCallback, useMemo, useState} from 'react'; import {Copy} from 'react-feather'; import {usePlausibleEvent} from 'sentry-docs/hooks/usePlausibleEvent'; import {DocMetrics} from 'sentry-docs/metrics'; -import {buildPrompt} from '../agentSetupCallout/shared'; +import { + buildPrompt, + CLI_INSTALL_METHODS, + SENTRY_CLI_URL, + setupTarget, +} from '../agentSetupCallout/shared'; import styles from './style.module.scss'; type Props = { @@ -88,33 +93,42 @@ export function CopyPromptButton({skill, platformName}: Props) { ); return ( - - | - - - - - - {!copied && ( - - - - Copy setup prompt for AI agents - - - - - )} - - - + + + | + + + + + + {!copied && ( + + + + Set up with the CLI + + + + + )} + + + + + ); } diff --git a/src/components/copyPromptButton/style.module.scss b/src/components/copyPromptButton/style.module.scss index 4bc6f92171583..1fb572ec3a6e8 100644 --- a/src/components/copyPromptButton/style.module.scss +++ b/src/components/copyPromptButton/style.module.scss @@ -67,4 +67,7 @@ letter-spacing: 0.01em; } - +/* Present in the HTML so markdown export can read it. Hidden on the page. */ +.mdOnly { + display: none; +} diff --git a/src/components/docPage/index.tsx b/src/components/docPage/index.tsx index 22e6c5e301a9e..014f3bb37904c 100644 --- a/src/components/docPage/index.tsx +++ b/src/components/docPage/index.tsx @@ -29,6 +29,7 @@ import Mermaid from '../mermaid'; import {PaginationNav} from '../paginationNav'; import {PlatformSdkDetail} from '../platformSdkDetail'; import {getSdkPackageName} from '../platformSdkPackageName'; +import {RuntimeSelector} from '../runtimeSelector'; import {Sidebar} from '../sidebar'; import {SidebarTableOfContents} from '../sidebarTableOfContents'; import {ReaderDepthTracker} from '../track-reader-depth'; @@ -123,6 +124,7 @@ export async function DocPage({ {/* This exact id is important for Algolia indexing */}

    + {frontMatter.runtime && } {children} diff --git a/src/components/featureInfo.tsx b/src/components/featureInfo.tsx index 6b893b539cae5..9e792259c1735 100644 --- a/src/components/featureInfo.tsx +++ b/src/components/featureInfo.tsx @@ -159,6 +159,7 @@ const FEATURE_DATA: Record< type FeatureInfoProps = { features: FeatureKey[]; + overrides?: Partial>; type: 'learnMore' | 'findInSentry'; }; @@ -169,11 +170,11 @@ type FeatureInfoProps = { * @param features - Array of feature keys to display * @param type - learnMore shows feature descriptions, findInSentry shows navigation help */ -export function FeatureInfo({features, type}: FeatureInfoProps) { +export function FeatureInfo({features, overrides, type}: FeatureInfoProps) { return (
      {features.map(key => { - const feature = FEATURE_DATA[key]; + const feature = {...FEATURE_DATA[key], ...overrides?.[key]}; if (type === 'learnMore') { return ( diff --git a/src/components/frameworkSelector/frameworks.spec.ts b/src/components/frameworkSelector/frameworks.spec.ts new file mode 100644 index 0000000000000..678adb983c3fb --- /dev/null +++ b/src/components/frameworkSelector/frameworks.spec.ts @@ -0,0 +1,96 @@ +import {existsSync, readdirSync, readFileSync} from 'node:fs'; +import {join} from 'node:path'; + +import matter from 'gray-matter'; +import {describe, expect, it} from 'vitest'; + +import {getRuntimeLinks} from '../runtimeLinks'; +import {Runtime, RUNTIMES} from './frameworks'; + +const GUIDES_DIR = 'docs/platforms/javascript/guides'; + +const linkedUrls = (runtime: Runtime) => + [...(runtime.frameworkGuides ?? []), ...(runtime.agentGuides ?? [])].map(g => g.url); + +const pageExists = (url: string) => { + const file = join('docs', url.replace(/\/$/, '')); + return existsSync(`${file}.mdx`) || existsSync(join(file, 'index.mdx')); +}; + +/** The index page of a guide and its child pages, with their frontmatter. */ +const guidePages = (guide: string) => { + const dir = join(GUIDES_DIR, guide); + const path = `platforms/javascript/guides/${guide}`; + const frontmatter = (file: string) => + matter(readFileSync(join(dir, file), 'utf8')).data; + const children = readdirSync(dir, {withFileTypes: true}).flatMap(entry => { + const file = entry.isDirectory() ? join(entry.name, 'index.mdx') : entry.name; + if (!file.endsWith('.mdx') || file === 'index.mdx' || !existsSync(join(dir, file))) { + return []; + } + const name = entry.isDirectory() ? entry.name : entry.name.replace(/\.mdx$/, ''); + return [{path: `${path}/${name}`, frontmatter: frontmatter(file)}]; + }); + return {path, frontmatter: frontmatter('index.mdx'), children}; +}; + +/** The quick start page of a runtime. Browser JavaScript is the platform's own page. */ +const quickStartFile = (runtime: string) => + runtime === 'browser' + ? 'docs/platforms/javascript/common/index.mdx' + : join(GUIDES_DIR, runtime, 'index.mdx'); + +const PLATFORM_CONTENT_RE = /]*)\/>/g; + +/** + * The `switchable` include paths of a runtime's quick start: the ones on its page and in the + * `platform-includes` files the page includes directly. + */ +const switchableIncludePaths = (runtime: string) => { + const found = new Set(); + const scan = (source: string, nested: boolean) => { + for (const [, includePath, attributes] of source.matchAll(PLATFORM_CONTENT_RE)) { + if (/\bswitchable\b/.test(attributes)) { + found.add(includePath); + } else if (nested) { + const file = [`javascript.${runtime}.mdx`, 'javascript.mdx'] + .map(name => join('platform-includes', includePath, name)) + .find(existsSync); + if (file) { + scan(readFileSync(file, 'utf8'), false); + } + } + } + }; + scan(readFileSync(quickStartFile(runtime), 'utf8'), true); + return [...found].sort(); +}; + +describe('RUNTIMES', () => { + it.each(Object.entries(RUNTIMES))('%s links only to existing pages', (_, runtime) => { + expect(linkedUrls(runtime).filter(url => !pageExists(url))).toEqual([]); + }); + + it.each(Object.entries(RUNTIMES))( + '%s lists every switchable include path of its quick start', + (runtime, {includePaths}) => { + expect(switchableIncludePaths(runtime)).toEqual([...includePaths].sort()); + } + ); + + it('links every quick start of a guide with quick starts for more than one runtime', () => { + const guides = readdirSync(GUIDES_DIR).filter(guide => + existsSync(join(GUIDES_DIR, guide, 'index.mdx')) + ); + const missing = guides.flatMap(guide => + (getRuntimeLinks(guidePages(guide), []) ?? []) + .filter( + link => + link.runtime in RUNTIMES && + !linkedUrls(RUNTIMES[link.runtime]).includes(link.url) + ) + .map(link => link.url) + ); + expect(missing).toEqual([]); + }); +}); diff --git a/src/components/frameworkSelector/frameworks.ts b/src/components/frameworkSelector/frameworks.ts new file mode 100644 index 0000000000000..8e60cf9b7032a --- /dev/null +++ b/src/components/frameworkSelector/frameworks.ts @@ -0,0 +1,173 @@ +export type Framework = { + /** Guide slug, e.g. `express` for `/platforms/javascript/guides/express/`. */ + key: string; + title: string; +}; + +const EXPRESS: Framework = {key: 'express', title: 'Express'}; +const FASTIFY: Framework = {key: 'fastify', title: 'Fastify'}; +const KOA: Framework = {key: 'koa', title: 'Koa'}; +const HAPI: Framework = {key: 'hapi', title: 'Hapi'}; + +/** A framework with its own Sentry SDK. The selector opens its guide instead of swapping snippets. */ +export type FrameworkGuide = { + /** Platform icon key, e.g. `javascript-astro`. */ + icon: string; + title: string; + url: string; +}; + +/** + * `slug` is the page path below `/platforms/javascript/guides/`. The icon defaults to the + * one of the guide in the first segment of `slug`. + */ +const guide = ( + title: string, + slug: string, + icon = `javascript-${slug.split('/')[0]}` +): FrameworkGuide => ({ + icon, + title, + url: `/platforms/javascript/guides/${slug}/`, +}); + +export type Runtime = { + /** Frameworks selectable on the runtime's getting started page. */ + frameworks: Framework[]; + /** Frameworks with their own Sentry SDK that the selector links to. */ + frameworkGuides?: FrameworkGuide[]; + /** + * Agent frameworks that the selector links to in the "Agent frameworks" group. Each URL is + * the framework's quick start for this runtime. + */ + agentGuides?: FrameworkGuide[]; + /** + * `` include paths on the runtime's getting started page. + * Each one is pre-built per framework as a static JSON file that the page loads on demand. + */ + includePaths: string[]; + title: string; +}; + +/** + * Runtime guides (keyed by guide slug) that have a framework selector on their getting started + * page. `browser` is the Browser JavaScript page at `/platforms/javascript/`. + */ +export const RUNTIMES: Record = { + browser: { + title: 'Browser JavaScript', + frameworks: [], + frameworkGuides: [ + guide('Angular', 'angular'), + guide('Astro', 'astro'), + guide('Ember', 'ember'), + guide('Gatsby', 'gatsby'), + guide('Next.js', 'nextjs'), + guide('Nuxt', 'nuxt'), + guide('React', 'react'), + guide('React Router', 'react-router'), + guide('Remix', 'remix'), + guide('Solid', 'solid'), + guide('SolidStart', 'solidstart'), + guide('Svelte', 'svelte'), + guide('SvelteKit', 'sveltekit'), + guide('TanStack Start', 'tanstackstart-react'), + guide('Vue', 'vue'), + ], + includePaths: [], + }, + node: { + title: 'Node.js', + frameworks: [EXPRESS, FASTIFY, KOA, HAPI], + frameworkGuides: [ + guide('Astro', 'astro'), + guide('Hono', 'hono'), + guide('NestJS', 'nestjs'), + guide('Next.js', 'nextjs'), + guide('Nitro', 'nitro'), + guide('Nuxt', 'nuxt'), + guide('React Router', 'react-router'), + guide('Remix', 'remix'), + guide('SolidStart', 'solidstart'), + guide('SvelteKit', 'sveltekit'), + guide('TanStack Start', 'tanstackstart-react'), + ], + agentGuides: [ + guide('Eve', 'eve'), + guide('Flue', 'flue'), + guide('Mastra', 'mastra'), + guide('Pi Durable', 'pi-durable'), + ], + includePaths: [ + 'getting-started-prerequisites', + 'getting-started-install', + 'getting-started-config', + 'getting-started-capture-errors', + 'getting-started-sourcemaps-short-version', + 'getting-started-data-collection', + 'getting-started-verify', + ], + }, + bun: { + title: 'Bun', + frameworks: [EXPRESS, FASTIFY, KOA, HAPI], + frameworkGuides: [ + guide('Elysia', 'elysia'), + guide('Hono', 'hono'), + guide('React Router', 'react-router/bun'), + ], + agentGuides: [guide('Pi Durable', 'pi-durable/bun')], + includePaths: ['getting-started-verify-issues-tracing'], + }, + deno: { + title: 'Deno', + frameworks: [EXPRESS, FASTIFY, KOA, HAPI], + frameworkGuides: [guide('Hono', 'hono'), guide('React Router', 'react-router/deno')], + agentGuides: [guide('Pi Durable', 'pi-durable/deno')], + includePaths: ['getting-started-verify-issues-tracing'], + }, + cloudflare: { + title: 'Cloudflare Workers', + frameworks: [], + frameworkGuides: [ + guide('Astro', 'astro/cloudflare'), + guide('Hono', 'hono/cloudflare'), + guide('Hydrogen', 'react-router/hydrogen', 'javascript-hydrogen'), + guide('Next.js', 'nextjs/cloudflare'), + guide('Nuxt', 'nuxt/cloudflare'), + guide('React Router', 'react-router/cloudflare'), + guide('Remix', 'remix/cloudflare'), + guide('SvelteKit', 'sveltekit/cloudflare'), + guide('TanStack Start', 'tanstackstart-react/cloudflare'), + ], + agentGuides: [ + guide('Flue', 'flue/cloudflare'), + guide('Mastra', 'mastra/cloudflare'), + guide('Pi Durable', 'pi-durable/cloudflare'), + ], + includePaths: [], + }, +}; + +export const FRAMEWORK_QUERY_PARAM = 'framework'; + +/** The serialized form of a `` include, served by the platform-content API route. */ +export type PlatformContentPayload = { + /** Whether the content differs from what the runtime's page shows without a framework. */ + changed: boolean; + /** Compiled MDX of the resolved include, or `null` if there is no content for it. */ + code: string | null; + /** Compiled MDX of nested `` files, keyed by name. */ + includes: Record; + /** Compiled MDX of nested `` files, keyed by include path. */ + platformContents: Record; +}; + +export function platformContentUrl( + platform: string, + runtime: string, + framework: string, + includePath: string +) { + return `/api/platform-content/${platform}/${runtime}/${framework}/${includePath}/`; +} diff --git a/src/components/frameworkSelector/index.tsx b/src/components/frameworkSelector/index.tsx new file mode 100644 index 0000000000000..6c569390f113d --- /dev/null +++ b/src/components/frameworkSelector/index.tsx @@ -0,0 +1,570 @@ +'use client'; + +import {ArrowRightIcon, CaretSortIcon} from '@radix-ui/react-icons'; +import * as RadixSelect from '@radix-ui/react-select'; +import {useRouter} from 'next/navigation'; +import { + createContext, + ReactNode, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from 'react'; +import {getMDXComponent} from 'sentry-docs/getMDXComponent'; + +import {Alert} from '../alert'; +import {CodeBlock} from '../codeBlock'; +import {CodeContext} from '../codeContext'; +import {CodeTabs} from '../codeTabs'; +import {Expandable} from '../expandable'; +import {FeatureBadge} from '../featureBadge'; +import { + OnboardingOption, + OnboardingOptionButtons, + OnboardingSteps, + updateElementsVisibilityForOptions, +} from '../onboarding'; +import {PlatformIcon} from '../platformIcon'; +import {SmartLink} from '../smartLink'; +import styles from '../versionSelector/style.module.scss'; +import { + Framework, + FRAMEWORK_QUERY_PARAM, + FrameworkGuide, + PlatformContentPayload, + platformContentUrl, + RUNTIMES, +} from './frameworks'; +import frameworkStyles from './style.module.scss'; + +const DEFAULT_VALUE = 'none'; +const GUIDE_VALUE_PREFIX = 'guide:'; +const groupLabelClassName = 'px-2 pt-2 pb-1 text-xs font-medium text-[var(--gray-11)]'; +const itemClassName = `${styles.item} ${frameworkStyles.option}`; + +/** The state of a switchable block while a framework is selected. */ +type ContentStatus = + | {state: 'loading' | 'unchanged'} + /** `step` is the title of the `h2` step that contains the block, `targetId` the block's id. */ + | {state: 'changed'; targetId: string; step?: string}; + +type FrameworkContextValue = { + framework: Framework | null; + platform: string; + /** Records the status of the block with `includePath`, or removes it with `null`. */ + reportContent: (includePath: string, status: ContentStatus | null) => void; + /** The runtime guide the page belongs to, e.g. `node`. */ + runtime: string; +}; + +const FrameworkContext = createContext(null); + +function ItemLabel({icon, title}: {icon: string; title: string}) { + return ( + + + {title} + + ); +} + +/** + * The guides of a dropdown group as plain links. The dropdown renders its options only while + * it's open, so without these the page's HTML, and its Markdown export for AI agents, would + * not link the guides. People use the dropdown, so the links are hidden from them. + */ +function GuideLinks({guides, label}: {guides: FrameworkGuide[]; label: string}) { + if (guides.length === 0) { + return null; + } + return ( + + ); +} + +function GuideGroup({guides, label}: {guides: FrameworkGuide[]; label: string}) { + if (guides.length === 0) { + return null; + } + + return ( + + {label} + {guides.map(g => ( + + + + + + + ))} + + ); +} + +function stepTitle(el: HTMLElement): string | undefined { + const step = Array.from(document.querySelectorAll('main h2[id]')) + .filter(h => h.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) + .pop(); + return (step?.querySelector('a') ?? step)?.textContent?.trim(); +} + +function FrameworkSummary({ + contents, + framework, + platform, +}: { + contents: Record; + framework: Framework; + platform: string; +}) { + const statuses = Object.values(contents); + if (statuses.some(c => c.state === 'loading')) { + return ( +

      Loading the steps for {framework.title}…

      + ); + } + + const changed = statuses + .filter(c => c.state === 'changed') + .map(c => ({...c, el: document.getElementById(c.targetId)})) + .filter(c => c.el) + .sort((a, b) => + a.el!.compareDocumentPosition(b.el!) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1 + ); + const steps = changed.filter( + (c, i) => changed.findIndex(other => other.step === c.step) === i + ); + + return ( +

      + + {steps.length > 0 ? ( + + Updated for {framework.title}:{' '} + {steps.map((c, i) => ( + + {i > 0 && ', '} + {c.step ?? 'Show the change'} + + ))} + + ) : ( + The steps for {framework.title} are the same as without a framework. + )} +

      + ); +} + +function readFrameworkFromUrl(frameworks: Framework[]): Framework | null { + const key = new URLSearchParams(window.location.search).get(FRAMEWORK_QUERY_PARAM); + return frameworks.find(f => f.key === key) ?? null; +} + +function writeFrameworkToUrl(framework: Framework | null) { + const url = new URL(window.location.href); + if (framework) { + url.searchParams.set(FRAMEWORK_QUERY_PARAM, framework.key); + } else { + url.searchParams.delete(FRAMEWORK_QUERY_PARAM); + } + window.history.replaceState(window.history.state, '', url); +} + +/** + * Renders a framework dropdown and lets `` blocks among its + * children swap to the selected framework's snippets for `runtime`, loaded on demand. + * The selection is kept in the `?framework=` query param. + */ +export function FrameworkSelector({ + children, + runtime, + platform = 'javascript', +}: { + runtime: string; + children?: ReactNode; + platform?: string; +}) { + const router = useRouter(); + const runtimeConfig = RUNTIMES[runtime]; + const frameworks = useMemo(() => runtimeConfig?.frameworks ?? [], [runtimeConfig]); + const [framework, setFramework] = useState(null); + const [contents, setContents] = useState>({}); + + const reportContent = useCallback( + (includePath: string, status: ContentStatus | null) => + setContents(prev => { + const next = {...prev}; + if (status) { + next[includePath] = status; + } else { + delete next[includePath]; + } + return next; + }), + [] + ); + + // The page is statically rendered, so the query param can only be read after mount. + useEffect(() => { + setFramework(readFrameworkFromUrl(frameworks)); + }, [frameworks]); + + const handleChange = (value: string) => { + if (value.startsWith(GUIDE_VALUE_PREFIX)) { + router.push(value.slice(GUIDE_VALUE_PREFIX.length)); + return; + } + const selected = frameworks.find(f => f.key === value) ?? null; + setFramework(selected); + writeFrameworkToUrl(selected); + }; + + const contextValue = useMemo( + () => ({framework, platform, reportContent, runtime}), + [framework, platform, reportContent, runtime] + ); + + return ( + + {/* Left out of the Markdown export, which gets the guides from `GuideLinks` */} +
      + +
      + + + + + + + + + {/* Radix finds the items for keyboard navigation only inside the viewport. + It hides the viewport's scrollbar, so the content scrolls instead. */} + + + + + + + {frameworks.length > 0 && ( + + + Set up with this guide + + {frameworks.map(f => ( + + + + + + ))} + + )} + + + + + +
      +
      + + +
      + {framework && ( + + )} +
      + {children} +
      + ); +} + +const payloadCache = new Map>(); + +function fetchPayload(url: string): Promise { + let promise = payloadCache.get(url); + if (!promise) { + promise = fetch(url).then(res => { + if (!res.ok) { + throw new Error(`Failed to load ${url}: ${res.status}`); + } + return res.json(); + }); + // Allow retrying after a failed request + promise.catch(() => payloadCache.delete(url)); + payloadCache.set(url, promise); + } + return promise; +} + +/** + * Client-side stand-ins for the server-only MDX components, scoped to the selected + * framework on the page's runtime. + */ +function clientMdxComponents( + payload: PlatformContentPayload, + platform: string, + runtime: string, + framework: string +) { + // Checked in order, like the server's fallback chain + const platformKeys = [`${platform}.${framework}`, `${platform}.${runtime}`]; + + function MDX({code}: {code: string | null | undefined}) { + const Component = useMemo(() => (code ? getMDXComponent(code) : null), [code]); + return Component ? : null; + } + + function Include({name}: {name: string}) { + return ; + } + + function PlatformContent({includePath}: {includePath: string}) { + return ; + } + + function PlatformLink({children, to}: {children: ReactNode; to?: string}) { + if (!to) { + return children; + } + return ( + + {children} + + ); + } + + function PlatformSection({ + children, + supported = [], + notSupported = [], + noGuides, + }: { + children: ReactNode; + noGuides?: boolean; + notSupported?: string[]; + supported?: string[]; + }) { + if (noGuides) { + return null; + } + for (const key of platformKeys) { + if (supported.includes(key)) { + return
      {children}
      ; + } + if (notSupported.includes(key)) { + return null; + } + } + return supported.length ? null :
      {children}
      ; + } + + const components = { + Alert, + CodeBlock, + CodeTabs, + Expandable, + FeatureBadge, + Include, + Link: SmartLink, + OnboardingOption, + OnboardingOptionButtons, + OnboardingSteps, + PlatformContent, + PlatformLink, + PlatformSection, + a: SmartLink, + }; + + return {MDX, components}; +} + +function RemoteFrameworkContent({ + fallback, + framework, + includePath, + platform, + reportContent, + runtime, +}: { + fallback: ReactNode; + framework: Framework; + includePath: string; + platform: string; + reportContent: FrameworkContextValue['reportContent']; + runtime: string; +}) { + const url = platformContentUrl(platform, runtime, framework.key, includePath); + const [payload, setPayload] = useState(null); + const [error, setError] = useState(false); + const codeContext = useContext(CodeContext); + const changedRef = useRef(null); + const targetId = `framework-content-${includePath.replace(/\//g, '-')}`; + + useEffect(() => { + if (error) { + reportContent(includePath, {state: 'unchanged'}); + } else if (!payload) { + reportContent(includePath, {state: 'loading'}); + } else if (!payload.changed || !changedRef.current) { + reportContent(includePath, {state: 'unchanged'}); + } else { + reportContent(includePath, { + state: 'changed', + step: stepTitle(changedRef.current), + targetId, + }); + } + }, [error, includePath, payload, reportContent, targetId]); + + useEffect(() => () => reportContent(includePath, null), [includePath, reportContent]); + + useEffect(() => { + let cancelled = false; + setPayload(null); + setError(false); + fetchPayload(url).then( + result => !cancelled && setPayload(result), + () => !cancelled && setError(true) + ); + return () => { + cancelled = true; + }; + }, [url]); + + const mdx = useMemo( + () => + payload ? clientMdxComponents(payload, platform, runtime, framework.key) : null, + [payload, platform, runtime, framework.key] + ); + + // Apply the current feature selection (tracing, profiling, ...) to the new content + useEffect(() => { + if (payload && codeContext?.onboardingOptions) { + updateElementsVisibilityForOptions(codeContext.onboardingOptions, false); + } + }, [payload, codeContext?.onboardingOptions]); + + if (error || payload?.changed === false) { + return fallback; + } + + if (!payload || !mdx) { + return ( +
      + {fallback} +
      + ); + } + + return ( +
      +

      + + For {framework.title} +

      + +
      + ); +} + +/** + * Renders the server-rendered `children` by default, or the selected framework's + * version of `includePath` when inside a `` with a framework selected. + */ +export function FrameworkContent({ + children, + includePath, +}: { + children: ReactNode; + includePath: string; +}) { + const context = useContext(FrameworkContext); + + if (!context?.framework) { + return children; + } + + return ( + + ); +} diff --git a/src/components/frameworkSelector/style.module.scss b/src/components/frameworkSelector/style.module.scss new file mode 100644 index 0000000000000..5ba4afe092218 --- /dev/null +++ b/src/components/frameworkSelector/style.module.scss @@ -0,0 +1,69 @@ +.summary { + display: flex; + align-items: center; + gap: 0.5rem; + margin-top: -0.5rem; + font-size: 0.875rem; + color: var(--gray-11); +} + +.changed { + margin-block: 1rem; + padding: 0.25rem 0 0.25rem 1rem; + border-left: 3px solid var(--accent-purple); + border-radius: 0 0.25rem 0.25rem 0; + // Clears the sticky header and the sticky feature buttons of the quick start + scroll-margin-top: calc(var(--header-height) + 5rem); + animation: highlight 1.6s ease-out; +} + +.label { + display: flex; + align-items: center; + gap: 0.5rem; + margin: 0 0 0.5rem; + font-size: 0.75rem; + font-weight: 500; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--accent-purple); +} + +// The option that has the keyboard focus. The selected option keeps its own color. +.option[data-highlighted]:not([data-state='checked']) { + background-color: var(--accent-purple-light); +} + +@keyframes highlight { + from { + background-color: var(--accent-purple-light); + } + + to { + background-color: transparent; + } +} + +:global(.dark) { + .label { + color: var(--accent-purple-light); + } + + .changed { + animation-name: highlight-dark; + } + + .option[data-highlighted]:not([data-state='checked']) { + background-color: var(--gray-a4); + } +} + +@keyframes highlight-dark { + from { + background-color: color-mix(in srgb, var(--accent-purple), transparent 85%); + } + + to { + background-color: transparent; + } +} diff --git a/src/components/home.module.scss b/src/components/home.module.scss index 44841f711466b..e8ccea1322b0d 100644 --- a/src/components/home.module.scss +++ b/src/components/home.module.scss @@ -83,7 +83,7 @@ .agentHeader { display: grid; - grid-template-columns: auto 1fr auto; + grid-template-columns: auto 1fr; align-items: center; column-gap: 16px; row-gap: 16px; @@ -100,13 +100,7 @@ margin-bottom: 0; } - .commandPill { - grid-column: 3; - grid-row: 1; - margin-top: 0; - margin-left: 0; - } - + .cliInstall, .setupRowCopy { grid-column: 1 / -1; } @@ -114,25 +108,6 @@ .setupDesc { margin-bottom: 0; flex: unset; - - & + .setupDesc { - margin-top: 6px; - } - } -} - -@media (max-width: 767px) { - .agentHeader { - grid-template-columns: auto 1fr; - - .commandPill { - grid-column: 1 / -1; - grid-row: 2; - } - - .setupRowCopy { - grid-row: 3; - } } } @@ -193,75 +168,6 @@ text-decoration: underline; } -// Shared command/action pill. -%pill { - display: flex; - align-items: center; - gap: 10px; - align-self: flex-start; - max-width: 100%; - margin-top: auto; - padding: 8px 14px; - border: 1px solid var(--gray-5); - border-radius: 999px; - background: var(--gray-1); - transition: - border-color 0.15s ease, - background 0.15s ease; - - &:hover { - border-color: var(--accent-purple); - } - - &:focus-visible { - outline: 2px solid var(--accent-purple); - outline-offset: 2px; - } -} - -.commandPill { - @extend %pill; - - cursor: pointer; -} - -:global(.dark) .commandPill { - background: var(--gray-3); -} - -.agentIcons { - display: inline-flex; - align-items: center; - gap: 6px; - flex-shrink: 0; - color: var(--gray-12); - padding-right: 10px; - border-right: 1px solid var(--gray-5); -} - -.commandText { - font-family: var(--font-family-monospace, monospace); - font-size: 12.5px; - white-space: nowrap; - color: var(--gray-12); - background: none; - border: none; - padding: 0; - overflow: hidden; - text-overflow: ellipsis; -} - -.commandAction { - display: inline-flex; - align-items: center; - flex-shrink: 0; - color: var(--accent-purple); -} - -:global(.dark) .commandAction { - color: var(--accent-purple-light); -} - .quickLink { display: block; padding: 18px 20px; diff --git a/src/components/homeAiSetupCard.tsx b/src/components/homeAiSetupCard.tsx index 3e3eab8ddb674..1265685a1bd41 100644 --- a/src/components/homeAiSetupCard.tsx +++ b/src/components/homeAiSetupCard.tsx @@ -1,96 +1,34 @@ -'use client'; - -import * as Sentry from '@sentry/nextjs'; -import Link from 'next/link'; -import {useCallback, useState} from 'react'; -import {Check, Copy} from 'react-feather'; -import {usePlausibleEvent} from 'sentry-docs/hooks/usePlausibleEvent'; -import Claude from 'sentry-docs/icons/claude'; -import Codex from 'sentry-docs/icons/codex'; -import Cursor from 'sentry-docs/icons/cursor'; -import {DocMetrics} from 'sentry-docs/metrics'; +import {Fragment} from 'react'; +import {CliSetupMarkdown} from './agentSetupCallout/markdown'; +import {SENTRY_CLI_URL} from './agentSetupCallout/shared'; +import {CliInstallCommand} from './cliInstallCommand'; import {ExternalLink} from './externalLink'; import styles from './home.module.scss'; -/** Keep in sync with /ai/agent-plugin/. */ -const INSTALL_COMMAND = 'npx @sentry/agent-plugin install'; - export function HomeAiSetupCard() { - const [copied, setCopied] = useState(false); - const {emit} = usePlausibleEvent(); - - const copyCommand = useCallback(async () => { - emit('Copy AI Prompt', { - props: {page: window.location.pathname, title: 'Homepage Setup Card'}, - }); - - try { - await navigator.clipboard.writeText(INSTALL_COMMAND); - setCopied(true); - DocMetrics.copyAIPrompt(window.location.pathname, undefined, true, 'homepage_card'); - setTimeout(() => setCopied(false), 1500); - } catch (error) { - Sentry.logger.warn('clipboard.writeText failed', { - error: (error as Error)?.message, - errorName: (error as Error)?.name, - }); - DocMetrics.copyAIPrompt( - window.location.pathname, - undefined, - false, - 'homepage_card' - ); - setCopied(false); - } - }, [emit]); - return ( -
      -
      - - - - -
      -

      Set up with a coding agent

      - -
      -

      - One command teaches Claude Code, Cursor, Codex, and Grok how to install and - configure Sentry for you.{' '} - - Read about the agent plugin - - . -

      -

      - Use Sentry without leaving your agent conversations by setting up the{' '} - - Sentry MCP server - {' '} - and{' '} - - Sentry CLI - - . -

      + +
      +
      + + + + +
      +

      Set up with Sentry CLI

      +
      + +
      +
      +

      + + Learn more about the Sentry CLI + +

      +
      -
      + + ); } diff --git a/src/components/linkWithPlatformIcon.tsx b/src/components/linkWithPlatformIcon.tsx index b44627ba812f1..0413c14e81187 100644 --- a/src/components/linkWithPlatformIcon.tsx +++ b/src/components/linkWithPlatformIcon.tsx @@ -5,7 +5,7 @@ import {SmartLink} from './smartLink'; type Props = { label?: string; platform?: string; - /** Agent skill name, e.g. "sentry-react-sdk". When provided, renders an inline "Agent Setup" copy-prompt button. */ + /** Agent skill name, e.g. "sentry-react-sdk". When provided, renders an inline Sentry CLI setup button. */ skill?: string; url?: string; }; diff --git a/src/components/migrationGuide/index.tsx b/src/components/migrationGuide/index.tsx index 1f46b98d4ed71..f4c9f1ba1083e 100644 --- a/src/components/migrationGuide/index.tsx +++ b/src/components/migrationGuide/index.tsx @@ -16,8 +16,10 @@ const MIGRATIONS = { 'dotnet-v7': {storagePrefix: 'sentry-dotnet-v7-migration', platform: 'dotnet'}, } as const; -// Share the MDX component map across item bodies and platform pages. -const components = mdxComponents(); +// Share the MDX component map across item bodies and platform pages. Built on first +// use rather than at import time: `mdxComponents` imports this module, so calling it +// while that import cycle is still resolving can read components that aren't loaded yet. +let components: ReturnType | undefined; // `getMDXComponent` compiles its source with `new Function`, so the same item // body is compiled once instead of once per page it appears on. Keyed by source, @@ -30,6 +32,7 @@ function ItemBody({mdxSource}: {mdxSource: string}) { MDXLayout = getMDXComponent(mdxSource); componentBySource.set(mdxSource, MDXLayout); } + components ??= mdxComponents(); return ; } diff --git a/src/components/platformContent.tsx b/src/components/platformContent.tsx index a4fa773303f60..4a6402165f00d 100644 --- a/src/components/platformContent.tsx +++ b/src/components/platformContent.tsx @@ -12,6 +12,7 @@ import { VERSION_INDICATOR, } from 'sentry-docs/versioning'; +import {FrameworkContent} from './frameworkSelector'; import {Include} from './include'; type Props = { @@ -20,6 +21,11 @@ type Props = { fallbackPlatform?: string; noGuides?: boolean; platform?: string; + /** + * Allow this content to be swapped client-side for another guide's version + * when rendered inside a ``. + */ + switchable?: boolean; }; const updatePathIfVersionedFileDoesNotExist = (path: string): string => { @@ -52,9 +58,33 @@ function MDXLayoutRenderer({mdxSource: source, ...rest}) { return ; } -export async function PlatformContent({includePath, platform, noGuides}: Props) { +export async function PlatformContent({ + includePath, + platform, + noGuides, + switchable, +}: Props) { const {path} = serverContext(); + const doc = await resolvePlatformContent({includePath, path, platform, noGuides}); + const content = doc ? : null; + if (switchable) { + return {content}; + } + + return content; +} + +/** + * Returns the `platform-includes//` file for the page at `path`: the file of the + * guide, its `fallbackGuide`, the platform, its `fallbackPlatform`, or `_default`, in this order. + */ +export async function resolvePlatformContent({ + includePath, + path, + platform, + noGuides, +}: Pick & {path: string[]}) { if (!platform) { if (path.length < 2 || path[0] !== 'platforms') { return null; @@ -136,8 +166,7 @@ export async function PlatformContent({includePath, platform, noGuides}: Props) } } - const {mdxSource} = doc; - return ; + return doc; } const mdxComponentsWithWrapper = mdxComponents({Include, PlatformContent}); diff --git a/src/components/platformFilter/client.tsx b/src/components/platformFilter/client.tsx index f9cc8274d8f9a..c18fbf266a0ed 100644 --- a/src/components/platformFilter/client.tsx +++ b/src/components/platformFilter/client.tsx @@ -4,11 +4,12 @@ import {TriangleRightIcon} from '@radix-ui/react-icons'; import classNames from 'classnames'; import {matchSorter, rankings} from 'match-sorter'; import Link from 'next/link'; -import {useMemo, useState} from 'react'; +import {Fragment, useMemo, useState} from 'react'; import {type Platform} from 'sentry-docs/types'; import {splitToChunks, uniqByReference} from 'sentry-docs/utils'; import {PlatformIcon} from '../platformIcon'; +import {guideGroupTitle, sortRuntimesFirst} from '../platformSelector/guideGroups'; import styles from './style.module.scss'; export function PlatformFilterClient({platforms}: {platforms: Platform[]}) { @@ -101,6 +102,7 @@ export function PlatformFilterClient({platforms}: {platforms: Platform[]}) { matchKeys={matchKeys} // force expand if the filter is long enough to have few results forceExpand={filter.length >= 2} + showGuideGroups={filter === ''} /> ) )} @@ -119,10 +121,13 @@ function PlatformWithGuides({ platform, forceExpand, matchKeys, + showGuideGroups, }: { forceExpand: boolean; matchKeys: string[]; platform: Platform; + /** Lists the runtime guides first and shows titles above them and the guides after them. */ + showGuideGroups: boolean; }) { const [expanded, setExpanded] = useState(false); @@ -133,10 +138,14 @@ function PlatformWithGuides({ // In this case, we do not need to add the platform to the list of guides const hasGuideWithPlatformKey = platform.guides.some(g => g.key === platform.key); - return showPlatformInContent && !hasGuideWithPlatformKey - ? [platform, ...platform.guides] - : platform.guides; - }, [matchKeys, platform]); + const platformAndGuides = + showPlatformInContent && !hasGuideWithPlatformKey + ? [platform, ...platform.guides] + : platform.guides; + return showGuideGroups + ? sortRuntimesFirst(platform.key, platformAndGuides) + : platformAndGuides; + }, [matchKeys, platform, showGuideGroups]); return ( = 8 || platform.integrations.length >= 8} > - {guides.map((guide, i) => ( - -
      - - {guide.title} -
      - - ))} + {guides.map((guide, i) => { + const groupTitle = showGuideGroups && guideGroupTitle(platform.key, guides, i); + return ( + + {groupTitle &&
      {groupTitle}
      } + +
      + + {guide.title} +
      + +
      + ); + })} {platform.guides.length === 0 && platform.integrations.map((integ, i) => { return ( diff --git a/src/components/platformFilter/style.module.scss b/src/components/platformFilter/style.module.scss index 00186fbdef9cb..75ad8bb45543d 100644 --- a/src/components/platformFilter/style.module.scss +++ b/src/components/platformFilter/style.module.scss @@ -149,6 +149,15 @@ } } +.GuideGroupTitle { + padding: 0.75rem 0.5rem 0.25rem 1.5rem; + font-size: 0.75rem; + font-weight: 500; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--foreground-secondary); +} + .PlatformIcon { width: 20px; height: 20px; diff --git a/src/components/platformIcon.tsx b/src/components/platformIcon.tsx index 132b094e3b550..3e09dc006a42c 100644 --- a/src/components/platformIcon.tsx +++ b/src/components/platformIcon.tsx @@ -76,6 +76,7 @@ import Html5SVG from 'platformicons/svg/HTML5.svg'; import HttpxSVG from 'platformicons/svg/httpx.svg'; import HueySVG from 'platformicons/svg/huey.svg'; import HuggingfaceSVG from 'platformicons/svg/huggingface.svg'; +import HydrogenSVG from 'platformicons/svg/hydrogen.svg'; import IonicSVG from 'platformicons/svg/ionic.svg'; import IrisSVG from 'platformicons/svg/iris.svg'; import JavaSVG from 'platformicons/svg/java.svg'; @@ -235,6 +236,7 @@ import Html5SVGLarge from 'platformicons/svg_80x80/HTML5.svg'; import HttpxSVGLarge from 'platformicons/svg_80x80/httpx.svg'; import HueySVGLarge from 'platformicons/svg_80x80/huey.svg'; import HuggingfaceSVGLarge from 'platformicons/svg_80x80/huggingface.svg'; +import HydrogenSVGLarge from 'platformicons/svg_80x80/hydrogen.svg'; import IonicSVGLarge from 'platformicons/svg_80x80/ionic.svg'; import IrisSVGLarge from 'platformicons/svg_80x80/iris.svg'; import JavaSVGLarge from 'platformicons/svg_80x80/java.svg'; @@ -672,6 +674,10 @@ const formatToSVG = { sm: HonoSVG, lg: HonoSVGLarge, }, + hydrogen: { + sm: HydrogenSVG, + lg: HydrogenSVGLarge, + }, kotlin: { sm: KotlinSVG, lg: KotlinSVGLarge, @@ -987,6 +993,7 @@ export const PLATFORM_TO_ICON = { android: 'android', anthropic: 'anthropic', apple: 'apple', + aws: 'aws', capacitor: 'capacitor', clojure: 'clojure', cocoa: 'apple', @@ -1076,6 +1083,7 @@ export const PLATFORM_TO_ICON = { 'javascript-ionic': 'ionic', 'javascript-hapi': 'hapi', 'javascript-hono': 'hono', + 'javascript-hydrogen': 'hydrogen', 'javascript-eve': 'eve', 'javascript-firebase': 'firebase', 'javascript-flue': 'flue', @@ -1132,6 +1140,7 @@ export const PLATFORM_TO_ICON = { 'python-gcp-functions': 'gcp-functions', 'python-anthropic': 'anthropic', 'python-beam': 'apache-beam', + 'python-bedrock': 'aws', 'python-boto3': 'aws', 'python-bottle': 'bottle', 'python-celery': 'celery', diff --git a/src/components/platformSelector/guideGroups.spec.ts b/src/components/platformSelector/guideGroups.spec.ts new file mode 100644 index 0000000000000..783be8eeb99a6 --- /dev/null +++ b/src/components/platformSelector/guideGroups.spec.ts @@ -0,0 +1,70 @@ +import {describe, expect, it} from 'vitest'; + +import {guideGroupTitle, sortRuntimesFirst} from './guideGroups'; + +const guides = (...keys: string[]) => keys.map(key => ({key})); +const keys = (list: Array<{key: string}>) => list.map(g => g.key); + +describe('sortRuntimesFirst', () => { + it('lists the runtime guides first, in their configured order', () => { + const sorted = sortRuntimesFirst( + 'javascript', + guides( + 'javascript', + 'javascript.angular', + 'javascript.bun', + 'javascript.cloudflare', + 'javascript.deno', + 'javascript.nextjs', + 'javascript.node' + ) + ); + expect(keys(sorted)).toEqual([ + 'javascript', + 'javascript.node', + 'javascript.bun', + 'javascript.deno', + 'javascript.cloudflare', + 'javascript.angular', + 'javascript.nextjs', + ]); + }); + + it('skips runtime guides that are not in the list', () => { + const sorted = sortRuntimesFirst( + 'javascript', + guides('javascript.angular', 'javascript.bun') + ); + expect(keys(sorted)).toEqual(['javascript.bun', 'javascript.angular']); + }); + + it('keeps the order of platforms without runtime guides', () => { + const list = guides('python.django', 'python.aiohttp'); + expect(sortRuntimesFirst('python', list)).toBe(list); + }); +}); + +describe('guideGroupTitle', () => { + const sorted = guides('javascript', 'javascript.node', 'javascript.angular'); + + it('returns "Runtimes" for the first runtime guide', () => { + expect(guideGroupTitle('javascript', sorted, 0)).toBe('Runtimes'); + expect(guideGroupTitle('javascript', sorted, 1)).toBeUndefined(); + }); + + it('returns "Frameworks and more" for the first guide after the runtimes', () => { + expect(guideGroupTitle('javascript', sorted, 2)).toBe('Frameworks and more'); + }); + + it('returns no titles for platforms without runtime guides', () => { + const list = guides('python.django', 'python.aiohttp'); + expect(guideGroupTitle('python', list, 0)).toBeUndefined(); + expect(guideGroupTitle('python', list, 1)).toBeUndefined(); + }); + + it('returns no title for a list that only has other guides', () => { + expect( + guideGroupTitle('javascript', guides('javascript.angular'), 0) + ).toBeUndefined(); + }); +}); diff --git a/src/components/platformSelector/guideGroups.ts b/src/components/platformSelector/guideGroups.ts new file mode 100644 index 0000000000000..a4b6bf42eb023 --- /dev/null +++ b/src/components/platformSelector/guideGroups.ts @@ -0,0 +1,49 @@ +/** + * Guide keys per platform that the platform selector and the platform grid list first, + * in this order, under the "Runtimes" title. The other guides of the platform follow under "Frameworks and more". + */ +export const RUNTIME_GUIDE_KEYS: Record = { + javascript: [ + 'javascript', + 'javascript.node', + 'javascript.bun', + 'javascript.deno', + 'javascript.cloudflare', + ], +}; + +const isRuntimeGuide = (platformKey: string, guideKey: string) => + RUNTIME_GUIDE_KEYS[platformKey]?.includes(guideKey) ?? false; + +/** + * Returns the guides with the platform's runtime guides first, in the order of + * `RUNTIME_GUIDE_KEYS`, followed by the other guides in their original order. + */ +export function sortRuntimesFirst( + platformKey: string, + guides: T[] +): T[] { + const runtimeKeys = RUNTIME_GUIDE_KEYS[platformKey]; + if (!runtimeKeys) { + return guides; + } + const runtimes = runtimeKeys.flatMap(key => guides.filter(g => g.key === key)); + return [...runtimes, ...guides.filter(g => !runtimeKeys.includes(g.key))]; +} + +/** + * Returns the group title to show above `guides[index]`, or `undefined` if the guide + * doesn't start a group. Expects the guides in the order of `sortRuntimesFirst`. + */ +export function guideGroupTitle( + platformKey: string, + guides: Array<{key: string}>, + index: number +): string | undefined { + const isRuntime = isRuntimeGuide(platformKey, guides[index].key); + if (index === 0) { + return isRuntime ? 'Runtimes' : undefined; + } + const followsRuntime = isRuntimeGuide(platformKey, guides[index - 1].key); + return !isRuntime && followsRuntime ? 'Frameworks and more' : undefined; +} diff --git a/src/components/platformSelector/index.tsx b/src/components/platformSelector/index.tsx index 7c9354b872b44..090fa2cd6de2a 100644 --- a/src/components/platformSelector/index.tsx +++ b/src/components/platformSelector/index.tsx @@ -25,6 +25,7 @@ import {Platform, PlatformGuide, PlatformIntegration} from 'sentry-docs/types'; import {isLocalStorageAvailable, uniqByReference} from 'sentry-docs/utils'; import {SidebarLink, SidebarSeparator} from '../sidebar/sidebarLink'; +import {guideGroupTitle, sortRuntimesFirst} from './guideGroups'; import {resolveSamePageUrl} from './samePageUrl'; import styles from './style.module.scss'; @@ -104,7 +105,7 @@ export function PlatformSelector({ ) .map(platform => [ platform, - ...platform.guides.map(guide => ({ + ...sortRuntimesFirst(platform.key, platform.guides).map(guide => ({ ...guide, // add a reference to the parent platform instead of its key platform, @@ -298,6 +299,7 @@ export function PlatformSelector({ activeItemKey={currentPlatformKey} onPlatformExpand={onToggleExpand} dropdownStyle={dropdownStyle} + showGuideGroups={searchValue === ''} listOnly /> ))} @@ -402,6 +404,7 @@ export function PlatformSelector({ activeItemKey={currentPlatformKey} onPlatformExpand={onToggleExpand} dropdownStyle={dropdownStyle} + showGuideGroups={searchValue === ''} listOnly={false} /> ); @@ -435,6 +438,8 @@ type PlatformItemProps = { dropdownStyle?: boolean; listOnly?: boolean; onPlatformExpand?: (platformKey: string) => void; + /** Shows titles above the runtime guides and the guides after them. */ + showGuideGroups?: boolean; }; function PlatformItem({ platform, @@ -443,6 +448,7 @@ function PlatformItem({ onPlatformExpand: onExpand, dropdownStyle = false, listOnly = false, + showGuideGroups = false, }: PlatformItemProps) { const showCaret = (p: Platform) => p.guides.length > 0 || p.integrations.length > 0; @@ -461,6 +467,15 @@ function PlatformItem({ ? markLastGuide(platform.guides.length > 0 ? platform.guides : platform.integrations) : []; + const groupTitle = (index: number) => { + const title = showGuideGroups && guideGroupTitle(platform.key, guides, index); + return title ? ( + + ) : null; + }; + if (listOnly) { return ( @@ -508,13 +523,11 @@ function PlatformItem({ )}
      - {guides.map(guide => ( - + {guides.map((guide, i) => ( + + {groupTitle(i)} + + ))} ); @@ -568,9 +581,12 @@ function PlatformItem({ - {guides.map(guide => { - return ; - })} + {guides.map((guide, i) => ( + + {groupTitle(i)} + + + ))} ); } diff --git a/src/components/platformSelector/style.module.scss b/src/components/platformSelector/style.module.scss index a985a568009b1..17383728b6a66 100644 --- a/src/components/platformSelector/style.module.scss +++ b/src/components/platformSelector/style.module.scss @@ -228,6 +228,16 @@ height: 80%; } +.guide-group-title { + margin-left: 1.5rem; + padding: 0.75rem 0.5rem 0.25rem; + font-size: 0.75rem; + font-weight: 500; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--foreground-secondary); +} + .item-indicator { position: absolute; left: 0.375rem; diff --git a/src/components/runtimeLinks.spec.ts b/src/components/runtimeLinks.spec.ts new file mode 100644 index 0000000000000..0989ac44cbca0 --- /dev/null +++ b/src/components/runtimeLinks.spec.ts @@ -0,0 +1,70 @@ +import {describe, expect, it} from 'vitest'; + +import {getQuickStartTitle, getRuntimeLinks} from './runtimeLinks'; + +const G = 'platforms/javascript/guides'; + +type Page = {children: Page[]; frontmatter: {runtime?: string}; path: string}; + +const page = (path: string, runtime?: string, children: Page[] = []): Page => ({ + path, + frontmatter: runtime ? {runtime} : {}, + children, +}); + +const piDurable = page(`${G}/pi-durable`, 'node', [ + page(`${G}/pi-durable/cloudflare`, 'cloudflare'), + page(`${G}/pi-durable/deno`, 'deno'), + page(`${G}/pi-durable/bun`, 'bun'), + page(`${G}/pi-durable/configuration`), +]); + +const path = (p: string) => p.split('/'); + +describe('getRuntimeLinks', () => { + it('links the guide page and its child pages with a runtime, in doc tree order', () => { + expect(getRuntimeLinks(piDurable, path(`${G}/pi-durable`))?.map(l => l.url)).toEqual([ + `/${G}/pi-durable/`, + `/${G}/pi-durable/cloudflare/`, + `/${G}/pi-durable/deno/`, + `/${G}/pi-durable/bun/`, + ]); + }); + + it('selects the runtime of the current page', () => { + const selected = (p: string) => + getRuntimeLinks(piDurable, path(p)) + ?.filter(l => l.selected) + .map(l => l.runtime); + + expect(selected(`${G}/pi-durable`)).toEqual(['node']); + expect(selected(`${G}/pi-durable/deno`)).toEqual(['deno']); + expect(selected(`${G}/pi-durable/configuration/options`)).toEqual([]); + }); + + it('returns null for a guide with quick starts for fewer than two runtimes', () => { + expect(getRuntimeLinks(page(`${G}/node`, 'node'), path(`${G}/node`))).toBeNull(); + expect(getRuntimeLinks(page(`${G}/eve`), path(`${G}/eve`))).toBeNull(); + expect(getRuntimeLinks(undefined, path('product/agents'))).toBeNull(); + }); +}); + +describe('getQuickStartTitle', () => { + it('names the runtime of the guide page if the guide has quick starts for more runtimes', () => { + expect(getQuickStartTitle(piDurable)).toBe('Quick Start (Node.js)'); + }); + + it('returns "Quick Start" for a guide with quick starts for fewer than two runtimes', () => { + expect(getQuickStartTitle(page(`${G}/node`, 'node'))).toBe('Quick Start'); + expect(getQuickStartTitle(page(`${G}/eve`))).toBe('Quick Start'); + expect(getQuickStartTitle(undefined)).toBe('Quick Start'); + }); + + it('returns "Quick Start" if only the child pages set a runtime', () => { + const hono = page(`${G}/hono`, undefined, [ + page(`${G}/hono/cloudflare`, 'cloudflare'), + page(`${G}/hono/bun`, 'bun'), + ]); + expect(getQuickStartTitle(hono)).toBe('Quick Start'); + }); +}); diff --git a/src/components/runtimeLinks.ts b/src/components/runtimeLinks.ts new file mode 100644 index 0000000000000..d2c448466c00d --- /dev/null +++ b/src/components/runtimeLinks.ts @@ -0,0 +1,61 @@ +const RUNTIME_TITLES: Record = { + node: 'Node.js', + cloudflare: 'Cloudflare', + deno: 'Deno', + bun: 'Bun', +}; + +export type RuntimeLink = { + runtime: string; + selected: boolean; + title: string; + url: string; +}; + +type QuickStartNode = { + frontmatter: {runtime?: string}; + path: string; + children?: QuickStartNode[]; +}; + +/** + * Returns the links to the quick starts of `guide`: the guide page and its child pages that + * set `runtime` in their frontmatter, in doc tree order. The page at `path` is selected. + * Returns `null` if the guide has quick starts for fewer than two runtimes. + */ +export function getRuntimeLinks( + guide: QuickStartNode | undefined, + path: string[] +): RuntimeLink[] | null { + if (!guide) { + return null; + } + + const current = path.join('/'); + const links = [guide, ...(guide.children ?? [])].flatMap(page => { + const runtime = page.frontmatter.runtime; + return runtime + ? [ + { + runtime, + selected: page.path === current, + title: RUNTIME_TITLES[runtime] ?? runtime, + url: `/${page.path}/`, + }, + ] + : []; + }); + return links.length < 2 ? null : links; +} + +/** + * Returns the sidebar title of the guide page of `guide`: "Quick Start", or + * "Quick Start ()", for example "Quick Start (Node.js)", if the guide has quick + * starts for more than one runtime. + */ +export function getQuickStartTitle(guide: QuickStartNode | undefined): string { + const runtime = getRuntimeLinks(guide, [])?.find( + link => link.url === `/${guide?.path}/` + )?.title; + return runtime ? `Quick Start (${runtime})` : 'Quick Start'; +} diff --git a/src/components/runtimeSelector.tsx b/src/components/runtimeSelector.tsx new file mode 100644 index 0000000000000..e03e6cb2fa50d --- /dev/null +++ b/src/components/runtimeSelector.tsx @@ -0,0 +1,66 @@ +import {Button} from '@radix-ui/themes'; +import Link from 'next/link'; +import {nodeForPath} from 'sentry-docs/docTree'; +import {serverContext} from 'sentry-docs/serverContext'; + +import {PlatformIcon} from './platformIcon'; +import {getRuntimeLinks} from './runtimeLinks'; + +/** + * Links the quick starts of the current guide for each runtime: the guide page and its child + * pages that set `runtime` in their frontmatter. `DocPage` renders it on each page that sets + * `runtime`. The links are plain anchors, so they are also in the page's Markdown export for + * AI agents. + */ +export function RuntimeSelector() { + const {rootNode, path} = serverContext(); + const links = getRuntimeLinks(nodeForPath(rootNode, path.slice(0, 4)), path); + if (!links) { + return null; + } + + return ( + + ); +} diff --git a/src/components/sidebar/dynamicNav.tsx b/src/components/sidebar/dynamicNav.tsx index 11ca96b607909..7ab25c73fb834 100644 --- a/src/components/sidebar/dynamicNav.tsx +++ b/src/components/sidebar/dynamicNav.tsx @@ -290,6 +290,8 @@ type Props = { collapsible?: boolean; exclude?: string[]; extraLinks?: ExternalSidebarLink[]; + /** The title of the link to the `root` page in a platform sidebar. */ + quickStartTitle?: string; title?: string; }; @@ -300,6 +302,7 @@ export function DynamicNav({ collapsible = false, exclude = [], extraLinks, + quickStartTitle = 'Quick Start', }: Props) { if (root.startsWith('/')) { root = root.substring(1); @@ -363,7 +366,7 @@ export function DynamicNav({ {isPlatformSidebar && (
    ); diff --git a/src/mdxComponents.ts b/src/mdxComponents.ts index 13d823b180d63..85c9d6dad9b5a 100644 --- a/src/mdxComponents.ts +++ b/src/mdxComponents.ts @@ -12,6 +12,7 @@ import {CommunitySupportedPlatforms} from './components/communitySupportedPlatfo import {ConfigKey} from './components/configKey'; import {ConfigValue} from './components/configValue'; import {ContentSeparator} from './components/contentSeparator'; +import {ConventionAttributes} from './components/conventionAttributes'; import {CopyableCard} from './components/copyableCard'; import {CreateGitHubAppForm} from './components/createGitHubAppForm'; import {DefinitionList} from './components/definitionList'; @@ -19,6 +20,7 @@ import {DevDocsCardGrid} from './components/devDocsCardGrid'; import DocImage from './components/docImage'; import {Expandable} from './components/expandable'; import {FeatureBadge} from './components/featureBadge'; +import {FrameworkSelector} from './components/frameworkSelector'; import {GitHubCodePreview} from './components/githubCodePreview'; import {GitHubDomainChecker} from './components/githubDomainChecker'; import {GradleFeatureConfig} from './components/gradleFeatureConfig'; @@ -82,6 +84,7 @@ export function mdxComponents( CliChecksumTable, CommunitySupportedPlatforms, ContentSeparator, + ConventionAttributes, DevDocsCardGrid, PlatformFilter, CodeBlock, @@ -99,6 +102,7 @@ export function mdxComponents( DefinitionList, Expandable, FeatureBadge, + FrameworkSelector, GuideGrid, IntegrationGrid, IntegrationListItem, diff --git a/src/metrics.ts b/src/metrics.ts index 85adb812369aa..f319dc49442fb 100644 --- a/src/metrics.ts +++ b/src/metrics.ts @@ -171,7 +171,7 @@ export const DocMetrics = { }, /** - * Track "Copy Prompt" button clicks in the Agent Setup Callout + * Track Sentry CLI setup copies from the callout, homepage card, and inline buttons * @param pathname - Page where the prompt was copied * @param skill - Skill name if present (e.g., "sentry-nextjs-sdk") * @param success - Whether the clipboard copy succeeded diff --git a/src/types/frontmatter.ts b/src/types/frontmatter.ts index fd9a5557eef19..47943ef95f842 100644 --- a/src/types/frontmatter.ts +++ b/src/types/frontmatter.ts @@ -97,6 +97,12 @@ export interface FrontMatter { */ previousPage?: PaginationNavNode; + /** + * The runtime of a quick start, for example `node` or `cloudflare`. The page then shows a + * runtime selector that links the quick starts of the same guide for the other runtimes. + */ + runtime?: string; + /** * Set this to true to show a separator/divider below this item in the sidebar * @deprecated Use sidebar_section instead diff --git a/vitest.config.mjs b/vitest.config.mjs index 836de9fb7e92f..9677c5df2ca28 100644 --- a/vitest.config.mjs +++ b/vitest.config.mjs @@ -4,4 +4,7 @@ import {defineConfig} from 'vitest/config'; export default defineConfig({ plugins: [tsconfigPaths()], + esbuild: { + jsx: 'automatic', + }, });