Created
October 30, 2013 17:05
-
-
Save epicserve/7236266 to your computer and use it in GitHub Desktop.
Example of how to setup logging for a Django management command.
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
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.