[issue22195] Make it easy to replace print() calls with logging calls

Vinay Sajip report at bugs.python.org
Fri Aug 15 16:07:15 CEST 2014


Vinay Sajip added the comment:

Here's a tentative suggestion. Does it meet your needs?

import logging
import sys

class LoggerWriter(object):
    def __init__(self, logger='', level=logging.DEBUG):
        if isinstance(logger, str):
            logger = logging.getLogger(logger)
        self.logger = logger
        self.level = level
        self.buffer = ''

    def _output(self, force):
        lines = self.buffer.split('\n')
        if force:
            self.buffer = ''
        else:
            self.buffer = lines.pop()
        for line in lines:
            self.logger.log(self.level, line)

    def flush(self):
        self._output(True)

    def write(self, text):
        self.buffer += text
        self._output(False)


def main():
    stream = LoggerWriter()
    with open('lwtest.txt', 'w') as f:
        print('foo', 1, 'bar\n\n', 2.0, 'baz', file=stream)
        print(file=stream)
        print('foo', 1, 'bar\n\n', 2.0, 'baz', file=f)
        print(file=f)
        print('frob', end=' ', file=stream)
        print('frob', end=' ', file=f)
        f.flush()
    stream.flush()

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s %(message)s',
                        filename='lwtest.log')
    sys.exit(main())

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue22195>
_______________________________________


More information about the Python-bugs-list mailing list