[Django]-Django logging of custom management commands

21👍

you need to namespace your logger. currently you are logging to the root logger, which isn’t caught by your handler, which is looking for main

rather than logging.debug("message"), you want

logger = logging.getLogger('main')
logger.debug("message")
👤second

4👍

Setting “stream” to sys.stdout is not necessary. However, you should define a formatter:

Example:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'log_to_stdout': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
            },
        },
    'loggers': {
        'main': {
            'handlers': ['log_to_stdout'],
            'level': 'DEBUG',
            'propagate': True,
        }
    }
}
👤jpic

-5👍

If you are enrolling these custom commands with cron, you can “force” logging by just redirecting output to a text file.

* 12 * * * python /path/to/my/custom/command.py >> /path/to/my/logfile.txt

This will run a cron job at 12am every morning, and anything directed to stdout (like python print statements) will be dumped into this text file, concatenated on any existing text in the logfile.

If you’re not using cron, just create a single shell script that runs all the scripts you need to run and manually direct them to the logfiles you want.

python /path/to/my/custom/command.py >> /path/to/my/logfile.txt

…and so on.

Leave a comment