开发者

Automatically append some text to every log message

An appl开发者_开发问答ication I'm working on uses the logging module to log errors etc. In such a case it would be nice to be able to include the HTTP referer, GET/POST arguments etc. in the log entry.

While it would be possible to append it to the message before calling .error() etc, I'm looking for a way to do it at a central location (without wrapping those functions of course).


I've never tried it, but I think that you can do it by specifying a FORMAT with logging.basicConfig.

From the logging documentation:

FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning("Protocol problem: %s", "connection reset", extra=d)

would print something like:

2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset


I now solved it using a custom formatter:

class IndicoMailFormatter(logging.Formatter):
    def format(self, record):
        s = super(IndicoMailFormatter, self).format(record)
        return s + self._getRequestInfo()

    def _getRequestInfo(self):
        info = ['Additional information:']
        # ...
        return '\n\n%s' % '\n'.join(info)

This formatter can be easily set using the class option in logging.conf (or via python code).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜