Management Commands¶
This module provides a structured base class for Django management commands.
ScriptCommand¶
A base class for Django management commands with per execution logging.
How it works¶
Each command execution:
- Generates a unique
run_id - Creates a dedicated log file
- Attaches a file handler to logger
- Executes
run() - Logs success / failure
- Cleans up handlers
Required method¶
run()
This replaces Django’s usual handle() logic.
Must be implemented by subclasses.
Usage Example¶
# <root>/<app>/management/doing-something.py
class DoingSomethingCommand(ScriptCommand):
def run(self, *args, **options):
self.logger.info("Running my command")
return "done"
Run:
Logging behavior¶
Each execution produces:
- Terminal logs (via shared logger)
- Application logs
- Dedicated file log:
Log format¶
Methods¶
get_command_name()¶
Returns the command name derived from module path.
get_log_directory()¶
Returns log directory for this command.
get_log_file()¶
Generates unique log file path per execution.
setup_logger()¶
Initializes logging configuration for the command run.
cleanup_logger()¶
Removes file handlers after execution.