|
| 1 | +import logging |
| 2 | +import os |
| 3 | + |
| 4 | +import sentry_sdk |
| 5 | +from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration |
| 6 | + |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | +logger.setLevel(logging.DEBUG) |
| 9 | + |
| 10 | + |
| 11 | +class Config: |
| 12 | + REQUIRED_ENV_VARS = ( |
| 13 | + "WORKSPACE", |
| 14 | + "SENTRY_DSN", |
| 15 | + ) |
| 16 | + OPTIONAL_ENV_VARS = ("WARNING_ONLY_LOGGERS",) |
| 17 | + |
| 18 | + def check_required_env_vars(self) -> None: |
| 19 | + """Method to raise exception if required env vars not set.""" |
| 20 | + missing_vars = [var for var in self.REQUIRED_ENV_VARS if not os.getenv(var)] |
| 21 | + if missing_vars: |
| 22 | + message = f"Missing required environment variables: {', '.join(missing_vars)}" |
| 23 | + raise OSError(message) |
| 24 | + |
| 25 | + @property |
| 26 | + def workspace(self) -> str | None: |
| 27 | + return os.getenv("WORKSPACE") |
| 28 | + |
| 29 | + @property |
| 30 | + def sentry_dsn(self) -> str | None: |
| 31 | + dsn = os.getenv("SENTRY_DSN") |
| 32 | + if dsn and dsn.strip().lower() != "none": |
| 33 | + return dsn |
| 34 | + return None |
| 35 | + |
| 36 | + |
| 37 | +def configure_logger( |
| 38 | + root_logger: logging.Logger, |
| 39 | + *, |
| 40 | + verbose: bool = False, |
| 41 | + warning_only_loggers: str | None = None, |
| 42 | +) -> str: |
| 43 | + """Configure application via passed application root logger. |
| 44 | +
|
| 45 | + If verbose=True, 3rd party libraries can be quite chatty. For convenience, they can |
| 46 | + be set to WARNING level by either passing a comma seperated list of logger names to |
| 47 | + 'warning_only_loggers' or by setting the env var WARNING_ONLY_LOGGERS. |
| 48 | + """ |
| 49 | + if verbose: |
| 50 | + root_logger.setLevel(logging.DEBUG) |
| 51 | + logging_format = ( |
| 52 | + "%(asctime)s %(levelname)s %(name)s.%(funcName)s() " |
| 53 | + "line %(lineno)d: %(message)s" |
| 54 | + ) |
| 55 | + else: |
| 56 | + root_logger.setLevel(logging.INFO) |
| 57 | + logging_format = "%(asctime)s %(levelname)s %(name)s.%(funcName)s(): %(message)s" |
| 58 | + |
| 59 | + warning_only_loggers = os.getenv("WARNING_ONLY_LOGGERS", warning_only_loggers) |
| 60 | + if warning_only_loggers: |
| 61 | + for name in warning_only_loggers.split(","): |
| 62 | + logging.getLogger(name).setLevel(logging.WARNING) |
| 63 | + |
| 64 | + # Clear any existing handlers to prevent duplication in AWS Lambda environment |
| 65 | + # where container may be reused between invocations |
| 66 | + for handler in root_logger.handlers[:]: |
| 67 | + root_logger.removeHandler(handler) |
| 68 | + |
| 69 | + handler = logging.StreamHandler() |
| 70 | + handler.setFormatter(logging.Formatter(logging_format)) |
| 71 | + root_logger.addHandler(handler) |
| 72 | + |
| 73 | + return ( |
| 74 | + f"Logger '{root_logger.name}' configured with level=" |
| 75 | + f"{logging.getLevelName(root_logger.getEffectiveLevel())}" |
| 76 | + ) |
| 77 | + |
| 78 | + |
| 79 | +def configure_dev_logger( |
| 80 | + warning_only_loggers: str = ",".join( # noqa: FLY002 |
| 81 | + ["asyncio", "botocore", "urllib3", "boto3", "smart_open"] |
| 82 | + ), |
| 83 | +) -> None: |
| 84 | + """Invoke to setup DEBUG level console logging for development work.""" |
| 85 | + os.environ["WARNING_ONLY_LOGGERS"] = warning_only_loggers |
| 86 | + root_logger = logging.getLogger() |
| 87 | + configure_logger(root_logger, verbose=True) |
| 88 | + |
| 89 | + |
| 90 | +def configure_sentry() -> None: |
| 91 | + CONFIG = Config() # noqa: N806 |
| 92 | + env = CONFIG.workspace |
| 93 | + if CONFIG.sentry_dsn: |
| 94 | + sentry_sdk.init( |
| 95 | + dsn=CONFIG.sentry_dsn, |
| 96 | + environment=env, |
| 97 | + integrations=[ |
| 98 | + AwsLambdaIntegration(), |
| 99 | + ], |
| 100 | + traces_sample_rate=1.0, |
| 101 | + ) |
| 102 | + logger.info( |
| 103 | + "Sentry DSN found, exceptions will be sent to Sentry with env=%s", env |
| 104 | + ) |
| 105 | + else: |
| 106 | + logger.info("No Sentry DSN found, exceptions will not be sent to Sentry") |
0 commit comments