views:

389

answers:

2

What is the standard way to make python's logging module work with apache/modpython?

I want to call mylog.warn('whatever') and have that result in a call to req.log_error() where req is the modpython request.

Is there an easy way to set this up?

+1  A: 

I've never done it, but it seems that writing a subclass of logging.Handler shouldn't be that hard. Something like this should do the trick. I can't say that I have actually tried this since I don't have mod_python installed currently but you should be able to call logging.root.addHandler(ApacheLogHandler()) somewhere and get it to work out. YMMV.

import logging
import apache

class ApacheLogHandler(logging.Handler):
    LEVEL_MAP = {
        logging.DEBUG: apache.APLOG_DEBUG,
        logging.INFO: apache.APLOG_INFO,
        logging.WARNING: apache.APLOG_WARNING,
        logging.ERROR: apache.APLOG_ERR,
        logging.CRITICAL: apache.APLOG_CRIT,
        }
    def __init__(self, request=None):
        self.log_error = apache.log_error
        if request is not None:
            self.log_error = request.log_error
    def emit(self,record):
        apacheLevel = apache.APLOG_DEBUG
        if record.levelno in ApacheLogHandler.LEVEL_MAP:
            apacheLevel = ApacheLogHandler.LEVEL_MAP[record.levelno]
        self.log_error(record.getMessage(), apacheLevel)
D.Shawley
A: 

We use the following. It's documented completely here.

  1. We use logging.fileConfig with a logging.ini file.

  2. Each module uses logger= logging.getLogger(__name__)

  3. Then we can do logger.error("blah blah blah") throughout our application.

It works perfectly. The logging.ini file defines where the log file goes so that we can keep it with other log files for our web app.

S.Lott