How to duplicate sys.stdout to a log file?

前端 未结 17 1189
醉酒成梦
醉酒成梦 2020-11-22 06:54

Edit: Since it appears that there\'s either no solution, or I\'m doing something so non-standard that nobody knows - I\'ll revise my question to also ask: What is the best w

17条回答
  •  庸人自扰
    2020-11-22 07:50

    As described elsewhere, perhaps the best solution is to use the logging module directly:

    import logging
    
    logging.basicConfig(level=logging.DEBUG, filename='mylog.log')
    logging.info('this should to write to the log file')
    

    However, there are some (rare) occasions where you really want to redirect stdout. I had this situation when I was extending django's runserver command which uses print: I didn't want to hack the django source but needed the print statements to go to a file.

    This is a way of redirecting stdout and stderr away from the shell using the logging module:

    import logging, sys
    
    class LogFile(object):
        """File-like object to log text using the `logging` module."""
    
        def __init__(self, name=None):
            self.logger = logging.getLogger(name)
    
        def write(self, msg, level=logging.INFO):
            self.logger.log(level, msg)
    
        def flush(self):
            for handler in self.logger.handlers:
                handler.flush()
    
    logging.basicConfig(level=logging.DEBUG, filename='mylog.log')
    
    # Redirect stdout and stderr
    sys.stdout = LogFile('stdout')
    sys.stderr = LogFile('stderr')
    
    print 'this should to write to the log file'
    

    You should only use this LogFile implementation if you really cannot use the logging module directly.

提交回复
热议问题