Skip to content

Instantly share code, notes, and snippets.

@epicserve
Created October 30, 2013 17:05
Show Gist options
  • Save epicserve/7236266 to your computer and use it in GitHub Desktop.
Save epicserve/7236266 to your computer and use it in GitHub Desktop.
Example of how to setup logging for a Django management command.
from django.core.management.base import BaseCommand
from mymodule import main
import logging
class Command(BaseCommand):
help = 'Do foo'
def handle(self, *args, **options):
# Setup logging
#
# Verbosity levels:
# 1 - prints nothing
# 2 - Prints log messages for just this module
# 3 or greater - Prints log messages from any module
options['verbosity'] = int(options['verbosity'])
if options['verbosity'] > 1:
if options['verbosity'] == 2:
# use logger for just this module
logger = logging.getLogger('mymodule')
else:
# use root logger
logger = logging.getLogger('')
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
console.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s'))
logger.addHandler(console)
main()
@woochica
Copy link

woochica commented Feb 9, 2022

Thank you for sharing your example.

The other day I had to enable logging in our management commands. We already relied on Django's bult-in self.stdout.write() to send message to the screen. I ended up creating a custom base command class that adds logging of the messages in a transparent way and printing to stdout is according to the chosen verbosity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment