Skip to content

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.

class ScriptCommand(BaseCommand):

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:

python manage.py doing_something

Logging behavior

Each execution produces:

  • Terminal logs (via shared logger)
  • Application logs
  • Dedicated file log:
LOG_DIR_PATH/scripts/<command_name>/<timestamp>_<run_id>.log

Log format

LEVEL | server_time | txn: transaction_id | message

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.