Skip to content

Commit

Permalink
Updated backend tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
antonpirker committed Jul 26, 2024
1 parent baf837d commit c00d2fc
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 72 deletions.
45 changes: 30 additions & 15 deletions docs/product/sentry-basics/integrate-backend/capturing-errors.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ If you're using your own source code, follow the instructions in [Getting Starte

## Unhandled Errors

The Sentry SDK will automatically capture and report any _unhandled error_ that happens in your application runtime without any additional configuration or explicit handling. Generally, unhandled errors are errors that aren't caught by any except (or try/catch) clause.
The Sentry SDK will automatically capture and report any _unhandled error_ that happens in your application runtime without any additional configuration or explicit handling. Generally, unhandled errors are errors that aren't caught by any `try/except` clause.

1. In your browser, launch the local Django app in the following endpoint to trigger an unhandled error: `http://localhost:8000/unhandled`.
1. Run the local Django app.

2. Point your browser to `http://localhost:8000/unhandled` to trigger an unhandled error.

2. If you've set up an alert rule, you should be notified about the error. Otherwise, open the **Issues** page in your Sentry account.

Expand Down Expand Up @@ -44,13 +46,23 @@ The Sentry SDK contains several methods that you can use to **explicitly** repor

1. Open the `views.py` file. Notice that we import `sentry_sdk` lib which contains the `capture_exception` method:

```python
import sentry_sdk
```python {filename: myapp/views.py}
import sentry_sdk
```

2. The method is used to capture the exception handled by the except clause in `HandledErrorView`:

![Import and Configure SDK](./img/capture_exception.png)
```python {filename: myapp/views.py}
class HandledErrorView(APIView):
def get(self, request):
...
try:
'2' + 2
except Exception as err:
sentry_sdk.capture_exception(err)

return Response()
```

3. To try it out on your localhost, trigger the following endpoint: `http://localhost:8000/handled`.

Expand All @@ -70,22 +82,26 @@ Typically, `capture_message` is not emitted, but there are times when a develope

2. You can use it anywhere within your app. In our example, we've created a dedicated view class, `CaptureMessageView`, to trigger and capture a message we want to track:

```Python
sentry_sdk.capture_message("You caught me!")
```python {filename: myapp/views.py}
sentry_sdk.capture_message("You caught me!")
```

3. To try it out on your localhost, trigger the following endpoint: `http://localhost:8000/message`.

4. As before, open the new issue’s detail page from the **Issues** page.
<Alert level="info">
**Note:** You need to remove the `"issue.priority is high or medium"` filter from issue's page "Custom Search" field to see the messages in the issues list.
</Alert>


![Import and Configure SDK](./img/capture_message.png)

> By default captured messages are marked with a severity level tag `level:info`, as reflected in the tags section. However, the `capture_message` methods accept an **optional** severity level parameter.

5. In the `views.py` file, change the `capture_message` method to:

```Python
sentry_sdk.capture_message("You caught me!", "fatal")
```python {filename: myapp/views.py}
sentry_sdk.capture_message("You caught me!", "fatal")
```

6. Save the changes and trigger the `/message` endpoint again. Changes should be applied immediately through `StateReloader`.
Expand All @@ -102,13 +118,12 @@ To enrich the data of the message events we've captured with `capture_message`:

2. Replace that line with the following code:

```Python
with sentry_sdk.push_scope() as scope:
scope.set_tag("my-tag", "my value")
scope.user = { "email" : "[email protected]" }
scope.set_extra("someVariable", "some data")
```python {filename: myapp/views.py}
sentry_sdk.set_tag("my-tag", "my value")
sentry_sdk.user = { "email" : "[email protected]" }
sentry_sdk.set_extra("someVariable", "some data")

sentry_sdk.capture_message("You caught me!", "fatal")
sentry_sdk.capture_message("You caught me!", "fatal")
```

> We're using the `push_scope` method that allows us to send data with one specific event on a local scope. We're setting a custom tag, user context attribute (email), and extra data on the local scope to enrich the data on the message event.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ To set up the release in this project:

1. Open the file `settings.py`. Notice that we add the `release` configuration option when initializing the SDK:

```python
release=os.environ.get("VERSION"),
```python {filename: myproject/settings.py}
sentry_sdk.init(
...
release=os.environ.get("VERSION"),
...
)
```

2. Open the `Makefile` you ran in the previous tutorial.
Expand All @@ -26,23 +30,23 @@ To set up the release in this project:

3. Notice that we're setting the release version name as an environment variable that is then used in the application's runtime. We're letting the CLI propose a release version name, but you'd probably want to apply your naming conventions:

```bash
```Makefile {filename: Makefile}
VERSION=`sentry-cli releases propose-version`
```

4. Then we create the new release for our project with the proposed or selected name.

```bash
> create_release:
sentry-cli releases -o $(SENTRY_ORG) new -p $(SENTRY_PROJECT) $(VERSION)
```Makefile {filename: Makefile}
create_release:
sentry-cli releases -o $(SENTRY_ORG) new -p $(SENTRY_PROJECT) $(VERSION)
```

5. In the previous tutorial, we configured the GitHub integration and added the code repository for commit tracking. Now we can associate commits from that repository to the new release by running the command:

```bash
> associate_commits:
sentry-cli releases -o $(SENTRY_ORG) -p $(SENTRY_PROJECT) \
set-commits $(VERSION) --auto
```Makefile {filename: Makefile}
associate_commits:
sentry-cli releases -o $(SENTRY_ORG) -p $(SENTRY_PROJECT) \
set-commits $(VERSION) --auto
```

## Breadcrumbs
Expand All @@ -53,19 +57,19 @@ To add breadcrumbs to our app:

1. Open the file `myapp > view.py`.

2. Notice we import `add_breadcrumb` from the SDK lib.
2. Notice that we import `sentry_sdk` lib which contains the `add_breadcrumb` method:

```python
from sentry_sdk import add_breadcrumb
```python {filename: myapp/views.py}
import sentry_sdk
```

3. We create a custom breadcrumb for each method handler in the view classes. This breadcrumb will be added to the trail of breadcrumbs associated with any error triggered through these method call flows. For instance, under `HandledErrorView:get`:
3. We create a custom breadcrumb for each method handler in the view classes. This breadcrumb will be added to the trail of breadcrumbs associated with any error triggered through these method call flows. For instance, under `HandledErrorView.get`:

```python
add_breadcrumb(
category='URL Endpoints',
message='In the handled function',
level='info',
```python {filename: myapp/views.py}
sentry_sdk.add_breadcrumb(
category='URL Endpoints',
message='In the handled function',
level='info',
)
```

Expand All @@ -77,11 +81,15 @@ _Environment_ is a powerful configuration option that enables developers using S

2. Notice that we initialize the SDK with the `environment` configuration option. Any event that's subsequently captured by the SDK will be tagged with the configured environment value.

```python
environment:"Production"
```python {filename: myproject/settings.py}
sentry_sdk.init(
...
environment="Production"
...
)
```

> Environment values are freeform strings. Neither the Sentry SDK nor [sentry.io](https://sentry.io) will not limit you to any specific value or format. In this example, we hardcoded the value. In a real-life app, the value would probably be determined dynamically through a properties file, system, or environment variable.
> Environment values are freeform strings. Neither the Sentry SDK nor [sentry.io](https://sentry.io) will limit you to any specific value or format. In this example, we hardcoded the value. In a real-life app, the value would probably be determined dynamically through a properties file, system, or environment variable.

## Next

Expand Down
58 changes: 23 additions & 35 deletions docs/product/sentry-basics/integrate-backend/getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ If you're using your own source code, you can skip this tutorial and either:
1. The demo app source code requires a Python development environment to build, install, and run the application. Make sure that you have the following in place:

- A source code editor (like [VS-Code](https://code.visualstudio.com))
- [Python3](https://www.python.org/download/releases/3.0/)
- [Python](https://www.python.org/)
- [Sentry-CLI](/product/cli/)
- [NPM](https://www.npmjs.com/)

2. To start monitoring errors in your application you'll need to create a new project in your Sentry account. Check out our [frontend tutorial](/guides/integrate-frontend/create-new-project/) to learn more about how to create a project and define alert rules.

Expand Down Expand Up @@ -56,78 +55,67 @@ Sentry captures data by using a platform-specific SDK within your application ru

1. To start working with the SDK in our Django app, we install the `sentry-sdk` by defining the dependency in the `requirements.txt` file. The SDK documentation and release information are available in the [Sentry SDK](https://github.com/getsentry/sentry-python) GitHub repository.

2. Open the `settings.py` file (located under `_./backend-monitoring/myproject/settings.py`). This is where we initialize and configure the Sentry SDK in our application.
2. Open the `settings.py` file (located under `./backend-monitoring/myproject/settings.py`). This is where we initialize and configure the Sentry SDK in our application.

3. After importing the Sentry SDK to the app, it is important to import the Sentry Django integration as well. Integrations extend the functionality of the SDK for some common frameworks and libraries.
3. In `settings.py` we import and initialize the Sentry SDK.

```python
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
```

4. In the Sentry SDK configuration, enter the `DSN` key value you copied from the project created in the [project creation tutorial](/guides/integrate-frontend/create-new-project/).
```python {filename: myproject/settings.py}
import sentry_sdk
```python
sentry_sdk.init(
dsn="YOUR_DSN",
integrations=[DjangoIntegration()],
dsn="YOUR_DSN", # replace with your DSN
...
)
```
> In `settings.py` replace `YOUR_DSN` with the `DSN` key value you copied from the project created in the [project creation tutorial](/guides/integrate-frontend/create-new-project/).


## Step 4: Install Dependencies and Run the Demo App

To build and run the demo application on your localhost:

1. Open a shell terminal and change directory to the `backend-monitoring` project root folder.

2. If you haven't installed Python3, do so by running the following:
2. If you haven't installed Python, do so by running the following:
```bash
brew install python3
brew install python
```
3. Install `virtualenv` and `virtualenvwrapper`:
3. Create a Python virtual environment in the project root.
```bash
pip3 install virtualenv virtualenvwrapper
echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc
exec bash
python -m venv .venv
```
4. Install Sentry's command-line tool to use release tracking and GitHub integration for commit data:
> You can name the virtual environment whatever you need for your project. In our case, we named it ".venv".
```bash
npm install -g @sentry/cli
```

5. Setup and activate a Python 3 virtual environment in the project root.
4. To activate the virtual environment, run:
```bash
mkvirtualenv --python=python3 sentry-demo-django
source .venv/bin/activate
```
> You can name the virtual environment whatever you need for your project. In our case, we named it "sentry-demo-django".

6. To activate the virtual environment, run:
5. Install Sentry's command-line tool to use release tracking and GitHub integration for commit data:

```bash
workon sentry-demo-django
python -m pip install "sentry-cli"
```

7. Open the `Makefile` included in the project's root folder. The file is used here to mimic a CI/CD flow.
6. Open the `Makefile` included in the project's root folder. The file is used here to mimic a CI/CD flow.
8. Follow the `deploy` target execution flow.
7. Follow the `deploy` target execution flow.
Notice that in addition to installing Python requirements and running the server, we also use the `sentry-cli` to create a new Sentry release, and associate commits to that release. Sentry will lookup through those commits when suggesting a suspect commit for your project issues.
Commands mentioned within the `Makefile` will be explained in detail in the next part of the tutorial, [Configuration Options](/product/sentry-basics/integrate-backend/configuration-options/).
9. To execute the `sentry-cli` commands, follow the instructions described [here](/product/sentry-basics/integrate-frontend/upload-source-maps/#step-1-prepare-the-build-environment) to obtain the values for your `SENTRY_AUTH_TOKEN`, `SENTRY_ORG`, and `SENTRY_PROJECT` environment variables.
8. To execute the `sentry-cli` commands, follow the instructions described [here](/product/sentry-basics/integrate-frontend/upload-source-maps/#step-1-prepare-the-build-environment) to obtain the values for your `SENTRY_AUTH_TOKEN`, `SENTRY_ORG`, and `SENTRY_PROJECT` environment variables.
![Makefile Config](./img/makefile_config.png)
> The sentry-cli can be configured by providing these values either through environment variables or through a dedicated configuration file. Learn more in [Sentry CLI > Configuration and Authentication](/product/cli/configuration/).
> The `sentry-cli` can be configured by providing these values either through environment variables or through a dedicated configuration file. Learn more in [Sentry CLI > Configuration and Authentication](/product/cli/configuration/).
10. Run the following command to install the required Python libraries, set up the Sentry Release, and run the Django server:
9. Run the following command to install the required Python libraries, set up the Sentry Release, and run the Django server:
```bash
make deploy
Expand Down
Binary file not shown.

0 comments on commit c00d2fc

Please sign in to comment.