Search code examples
pythondjangologgingcommanddjango-management-command

Log something at beginning & end of Django management commands


Right now I have multiple management commands in my Django project.

I would like to log something like [command_name] command started and [command_name] command finished at the beginning and end of the commands in a way that I would'nt repeat myself in each command.

Already tried decorators on top of the handle() method but didn't think it was a good solution since I would have to decorate the handle() method in all commands.

PS: I'm using python logger.

Edit

Got to this point:

class Parent(BaseCommand):

    def __init__(self, *args, **kwargs):
        logger.info(f'started {self.__module__}')
        super().__init__(*args, **kwargs)
        logger.info(f'finished {self.__module__}')

Output:

> started command_name
> finished command_name
> actual command logs

Solution

  • Write a base class which all of your commands shall inherit from and do the logging in it. As a good place to log the output is to override the execute method of the command (Your code logs in wrong order because the command is not actually run by the __init__ method, it is actually called on the class separately using the run_from_argv method of the class):

    from django.core.management.base import BaseCommand as DjangoBaseCommand
    
    class BaseCommand(DjangoBaseCommand):
        def execute(self, *args, **options):
            logger.info(f'started {self.__module__}')
            output = super().execute(*args, **options)
            logger.info(f'finished {self.__module__}')
            return output
    

    Now for all of your commands simply inherit from this command:

    from some_app.somewhere import BaseCommand
    
    
    class MyCommand(BaseCommand):
        # Your code here