How to duplicate sys.stdout to a log file?

前端 未结 17 921
醉酒成梦
醉酒成梦 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:49

    (Ah, just re-read your question and see that this doesn't quite apply.)

    Here is a sample program that makes uses the python logging module. This logging module has been in all versions since 2.3. In this sample the logging is configurable by command line options.

    In quite mode it will only log to a file, in normal mode it will log to both a file and the console.

    import os
    import sys
    import logging
    from optparse import OptionParser
    
    def initialize_logging(options):
        """ Log information based upon users options"""
    
        logger = logging.getLogger('project')
        formatter = logging.Formatter('%(asctime)s %(levelname)s\t%(message)s')
        level = logging.__dict__.get(options.loglevel.upper(),logging.DEBUG)
        logger.setLevel(level)
    
        # Output logging information to screen
        if not options.quiet:
            hdlr = logging.StreamHandler(sys.stderr)
            hdlr.setFormatter(formatter)
            logger.addHandler(hdlr)
    
        # Output logging information to file
        logfile = os.path.join(options.logdir, "project.log")
        if options.clean and os.path.isfile(logfile):
            os.remove(logfile)
        hdlr2 = logging.FileHandler(logfile)
        hdlr2.setFormatter(formatter)
        logger.addHandler(hdlr2)
    
        return logger
    
    def main(argv=None):
        if argv is None:
            argv = sys.argv[1:]
    
        # Setup command line options
        parser = OptionParser("usage: %prog [options]")
        parser.add_option("-l", "--logdir", dest="logdir", default=".", help="log DIRECTORY (default ./)")
        parser.add_option("-v", "--loglevel", dest="loglevel", default="debug", help="logging level (debug, info, error)")
        parser.add_option("-q", "--quiet", action="store_true", dest="quiet", help="do not log to console")
        parser.add_option("-c", "--clean", dest="clean", action="store_true", default=False, help="remove old log file")
    
        # Process command line options
        (options, args) = parser.parse_args(argv)
    
        # Setup logger format and output locations
        logger = initialize_logging(options)
    
        # Examples
        logger.error("This is an error message.")
        logger.info("This is an info message.")
        logger.debug("This is a debug message.")
    
    if __name__ == "__main__":
        sys.exit(main())
    

提交回复
热议问题