1

How can I configure logging in Django to use Sentry by default for all WARNING and higher messages, but when I run a management command lower it to INFO and add a console logger?

In normal operation (running the site via mod_python or uWSGI), I only care about WARNING and higher. However, we have some management commands that we run via cronjobs, and I would like to collect their INFO messages (in the management command, but also in deeper code) too in a logfile. Some of the management commands come from external libraries, I would prefer not to change them (to add extra initialization there). Ideally, I would like to detect in the settings module whether we are running via manage.py or via WSGI.

The relevant part of my current LOGGING dict:

    'root': {
        'level': 'WARNING',
        'handlers': ['sentry'],
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
        }.
        'sentry': {
            'level': 'WARNING',
            'class': 'raven.contrib.django.handlers.SentryHandler',
        },
    },
bignose
  • 30,281
  • 14
  • 77
  • 110
Jan Fabry
  • 7,221
  • 2
  • 36
  • 41

2 Answers2

0

A very crude way: modify manage.py to add something in the environment, and detect this in the settings module.

In manage.py:

import os
os.environ['DJANGO_IS_MANAGEMENT_COMMAND'] = '1'

In the settings module:

if os.environ.get('DJANGO_IS_MANAGEMENT_COMMAND', False):
    LOGGING['root']['level'] = 'INFO'
    LOGGING['root']['handlers'].append('console')

This will also add the logger when running Celery workers, but I think the daemon has no stdout, so it doesn't matter?

Jan Fabry
  • 7,221
  • 2
  • 36
  • 41
0

You can use different settings for management commands ./manage.py my_task --settings=proj.settings.management, right? So you can just override the logging section and "inherit" the rest from your original settings file... Or am I missing some point in your question?

starenka
  • 580
  • 3
  • 9
  • That would be possible indeed, but then I would need to remember to add this every time. I was looking for a simple way to detect Django was started via `manage.py` vs. another way (most likely WSGI). – Jan Fabry Oct 09 '13 at 15:37