return ( result.status_code, result.text, { "Content-Type": result.headers.get("Content-Type", "application/xml") }, ) if "pytest" not in sys.modules: sentry_sdk.init( dsn=os.environ["SENTRY_DSN"], environment=os.environ["SENTRY_ENVIRONMENT"], integrations=[AwsLambdaIntegration()], ) muxer = TwilioMuxer( twilio_auth_token=os.environ["TWILIO_AUTH_TOKEN"], muxer_url=os.environ["TWILIO_CALLBACK_URL"], config=parse_config(os.environ["DOWNSTREAM_CONFIG"]), ) def handler(event: Any, context: Any): request_body = event["body"] request_headers = event["headers"] status_code, body, headers = muxer.mux_request(request_body, request_headers)
import glob import importlib import os import sys import sentry_sdk from decouple import config from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration SENTRY_DSN = config("SENTRY_DSN", default=None) if SENTRY_DSN: # Note! If you don't do `sentry_sdk.init(DSN)` it will still work # to do things like calling `sentry_sdk.capture_exception(exception)` # It just means it's a noop. sentry_sdk.init(SENTRY_DSN, integrations=[AwsLambdaIntegration()]) def help_(**kwargs): """Show this help.""" def white_bold(s): return f"\033[1m\x1B[37m{s}\033[0;0m" entrypoints = [ os.path.splitext(os.path.basename(f))[0] for f in glob.glob("./commands/[a-z]*.py") ] commands = [ getattr(importlib.import_module(f"commands.{entrypoint}"), entrypoint) for entrypoint in entrypoints ]
from twython import Twython import boto3 import credentials import sentry_sdk from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration # Automatically report all uncaught exceptions sentry_sdk.init(dsn="url_sentry", integrations=[AwsLambdaIntegration()]) # publish a tweet with a message, a place ad a video integrated, pay attention to twitter size limit for videos def publish_video(path_video, message, place=None): twitter = Twython(credentials.consumer_key, credentials.consumer_secret, credentials.access_token, credentials.access_token_secret) video = open(path_video, 'rb') response = twitter.upload_video(media=video, media_type='video/mp4') if place == None: twitter.update_status(status=message, media_ids=[response['media_id']]) else: twitter.update_status(status=message, media_ids=[response['media_id']], place_id=place) close(video) # publish a tweet with a message, a place ad a photo integrated, pay attention to twitter size limit for photos def publish_image(path_image, message, place=None): twitter = Twython(credentials.consumer_key, credentials.consumer_secret, credentials.access_token, credentials.access_token_secret) photo = open(path_image, 'rb')
from acme_serverless_client import find_certificates_to_renew, issue, renew, revoke from acme_serverless_client.authenticators.http import HTTP01Authenticator from acme_serverless_client.storage.aws import S3Storage logger = logging.getLogger("aws-lambda-acme") if os.environ.get("SENTRY_DSN"): import sentry_sdk from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration from sentry_sdk.integrations.logging import LoggingIntegration sentry_sdk.init( dsn=os.environ["SENTRY_DSN"], integrations=[ AwsLambdaIntegration(), LoggingIntegration(level=logging.INFO, event_level=logging.ERROR), ], ) def handler(event: typing.Any, context: typing.Any) -> typing.Mapping[str, typing.Any]: client = boto3.client("s3") storage = S3Storage(bucket=S3Storage.Bucket(os.environ["BUCKET"], client)) authenticators = [HTTP01Authenticator(storage=storage)] params: typing.Any = { "acme_account_email": os.environ["ACME_ACCOUNT_EMAIL"], "acme_directory_url": os.environ["ACME_DIRECTORY_URL"], "storage": storage, } if event["action"] == "renew":
import logging import os from ..utils.mail_sender import send_mail_to_user from jinja2 import Template import boto3 from ..utils.json_util import loads from datetime import datetime import sentry_sdk from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration sentry_sdk.init(dsn=os.environ.get('SENTRY_DSN'), integrations=[AwsLambdaIntegration()]) client = boto3.client('dynamodb', region_name=os.environ['AWS_REGION']) USERS_TABLE_NAME = os.environ['USERS_TABLE_NAME'] IDEAS_TABLE_NAME = os.environ['IDEAS_TABLE_NAME'] TAGS_TABLE_NAME = os.environ['TAGS_TABLE_NAME'] STATS_ACTIONS_TABLE_NAME = os.environ['STATS_ACTIONS_TABLE_NAME'] logger = logging.getLogger() logger.setLevel(logging.INFO) def get_user_by_id(user_id: str) -> dict: resp = client.get_item( TableName=USERS_TABLE_NAME, Key={'userId': {'S': user_id}} ) return resp.get('Item')
def init_logger(self): """ Initialize the logger. Call exactly once. """ assert (self.name is not None) assert (self.author is not None) self.handlers = {} if self.is_root: self.log = logging.getLogger() else: self.log = logging.getLogger(self.name) if not self.propagate: self.log.propagate = False # set the root log level if self.verbose: self.log.setLevel(logging.DEBUG) else: self.log.setLevel(logging.INFO) if self.log.hasHandlers(): self.log.info("Logger already initialized.") # create file handler if self.log_directory is None: self.log_directory = appdirs.user_log_dir(self.name, self.author) if self.log_directory is not None: if self.delete_existing_log_files: for file_path in glob( os.path.join(self.log_directory, "*%s" % self.log_extension)): try: os.remove(file_path) except OSError: pass os.makedirs(self.log_directory, exist_ok=True) self.log_path = os.path.join( self.log_directory, "%s%s" % (self.name, self.log_extension)) file_handler = logging.handlers.RotatingFileHandler( self.log_path, maxBytes=self.max_bytes, backupCount=self.backup_count) file_handler.setFormatter(self.log_formatter) if self.verbose: file_handler.setLevel(logging.DEBUG) else: file_handler.setLevel(logging.INFO) self.log.addHandler(file_handler) self.handlers[HandlerType.File] = file_handler self.log.info('log file path : "%s" ("%s")' % (self.log_path, os.path.abspath(self.log_path))) if self.gui: # GUI will only pop up a dialog box - it's important that GUI not try to output to stdout or stderr # since that would likely cause a permissions error. dialog_box_handler = DialogBoxHandler(self.rate_limits) if self.verbose: dialog_box_handler.setLevel(logging.WARNING) else: dialog_box_handler.setLevel(logging.ERROR) self.log.addHandler(dialog_box_handler) self.handlers[HandlerType.DialogBox] = dialog_box_handler else: console_handler = logging.StreamHandler() console_handler.setFormatter(self.log_formatter) if self.verbose: console_handler.setLevel(logging.INFO) else: console_handler.setLevel(logging.WARNING) self.log.addHandler(console_handler) self.handlers[HandlerType.Console] = console_handler string_list_handler = BalsaStringListHandler( self.max_string_list_entries) string_list_handler.setFormatter(self.log_formatter) string_list_handler.setLevel(logging.INFO) self.log.addHandler(string_list_handler) self.handlers[HandlerType.StringList] = string_list_handler # setting up Sentry error handling # For the Client to work you need a SENTRY_DSN environmental variable set, or one must be provided. if self.use_sentry: sample_rate = 0.0 if self.inhibit_cloud_services else 1.0 integrations = [] if self.use_sentry_django: from sentry_sdk.integrations.django import DjangoIntegration integrations.append(DjangoIntegration()) if self.use_sentry_flask: from sentry_sdk.integrations.flask import FlaskIntegration integrations.append(FlaskIntegration()) if self.use_sentry_lambda: from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration integrations.append(AwsLambdaIntegration()) if self.use_sentry_sqlalchemy: from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration integrations.append(SqlalchemyIntegration()) if self.use_sentry_celery: from sentry_sdk.integrations.celery import CeleryIntegration integrations.append(CeleryIntegration()) if self.sentry_dsn is None: if 'SENTRY_DSN' not in os.environ: raise ValueError(f"Missing sentry_dsn") else: sentry_sdk.init( dsn=os.environ['SENTRY_DSN'], sample_rate=sample_rate, integrations=integrations, ) else: sentry_sdk.init( dsn=self.sentry_dsn, sample_rate=sample_rate, integrations=integrations, ) # error handler for callback on error or above # (this is last since the user may do a sys.exit() in the error callback) if self.error_callback is not None: error_callback_handler = BalsaNullHandler(self.error_callback) error_callback_handler.setLevel(logging.ERROR) self.log.addHandler(error_callback_handler) self.handlers[HandlerType.Callback] = error_callback_handler
import os import json import re from datetime import datetime, timedelta import calendar from functools import reduce import logging from collections import Counter, defaultdict from string import hexdigits from urllib.parse import parse_qs try: import sentry_sdk from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration sentry_kwargs = { "integrations": [AwsLambdaIntegration()] } if os.getenv("_HANDLER") else {} sentry_sdk.init(dsn=os.environ["SENTRY_DSN"], **sentry_kwargs) except (ImportError, KeyError) as e: logging.warning(f"Sentry did not init: {e}") import boto3 logger = logging.getLogger() logger.setLevel(logging.INFO) TLD_list = None # setting up a global for caching IO of get_tld_list() # Allows enforcing of querystrings' presence def validate_params(event, required_params, **kwargs):
import os import sentry_sdk from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration sentry_config = { 'dsn': os.environ['SENTRY_DNS'], 'environment': os.environ['STAGE'], 'send_default_pii': True, } sentry_sdk.init(**sentry_config, integrations=[AwsLambdaIntegration()])