Last active
November 6, 2018 17:20
-
-
Save vfr292/3fb3aa7b142bcd891cd055a0a27d8ffe to your computer and use it in GitHub Desktop.
Celery logging with a mail handler and filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os, logging, random, string | |
| from celery.signals import after_setup_logger | |
| from celery.app.log import TaskFormatter | |
| from car_listing_flask_app.app import celery, app_factory | |
| from car_listing_flask_app.utilities.s3_internal_static_file_download import download_internal_static_files | |
| from car_listing_flask_app.utilities.logging_set_up import SparkPostMailHandler | |
| environment_import_path = os.environ['APP_SETTINGS'] | |
| app = app_factory(environment_import_path) | |
| if not app.config['SERVER_NAME']: | |
| app.config['SERVER_NAME'] = 'localhost:5000' #This is needed to for email URL's to work. It caused some wierd problems in development (se note in config file), so I put it here. | |
| app.app_context().push() | |
| class ContextualFilter(logging.Filter): | |
| def filter(self, log_record): | |
| log_record.key_code = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(16)) | |
| @after_setup_logger.connect | |
| def setup_loggers(logger, *args, **kwargs): | |
| formater = TaskFormatter('%(asctime)s - %(task_id)s - %(task_name)s - %(name)s - %(levelname)s - %(message)s') | |
| default_subject = 'site-' + os.environ['APP_SETTINGS'].split('.')[-1] + '-Celery' + '#' | |
| mail_handler = SparkPostMailHandler(app.config['SPARKPOST_API_KEY'], dict(name = 'dev-errors', email = '[email protected]'), ['[email protected]'], default_subject) | |
| mail_handler.setFormatter(formater) | |
| mail_handler.setLevel(logging.ERROR) | |
| context_provider = ContextualFilter() | |
| logger.addFilter(context_provider) | |
| logger.addHandler(mail_handler) | |
| download_internal_static_files() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment