5

I have become aware that the print statements in my django app are causing wsgi to error and fail. Without going over all my code and removing/commenting out the print statements, is there a way I can disable them when running wsgi. It needs to be a simple as possible.

Thanks

Designer023
  • 193
  • 1
  • 1
  • 8

2 Answers2

9

Use WSGIRestrictStdout option:

WSGIRestrictStdout Off

or replace sys.stdout with sys.stderr in Django WSGI star script:

import sys
sys.stdout = sys.stderr

Writing To Standard Output

No WSGI application component which claims to be portable should write to standard output. That is, an application should not use the Python print statement without directing output to some alternate stream. An application should also not write directly to sys.stdout.

ooshro
  • 11,134
  • 1
  • 32
  • 31
  • Excellent. Worked spot on. I used the second option. Thanks for your help – Designer023 Feb 24 '11 at 09:59
  • I have to disagree with the statement about logging to stdout. There are a lot of applications which adhere to the 12factor app principles http://12factor.net/logs – Lloyd Moore Nov 11 '15 at 07:43
  • @LloydMoore I can certainly see the value of the 12factor app principle linked, and I agree with all the advantages (though stderr has similar advantages): The problem is that logging to `stdout` conflicts with writing request responses to `stdout`, which some WSGI implementations require that, the same way CGI did (which is sorta going with the original Unix-y take on file output streams, where `stdout` is where the *results* or *answer* of a program to its requested task go, and `stderr` is where other diagnostics/etc go). – mtraceur Dec 22 '17 at 23:16
  • @mtraceur I completely agree. My comment was more a gripe with the WSGI policy although the documentation does explain why it's in place. – Lloyd Moore Dec 27 '17 at 19:58
2

In general, it is better to use logging for any kind of debug output in a web app and never use print statements at all. Or use them in the form:

print >> environ['wsgi.errors'], "message to be printed"

It is best to get rid of sys.stdout by making it a copy of sys.stderr just in case.

If you do development on a UNIX server, you can have two terminal windows open, one to run Django and the second one to do

tail -f loggingfile

And you get pretty much the same effect as using print statements, but you can use the standard logging module to generate the output, and in the production app, you just change the filter setting to not show DEBUG level messages.

Michael Dillon
  • 1,819
  • 13
  • 16
  • In the future that sounds Ideal. I will try and add this to my code as I go through it. I knew I was doing it wrong when I started doing it, but it was just more to add to my learning curve. Thanks :D – Designer023 Feb 24 '11 at 10:00