diff options
author | Vinay Sajip <vinay_sajip@yahoo.co.uk> | 2013-03-30 11:57:09 (GMT) |
---|---|---|
committer | Vinay Sajip <vinay_sajip@yahoo.co.uk> | 2013-03-30 11:57:09 (GMT) |
commit | 3fdd4f1935ba1bb4b45d77ed99281b134f3e6d24 (patch) | |
tree | da4f9bf56ca1cb5bc508d04cbce004b02b673896 /Doc | |
parent | 9d672384399e7bde8c058c64f85f3a2d5dfe20ac (diff) | |
parent | 8028a5cf15753c283b7308a32ecc4651db33c6c9 (diff) | |
download | cpython-3fdd4f1935ba1bb4b45d77ed99281b134f3e6d24.zip cpython-3fdd4f1935ba1bb4b45d77ed99281b134f3e6d24.tar.gz cpython-3fdd4f1935ba1bb4b45d77ed99281b134f3e6d24.tar.bz2 |
Merged documentation update from 3.3.
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/howto/logging-cookbook.rst | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/Doc/howto/logging-cookbook.rst b/Doc/howto/logging-cookbook.rst index e113564..efd8c1c 100644 --- a/Doc/howto/logging-cookbook.rst +++ b/Doc/howto/logging-cookbook.rst @@ -1094,6 +1094,40 @@ parentheses go around the format string and the arguments, not just the format string. That's because the __ notation is just syntax sugar for a constructor call to one of the XXXMessage classes. +If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar effect +to the above, as in the following example:: + + import logging + + class Message(object): + def __init__(self, fmt, args): + self.fmt = fmt + self.args = args + + def __str__(self): + return self.fmt.format(*self.args) + + class StyleAdapter(logging.LoggerAdapter): + def __init__(self, logger, extra=None): + super(StyleAdapter, self).__init__(logger, extra or {}) + + def log(self, level, msg, *args, **kwargs): + if self.isEnabledFor(level): + msg, kwargs = self.process(msg, kwargs) + self.logger._log(level, Message(msg, args), (), **kwargs) + + logger = StyleAdapter(logging.getLogger(__name__)) + + def main(): + logger.debug('Hello, {}', 'world!') + + if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + main() + +The above script should log the message ``Hello, world!`` when run with +Python 3.2 or later. + .. currentmodule:: logging |