Django has a command line --verbosity 0/1/2/3
option, but it only has
influence on some of django’s internal output. It does not affect generic
python logging levels.
For management commands it can be handy to control the log level of the
console output. First thing to look at, then is the logging setup. I normally
have something like this in my settings.py
:
LOGGING = {
...
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
},
'logfile': {
'level': 'INFO',
'class': 'logging.FileHandler',
'formatter': 'verbose',
'filename': os.path.join(
SOMEWHERE, 'var', 'log', 'django.log'),
},
},
'loggers': {
'': {
'handlers': ['console', 'logfile'],
'propagate': True,
'level': 'INFO',
},
'django.request': {
'handlers': ['console', 'logfile'],
'propagate': False,
'level': 'ERROR', # WARN also shows 404 errors
},
... some more specialised loggers ...
}
}
A console handler that prints everything of log level DEBUG
and higher and
a logfile that starts at INFO
(or WARN
).
Loggers: the ''
one is the root logger. Everything that’s not handled
elsewhere ends up here. A level of INFO
filters out all the DEBUG
level messages.
The django.request
logger is one I normally configure separately as
everything of level WARN
and higher is normally logged to sentry. And I
don’t want the 404’s to show up (mysql.php?hack=true
…). So I restrict
that one to ERROR
.
Now…. if we want to use django’s build-in --verbosity
option in a
management command to switch on debug logging, this is how to do it:
from django.core.management.base import BaseCommand
import logging
logger = logging.getLogger(__name__)
class Command(BaseCommand):
...
def handle(self, *args, **options):
verbosity = int(options['verbosity'])
root_logger = logging.getLogger('')
if verbosity > 1:
root_logger.setLevel(logging.DEBUG)
... your code ...
logger.debug("I'm doing something")
Now you can run your management command with --verbosity 2
and you’ll get
debug output!
My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.
Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):