Skip to content

Commit

Permalink
Move configure_logger and configure_sentry outside of Config class
Browse files Browse the repository at this point in the history
  • Loading branch information
jonavellecuerdo committed Sep 19, 2024
1 parent 3c963d2 commit 1c9fd2f
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 46 deletions.
7 changes: 4 additions & 3 deletions lambdas.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

from apig_wsgi import make_lambda_handler

from webapp import Config, create_app
from webapp import create_app
from webapp.config import Config, configure_logger, configure_sentry

logger = logging.getLogger(__name__)
CONFIG = Config()
Expand All @@ -21,8 +22,8 @@ def lambda_handler(event: dict, context: dict) -> dict:
See https://github.com/adamchainz/apig-wsgi/tree/main.
"""
CONFIG.check_required_env_vars()
CONFIG.configure_logger(verbose=True)
CONFIG.configure_sentry()
logger.info(configure_logger(verbose=True))
logger.info(configure_sentry())

apig_wsgi_handler = make_lambda_handler(create_app())

Expand Down
3 changes: 2 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@
from moto.core.utils import unix_time_millis, utcnow
from moto.moto_api import state_manager

from webapp import Config, create_app
from webapp import create_app
from webapp.app import User
from webapp.config import Config
from webapp.utils.aws import CloudWatchLogsClient, ECSClient

AWS_DEFAULT_REGION = "us-east-1"
Expand Down
10 changes: 6 additions & 4 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import pytest

from webapp.config import configure_logger, configure_sentry


def test_config_check_required_env_vars_success(config):
config.check_required_env_vars()
Expand All @@ -15,29 +17,29 @@ def test_config_check_required_env_vars_error(monkeypatch, config):

def test_configure_logger_not_verbose(config, caplog):
logger = logging.getLogger(__name__)
result = config.configure_logger(verbose=False)
result = configure_logger(verbose=False)
assert logger.getEffectiveLevel() == logging.INFO
assert result == "Logger 'root' configured with level=INFO"


def test_configure_logger_verbose(config, caplog):
logger = logging.getLogger(__name__)
result = config.configure_logger(verbose=True)
result = configure_logger(verbose=True)
assert logger.getEffectiveLevel() == logging.DEBUG
assert result == "Logger 'root' configured with level=DEBUG"


def test_configure_sentry_if_dsn_exists(config, caplog, monkeypatch):
monkeypatch.setenv("SENTRY_DSN", "https://1234567890@00000.ingest.sentry.io/123456")
config.configure_sentry()
configure_sentry()
assert (
"Sentry DSN found, exceptions will be sent to Sentry with env=test" in caplog.text
)


def test_configure_sentry_if_dsn_missing(config, caplog, monkeypatch):
monkeypatch.delenv("SENTRY_DSN", raising=False)
config.configure_sentry()
configure_sentry()
assert "No Sentry DSN found, exceptions will not be sent to Sentry" in caplog.text


Expand Down
3 changes: 1 addition & 2 deletions webapp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""lambdas package."""

from webapp.app import create_app
from webapp.config import Config

__all__ = ["Config", "create_app"]
__all__ = ["create_app"]
67 changes: 31 additions & 36 deletions webapp/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from typing import Any

import sentry_sdk
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration

logger = logging.getLogger("__name__")

Expand Down Expand Up @@ -62,41 +61,37 @@ def check_required_env_vars(self) -> None:
message = f"Missing required environment variables: {', '.join(missing_vars)}"
raise OSError(message)

def configure_logger(self, *, verbose: bool) -> str:
logger = logging.getLogger()
if verbose:
logging.basicConfig(
format=(
"%(asctime)s %(levelname)s %(name)s.%(funcName)s() "
"line %(lineno)d: "
"%(message)s"
)
)
logger.setLevel(logging.DEBUG)
else:
logging.basicConfig(
format="%(asctime)s %(levelname)s %(name)s.%(funcName)s(): %(message)s"
)
logger.setLevel(logging.INFO)

return (
f"Logger '{logger.name}' configured with level="
f"{logging.getLevelName(logger.getEffectiveLevel())}"
def configure_logger(*, verbose: bool) -> str:
logger = logging.getLogger()
if verbose:
logging.basicConfig(
format=(
"%(asctime)s %(levelname)s %(name)s.%(funcName)s() "
"line %(lineno)d: "
"%(message)s"
)
)
logger.setLevel(logging.DEBUG)
else:
logging.basicConfig(
format="%(asctime)s %(levelname)s %(name)s.%(funcName)s(): %(message)s"
)
logger.setLevel(logging.INFO)

def configure_sentry(self) -> None:
if sentry_dsn := self.SENTRY_DSN:
sentry_sdk.init(
dsn=sentry_dsn,
environment=self.WORKSPACE,
integrations=[
AwsLambdaIntegration(),
],
traces_sample_rate=1.0,
)
logger.info(
"Sentry DSN found, exceptions will be sent to Sentry with env=%s",
self.WORKSPACE,
)
else:
logger.info("No Sentry DSN found, exceptions will not be sent to Sentry")
return (
f"Logger '{logger.name}' configured with level="
f"{logging.getLevelName(logger.getEffectiveLevel())}"
)


def configure_sentry() -> str:
env = os.getenv("WORKSPACE")
sentry_dsn = os.getenv("SENTRY_DSN")
if sentry_dsn and sentry_dsn.lower() != "none":
sentry_sdk.init(
sentry_dsn,
environment=env,
)
return f"Sentry DSN found, exceptions will be sent to Sentry with env={env}"
return "No Sentry DSN found, exceptions will not be sent to Sentry"

0 comments on commit 1c9fd2f

Please sign in to comment.