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

The "Started command" line includes the command options. Values of options whose name contains password, secret, token, key or credential are replaced by ***. Override get_loggable_options(options) to change the rule.

Note

A new file is created for every run and none is deleted. Remove old files with your own cleanup (for example find LOG_DIR_PATH/scripts -name "*.log" -mtime +30 -delete in a cron job) or they grow without limit.

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.

get_loggable_options(options)

Returns the options with sensitive values hidden, used for the start log line.

cleanup_logger()

Removes file handlers after execution.