direct print to log file

Diez B. Roggisch deets at web.de
Tue Oct 5 10:01:03 EDT 2010


Dirk Nachbar <dirknbr at gmail.com> writes:

> How can I direct all print to a log file, eg some functions have their
> own print and I cannot put a f.write() in front of it.

you can replace sys.stdout with something that performs logging.

class MyWriter(object):

      def __init__(self, old_stream):
          self.old_stream = old_stream
          self.logger = logging.getLogger("stdout")


      def write(self, msg):
          self.old_stream.write(msg)
          self.logger.debug(msg)


sys.stdout = MyWriter(sys.stdout)

Untested - but you get the gist.

Diez



More information about the Python-list mailing list