Skip to content

Commit

Permalink
Merge pull request #34 from evo-company/fix-sentry-integration
Browse files Browse the repository at this point in the history
update sentry integrations
  • Loading branch information
n4mespace authored Feb 20, 2024
2 parents aab5625 + 67a62fe commit 6b316d8
Show file tree
Hide file tree
Showing 11 changed files with 91 additions and 46 deletions.
4 changes: 2 additions & 2 deletions featureflags/http/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ def create_app() -> FastAPI:
configure_lifecycle(app, container)

if config.sentry.enabled:
from featureflags.sentry import configure_sentry
from featureflags.sentry import configure_sentry, SentryMode

configure_sentry(config.sentry, env_prefix="http", app=app)
configure_sentry(config.sentry, env_prefix="http", mode=SentryMode.HTTP)

return app

Expand Down
12 changes: 10 additions & 2 deletions featureflags/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,16 @@ def configure_metrics(
)
instrumentator.instrument(
app=app,
latency_lowr_buckets=[0.001, 0.005, 0.01, 0.025, 0.05, 0.1,
0.25, 0.5],
latency_lowr_buckets=[
0.001,
0.005,
0.01,
0.025,
0.05,
0.1,
0.25,
0.5,
],
)
log.info("Http instrumentation initialized")

Expand Down
4 changes: 2 additions & 2 deletions featureflags/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
from datetime import datetime
from typing import Any, ClassVar

from featureflags.protobuf.graph_pb2 import Check as CheckProto
from featureflags.protobuf.graph_pb2 import Variable as VariableProto
from sqlalchemy import Index, Integer, UniqueConstraint
from sqlalchemy.dialects.postgresql import (
ARRAY,
Expand All @@ -17,6 +15,8 @@
from sqlalchemy.types import Boolean, Enum, String

from featureflags.graph.types import Action
from featureflags.protobuf.graph_pb2 import Check as CheckProto
from featureflags.protobuf.graph_pb2 import Variable as VariableProto
from featureflags.utils import ArrayOfEnum

metadata = MetaData()
Expand Down
6 changes: 4 additions & 2 deletions featureflags/rpc/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,11 @@ async def main() -> None:
set_internal_user_session()

if config.sentry.enabled:
from featureflags.sentry import configure_sentry
from featureflags.sentry import configure_sentry, SentryMode

configure_sentry(config.sentry, env_prefix="rpc")
configure_sentry(
config.sentry, env_prefix="rpc", mode=SentryMode.GRPC
)

server = await create_server()
stack.enter_context(graceful_exit([server])) # type: ignore
Expand Down
2 changes: 1 addition & 1 deletion featureflags/rpc/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
from uuid import UUID, uuid4

from aiopg.sa import SAConnection
from featureflags.protobuf import service_pb2
from sqlalchemy import and_, select
from sqlalchemy.dialects.postgresql import insert

from featureflags.models import Flag, Project, Variable, VariableType
from featureflags.protobuf import service_pb2
from featureflags.utils import EntityCache, FlagAggStats


Expand Down
2 changes: 1 addition & 1 deletion featureflags/rpc/servicer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import weakref

import aiopg.sa
from featureflags.protobuf import service_grpc, service_pb2
from google.protobuf.empty_pb2 import Empty
from grpclib.server import Stream
from hiku.engine import Engine
Expand All @@ -13,6 +12,7 @@
from featureflags.graph.graph import exec_graph
from featureflags.graph.proto_adapter import populate_result_proto
from featureflags.models import Project
from featureflags.protobuf import service_grpc, service_pb2
from featureflags.rpc.db import add_statistics
from featureflags.rpc.metrics import track
from featureflags.rpc.utils import debug_cancellation
Expand Down
60 changes: 38 additions & 22 deletions featureflags/sentry.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import logging

from fastapi import FastAPI
from enum import Enum

try:
import sentry_sdk
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
from sentry_sdk.integrations.asyncio import AsyncioIntegration
from sentry_sdk.integrations.atexit import AtexitIntegration
from sentry_sdk.integrations.dedupe import DedupeIntegration
from sentry_sdk.integrations.excepthook import ExcepthookIntegration
from sentry_sdk.integrations.fastapi import FastApiIntegration
from sentry_sdk.integrations.grpc import GRPCIntegration
from sentry_sdk.integrations.logging import LoggingIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
from sentry_sdk.integrations.starlette import StarletteIntegration
from sentry_sdk.integrations.stdlib import StdlibIntegration
from sentry_sdk.integrations.threading import ThreadingIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
except ImportError:
raise ImportError(
"`sentry_sdk` is not installed, please install it to use `sentry` "
Expand All @@ -26,17 +26,48 @@
log = logging.getLogger(__name__)


class SentryMode(Enum):
HTTP = "http"
GRPC = "grpc"


def configure_sentry(
config: SentrySettings,
env_prefix: str | None = None,
app: FastAPI | None = None,
mode: SentryMode = SentryMode.HTTP,
) -> None:
"""
Configure error logging to Sentry.
"""

env = f"{env_prefix}-{config.env}" if env_prefix else config.env

integrations = [
AsyncioIntegration(),
AtexitIntegration(),
ExcepthookIntegration(),
DedupeIntegration(),
StdlibIntegration(),
ThreadingIntegration(),
LoggingIntegration(),
SqlalchemyIntegration(),
]

match mode:
case mode.HTTP:
# Add FastApi specific integrations.
integrations.extend(
[
StarletteIntegration(transaction_style="endpoint"),
FastApiIntegration(transaction_style="endpoint"),
]
)
case mode.GRPC:
# Add gRPC specific integrations.
integrations.append(GRPCIntegration())
case _:
raise ValueError(f"{mode} option is not supported")

sentry_sdk.init(
dsn=config.dsn,
environment=env,
Expand All @@ -48,21 +79,6 @@ def configure_sentry(
max_breadcrumbs=1000,
enable_tracing=config.enable_tracing,
traces_sample_rate=config.traces_sample_rate,
integrations=[
AsyncioIntegration(),
AtexitIntegration(),
ExcepthookIntegration(),
DedupeIntegration(),
StdlibIntegration(),
ThreadingIntegration(),
LoggingIntegration(),
GRPCIntegration(),
SqlalchemyIntegration(),
],
integrations=integrations,
)

if app is not None:
# Add FastApi specific middleware.
app.add_middleware(SentryAsgiMiddleware)

log.info(f"Sentry initialized with env: `{env}`")
log.info(f"Sentry initialized with env: `{env}` in mode: `{mode}`")
2 changes: 1 addition & 1 deletion featureflags/tests/test_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from uuid import uuid4

import pytest
from featureflags.protobuf import graph_pb2
from google.protobuf.wrappers_pb2 import BoolValue # type: ignore
from hiku.builder import Q, build
from hiku.result import denormalize
Expand All @@ -11,6 +10,7 @@
from featureflags.graph.proto_adapter import populate_result_proto
from featureflags.graph.types import Action
from featureflags.graph.utils import is_valid_uuid
from featureflags.protobuf import graph_pb2
from featureflags.services.auth import (
EmptyAccessTokenState,
ExpiredAccessTokenState,
Expand Down
4 changes: 2 additions & 2 deletions featureflags/web/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ def create_app() -> FastAPI:
configure_lifecycle(app, container)

if config.sentry.enabled:
from featureflags.sentry import configure_sentry
from featureflags.sentry import configure_sentry, SentryMode

configure_sentry(config.sentry, env_prefix="web", app=app)
configure_sentry(config.sentry, env_prefix="web", mode=SentryMode.HTTP)

return app

Expand Down
34 changes: 25 additions & 9 deletions pdm.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ license = {text = "MIT"}

[project.optional-dependencies]
sentry = [
"sentry-sdk[fastapi]>=1.40.4",
"sentry-sdk[fastapi,grpcio]>=1.40.5",
]

[build-system]
Expand Down Expand Up @@ -111,6 +111,7 @@ extend-exclude = '''
| .venv
| venv
| .ve
| featureflags/protobuf
)/
'''

Expand Down Expand Up @@ -170,6 +171,7 @@ exclude = [
".ve",
"__pycache__",
"featureflags/migrations",
"featureflags/protobuf",
]
line-length = 80
# Allow unused variables when underscore-prefixed.
Expand Down Expand Up @@ -216,6 +218,7 @@ exclude = [
"venv",
".ve",
"featureflags/migrations",
"featureflags/protobuf",
"featureflags/tests",
]

Expand All @@ -224,7 +227,7 @@ module = "hiku.*"
follow_imports = "skip"

[[tool.mypy.overrides]]
module = "featureflags_protobuf.*"
module = "featureflags.protobuf.*"
follow_imports = "skip"
disallow_untyped_decorators = false
disable_error_code = [
Expand Down

0 comments on commit 6b316d8

Please sign in to comment.