]> granicus.if.org Git - python/commitdiff
Updated logging cookbook with additional example for output using str.format().
authorVinay Sajip <vinay_sajip@yahoo.co.uk>
Sat, 30 Mar 2013 11:56:18 +0000 (11:56 +0000)
committerVinay Sajip <vinay_sajip@yahoo.co.uk>
Sat, 30 Mar 2013 11:56:18 +0000 (11:56 +0000)
Doc/howto/logging-cookbook.rst

index 8d58c8486a77fc33a431e01a91c291c374ced7cf..47406aa9eb7cdfd6679f658ed35184d034908c51 100644 (file)
@@ -1096,6 +1096,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