Esempio n. 1
0
def setup_sentry_logging(sentry_dsn: Optional[str]) -> None:
    """Set up logging with sentry."""

    logging.basicConfig()
    if not sentry_dsn:
        raise ValueError()
    logging_integration = sentry_logging.LoggingIntegration(
        level=logging.DEBUG, event_level=logging.WARNING)
    sentry_sdk.init(dsn=sentry_dsn, integrations=[logging_integration])
Esempio n. 2
0
def _setup_sentry_logging(sentry_dsn: Optional[str]) -> None:
    """Set up logging with sentry."""

    logging.basicConfig()
    if not sentry_dsn:
        raise ValueError()
    logging_integration = sentry_logging.LoggingIntegration(
        level=logging.DEBUG,
        event_level=logging.WARNING)
    # TODO(pascal): Fix when https://github.com/getsentry/sentry-python/issues/1081 is solved.
    sentry_sdk.init(dsn=sentry_dsn, integrations=[logging_integration])  # pylint: disable=abstract-class-instantiated
Esempio n. 3
0
    async def on_start(self, _app: http.app.Application,
                       _loop: ioloop.IOLoop) -> None:
        """Invoked on startup of the application"""
        self.startup_complete = asyncio.Event()

        if sentry_sdk and self.settings['sentry_backend_dsn']:
            sentry_sdk.init(debug=self.settings['debug'],
                            dsn=self.settings['sentry_backend_dsn'],
                            environment=os.environ.get('environment',
                                                       'production'),
                            integrations=[
                                sentry_logging.LoggingIntegration(
                                    event_level=logging.CRITICAL),
                                sentry_tornado.TornadoIntegration()
                            ],
                            release=version)

        self.loop = ioloop.IOLoop.current()
        try:
            self.session_redis = aioredis.Redis(await aioredis.create_pool(
                self.settings['session_redis_url'],
                maxsize=self.settings['session_pool_size']))
        except (OSError, ConnectionRefusedError) as error:
            LOGGER.info('Error connecting to Session redis: %r', error)
            self.stop(self.loop)
            return

        try:
            pool = aioredis.Redis(await aioredis.create_pool(
                self.settings['session_redis_url'],
                maxsize=self.settings['session_pool_size']))
        except (OSError, ConnectionRefusedError) as error:
            LOGGER.info('Error connecting to Stats redis: %r', error)
            self.stop(self.loop)
            return
        else:
            self.stats = stats.Stats(pool)

        await self._postgres_connected.wait()

        self.startup_complete.set()
        self._ready_to_serve = True
        LOGGER.info('Application startup complete, ready to serve requests')
Esempio n. 4
0
    def setup_sentry_logging(self):
        """
        Setup sentry logging if SENTRY_ENABLED and OctoBot version is importable
        """
        if DISABLE_SENTRY is None:
            try:
                from octobot.constants import VERSION
                import sentry_sdk
                import sentry_sdk.integrations.logging as sentry_logging

                sentry_sdk.init(
                    f"https://{SENTRY_KEY}@{SENTRY_URL}/{SENTRY_PROJECT}",
                    traces_sample_rate=SENTRY_RATE,
                    release=VERSION,
                    environment=SENTRY_ENV,
                    integrations=[
                        sentry_logging.LoggingIntegration(
                            level=logging.ERROR, event_level=logging.ERROR)
                    ],
                )
            except ImportError:
                self.logger.debug(
                    "Failed to start sentry : can't import OctoBot version")
Esempio n. 5
0
    for collection_name in (args.revert or []):
        if not db_client:
            logging.info('Database is missing')
            return

        if collection_name in all_importers:
            _revert_collection(collection_name, db_client)
        else:
            _warn_unknown_collection(collection_name, all_importers)

    if not args.revert and not args.run:
        if not db_client:
            logging.info('Database is missing')
            return

        _print_report(db_client, unknown_args, all_importers)


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    if _SENTRY_DSN:
        # Setup logging basic's config first so that we also get basic logging to STDERR.
        # TODO(sil): Add info on which release version we are on.
        # TODO(pascal): Fix when https://github.com/getsentry/sentry-python/issues/1081 is solved.
        sentry_sdk.init(  # pylint: disable=abstract-class-instantiated
            dsn=_SENTRY_DSN,
            integrations=[
                sentry_logging.LoggingIntegration(level=logging.INFO, event_level=logging.WARNING)]
        )
    main()
Esempio n. 6
0
def main(string_args: Optional[Sequence[str]] = None) -> None:
    """Translate a Mailjet template from a folder.

    Args:
        string_args: a list of folder to extract from. None to use the command line arguments.
    """

    logging.basicConfig(level='INFO')

    parser = argparse.ArgumentParser(
        description='Translate a MailJet template.')
    parser.add_argument(
        '--lang',
        action='append',
        choices=_MAILJET_LOCALES.keys(),
        help=
        'The code of the language in which to translate the template (defaults to "en")'
    )
    parser.add_argument('campaign_id',
                        choices=mailjet_templates.MAP.keys() | {'existing'},
                        nargs='+',
                        help='The ID of the mailjet campaign to translate')
    parser.add_argument('--mailjet-apikey',
                        default=os.getenv('MAILJET_APIKEY_PUBLIC'),
                        help='The public API key to access the MailJet API')
    parser.add_argument('--mailjet-secret',
                        default=os.getenv('MAILJET_SECRET'),
                        help='The secret API key to access the MailJet API')
    parser.add_argument(
        '--template-map-file',
        default=os.path.join(mailjet_templates.PATH, 'mailjet.json'),
        help='The path to the json file containing the map of templates')
    parser.add_argument('--dry-run',
                        action='store_true',
                        help='Do not update any template nor files')
    args = parser.parse_args(string_args)

    sentry_dsn = os.getenv('SENTRY_DSN')
    if sentry_dsn:
        # TODO(pascal): Fix when https://github.com/getsentry/sentry-python/issues/1081 is solved.
        sentry_sdk.init(  # pylint: disable=abstract-class-instantiated
            dsn=sentry_dsn,
            integrations=[
                sentry_logging.LoggingIntegration(level=logging.INFO,
                                                  event_level=logging.WARNING)
            ])

    if 'existing' in args.campaign_id:
        actions = [(campaign_id, lang)
                   for campaign_id, campaign in mailjet_templates.MAP.items()
                   for lang in campaign.get('i18n', {}).keys()]
    else:
        actions = [(campaign_id, lang) for campaign_id in args.campaign_id
                   for lang in args.lang or ('en', )]

    for campaign_id in {action[0] for action in actions}:
        if mailjet_templates.MAP[campaign_id].get('noI18n'):
            raise ValueError(f'{campaign_id} is marked as not translatable.')

    errors: list[Tuple[str, str, ValueError]] = []
    translator = _MailTranslator(args.mailjet_apikey, args.mailjet_secret)
    for campaign_id, lang in actions:
        try:
            result = translator.update_template(campaign_id,
                                                lang,
                                                dry_run=args.dry_run)
        except ValueError as error:
            errors.append((campaign_id, lang, error))
            continue
        if result.new_template_id and not args.dry_run:
            _update_mailjet_templates(args.template_map_file, campaign_id,
                                      lang, result.new_template_id)

    if errors:
        raise ValueError('Errors in translations:\n\n' + '\n\n'.join(
            f'In template "{campaign_id}" in language "{lang}":\n{error}'
            for campaign_id, lang, error in errors)) from errors[0][2]