Django manage command set stdout and stderr
Is there a way to set stdout
and stderr
from base_stealth_options
in BaseCommand
when running the django command? I can't find any documentation about how to use those options. For example, I would like to set stdout
and stderr
to a logger info
and error
when running python manage.py foo
.
Code reference: https://github.com/django/django/blob/stable/5.2.x/django/core/management/base.py#L269
This is my attempt at making my own manage_custom_logging.py
. I am wondering if there is a better way to do this since base_stealth_options
exists.
# manage_custom_logging.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
import traceback
import logging
logger = logging.getLogger('manage_custom_logging')
class StreamToLogger(object):
def __init__(self, logfct):
self.logfct = logfct
def write(self, buf):
for line in buf.rstrip().splitlines():
self.logfct(line.rstrip())
def flush(self):
pass
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_django_app.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
'available on your PYTHONPATH environment variable? Did you '
'forget to activate a virtual environment?'
) from exc
try:
sys.stdout = StreamToLogger(logging.info)
sys.stderr = StreamToLogger(logging.error)
execute_from_command_line(sys.argv)
except Exception:
logger.error(traceback.format_exc())
if __name__ == '__main__':
main()