[Django]-How to redirect "print" command output to a file without changing the python code?

1๐Ÿ‘

โœ…

I believe that > writes to the file test.log whatever gets logged to console from Django.
print('query_content:') is not getting logged, therefore is not part of Django output.

You need to create a logger for your application:

  1. In settings.py add:

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': {
        'standard': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        # This logs to the console
        'console':{
            'level':'INFO',
            'class':'logging.StreamHandler',
            'formatter': 'standard'
        },
    },
    'loggers': {
        'django': {
            'handlers':['console'],
            'propagate': True,
            'level':'INFO',
         },
    },
    
  2. Add the following were you want to log something:

    import logging
    mylogger = logging.getLogger(__name__)
    
    
    ...
    logger.info('query content: {}'.format(your_query_content))
    ...
    

Although the above solves your immediate problem, you can take it a step further:

Add a file handler in your LOGGER configuration:

  1. On handlers add:

    'file': {  
        'class': 'logging.FileHandler',
        'filename': 'a/file/location/logs.log',  
        'formatter': 'standard'
    },
    
  2. On loggers.django update the handlers:

    'handlers':['console', 'file'], 
    

You can customize the above even further, but that is another subject:

More info on python and django logging:

  1. https://docs.python.org/3/library/logging.html
  2. https://docs.djangoproject.com/en/2.0/topics/logging/
๐Ÿ‘คJohn Moutafis

1๐Ÿ‘

TL;DR: if you have a loop in the end of a file you are feeding to manage.py shell add two newlines in the end.

In my case the reason prints were not present in the stdout was because they were never really executed in the first place. They were in a for loop that was at the end of file without two newlines or a newline and any other line (with a comment) after it. This way the shell was left waiting for a for loop code to be finished and it never was.

๐Ÿ‘คint_ua

0๐Ÿ‘

I think this shell command maybe can output the result.

python manage.py runserver 0.0.0.0:8000 2>&1 | tee file.txt
๐Ÿ‘คEdge Li

Leave a comment