Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8028a5c

Browse files
committed
Updated logging cookbook with additional example for output using str.format().
1 parent b40a220 commit 8028a5c

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Doc/howto/logging-cookbook.rst

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1096,6 +1096,40 @@ parentheses go around the format string and the arguments, not just the format
10961096
string. That's because the __ notation is just syntax sugar for a constructor
10971097
call to one of the XXXMessage classes.
10981098

1099+
If you prefer, you can use a :class:`LoggerAdapter` to achieve a similar effect
1100+
to the above, as in the following example::
1101+
1102+
import logging
1103+
1104+
class Message(object):
1105+
def __init__(self, fmt, args):
1106+
self.fmt = fmt
1107+
self.args = args
1108+
1109+
def __str__(self):
1110+
return self.fmt.format(*self.args)
1111+
1112+
class StyleAdapter(logging.LoggerAdapter):
1113+
def __init__(self, logger, extra=None):
1114+
super(StyleAdapter, self).__init__(logger, extra or {})
1115+
1116+
def log(self, level, msg, *args, **kwargs):
1117+
if self.isEnabledFor(level):
1118+
msg, kwargs = self.process(msg, kwargs)
1119+
self.logger._log(level, Message(msg, args), (), **kwargs)
1120+
1121+
logger = StyleAdapter(logging.getLogger(__name__))
1122+
1123+
def main():
1124+
logger.debug('Hello, {}', 'world!')
1125+
1126+
if __name__ == '__main__':
1127+
logging.basicConfig(level=logging.DEBUG)
1128+
main()
1129+
1130+
The above script should log the message ``Hello, world!`` when run with
1131+
Python 3.2 or later.
1132+
10991133

11001134
.. currentmodule:: logging
11011135

0 commit comments

Comments
 (0)