Graham Dumpleton wrote:
Hopefully everyone follows what I am talking about. I will try and get
together a working example today of what I am talking about, but Nick,
you may want to consider posting your code and how you are using it
as it probably will not be too different.
Here's my sample code I was using. Very rough and unpolished, since I
ultimately decided not to use it. I haven't tried it in a while, but it
should more or less work. apache.py might contain the following code:
from logger import log_handler
Sample usage might look like the following (to steal your example from a
subsequent email):
from mod_python import apache
import logging
log = logging.getLogger("mod_python")
log.warning("importing handler")
def handler(req):
apache.log_handler.set_req(req) # <-- here's the extra code
log.warning("running handler")
req.content_type = 'text/plain'
req.send_http_header()
req.write('hello\n')
return apache.OK
Notice that if you *don't* call set_req, logging will still work, but
not according to any special ErrorLog settings in your apache config
other than the global setting. Also, since log_handler is available,
you can change it's default formatting options somehow as a mod_python
directive in your apache config, or whatever else you want to set.
Nick
from mod_python import apache
import logging, threading
class mpHandler(logging.Handler):
apache_levels = { logging.CRITICAL : apache.APLOG_CRIT,
logging.DEBUG : apache.APLOG_DEBUG,
logging.ERROR : apache.APLOG_ERR,
logging.FATAL : apache.APLOG_EMERG,
logging.INFO : apache.APLOG_INFO,
logging.NOTSET : apache.APLOG_INFO,
logging.WARN : apache.APLOG_WARNING }
def __init__(self, level = logging.NOTSET):
logging.Handler.__init__(self, level)
self.local = threading.local()
self.local.req = None
def emit(self, record):
if self.local.req:
self.local.req.log_error(self.format(record),
mpHandler.apache_levels[record.levelno] | apache.APLOG_NOERRNO)
else:
apache.log_error(self.format(record),
mpHandler.apache_levels[record.levelno] | apache.APLOG_NOERRNO)
def set_req(self, req):
self.local.req = req
def free_req():
self.local.req = None
req.register_cleanup(free_req)
log = logging.getLogger('')
log_handler = mpHandler()
log_handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
log.addHandler(log_handler)
log.setLevel(logging.NOTSET)