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
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
executemethod 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 therun_from_argvmethod of the class):Now for all of your commands simply inherit from this command: