Logging in Python WSGI application with Passenger not working

时间:2015-05-24 21:53:21

标签: python passenger wsgi error-logging

I'm trying to get the Python logging facility working without success, despite googling and reading the docs. This is a WSGI Python app inside Passenger on a Dreamhost shared server. The Paste middleware is working to provide info on 500 errors. There are no python errors when this code is run.

My sanitized code (passenger_wsgi.py):

#!/usr/bin/python

import os
import sys
import logging

cwd = os.getcwd()
sys.path.insert(0,cwd)
sys.path.append(cwd)
from paste.exceptions.errormiddleware import ErrorMiddleware

# configure the logging
logfilename = os.path.join('<path>/passenger_wsgi.log')
logging.basicConfig(filename=logfilename, level=logging.DEBUG, filemode='a+', format='%(asctime)s %(levelname)s %(message)s')
logging.info("Running %s", sys.executable)

log = file('<path>/passenger_wsgi_2.log', 'a')
print >>log, "Running %s" % (sys.executable)
log.flush()

application = ''
def application(environ, start_response):
    results = ''
    logging.info("Application called:")
    logging.info("environ: %s", str(environ))
    print >>log, "Application called:"
    log.flush()
    status = '200 OK'
    results = 'Hello World! Running Python version ' + sys.version + '\n\n'
    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(results)))]
    # to test paste's error catching prowess, uncomment the following line
    #raise("error")
    start_response(status, response_headers)
    return results

# load the application within Paste's error middleware
application = ErrorMiddleware(application, debug=True)

The print >>log statements work as expected, both when run from the command line and when run in response to an http request. The first logging.info statement works when run from the command line (of course the other logging.info statements never get hit from the command line). However, when run in response to an HTTP request, none of the logging.info statements work.

When I say 'work' here, I mean 'writes the statements to the log file'. I'd much rather use the logging facility than the print statements, if it can be made to work.

Thanks in advance for helping me understand and solve this issue.

0 个答案:

没有答案