Jason Goldstein
Jason Goldstein

Reputation: 1127

Manually fire Django 1.3's traceback/exception log

I'm using djutils's async decorator, which has the nasty side effect of not sending traceback emails when an exception is raised, since it runs on a separate thread.

It does, however, have the following place to put a logger.

def worker_thread():
    while 1:
        func, args, kwargs = queue.get()
        try:
            func(*args, **kwargs)
        except: 
            pass # <-- log error here
        finally:
            queue.task_done()

I've confirmed this will work, but even with the try/except removed, it won't trip Django's traceback logger.

While it'd be pretty easy to tell it to write to a db/file on exception, I'd really like it to send a regular traceback as defined in settings. How can I do that?

Edit: answer seems to involve django.utils.log.AdminEmailHandler - but I'm having a hard time finding an example.

Edit 2: Here's my current (99% likely to be wrong) attempt.

from django.utils.log import AdminEmailHandler
def worker_thread():
    while 1:
        func, args, kwargs = queue.get()
        try:
            func(*args, **kwargs)
        except:
            import logging
            from django.conf import settings
            print settings.EMAIL_HOST
            logger = logging.getLogger("async.logger")
            logger.exception("Async exploded")
            AdminEmailHandler
            pass # <-- log error here
        finally:
            queue.task_done()

Upvotes: 3

Views: 532

Answers (1)

drul
drul

Reputation: 89

first, configure your logging settings i settings.py:


    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'mail_admins': {
                'level': 'ERROR',
                'class': 'django.utils.log.AdminEmailHandler'
            }
        },
        'loggers': {
            'myproject': {
                'handlers': ['mail_admins'],
                'level': 'INFO',
                'propagate': True,
            },
            'django.request': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': True,
            },
        }
    }

from now, all loggers which starts with 'myproject' should use AdminEmailHandler your code should look like this:


    import logging
    logger = logging.getLogger('myproject.optional.path')
    # example
    # logger = logging.getLogger('myprojects.myapp.views')
    def worker_thread():
        while 1:
            func, args, kwargs = queue.get()
            try:
                func(*args, **kwargs)
            except:
                logger.exception("Async exploded")
            finally:
                queue.task_done()

Upvotes: 3

Related Questions