Redirection of stdout to console and file with verbosity turned on or off
Question: I have written some code just to practice verbosity in python. Verbosity is
embedded by means of the `ArgumentParser` module. However, I'd also like to
write the `stdout` to file also when verbosity is disabled:

    
    
    #!/usr/bin/python                                                               
    import sys
    
    def printable1():
        print "1"
    
    def printable2():
        print "2"
    
    def printable3():
        print "3"
    
    def Main1():
        printable1()
        printable2()
    
    def Main2():
        printable2()
        printable3()
    
    class Logger(object):
        def __init__(self):
            self.terminal = sys.stdout
            self.log = open("logfile2.log", "a")
    
        def write(self, message):
            self.terminal.write(message)
            self.log.write(message)
    
    
    if __name__ == "__main__":
        from argparse import ArgumentParser
    
        parser = ArgumentParser(description='PC Test',version="1.0")
        parser.add_argument('--nopc',action='store_true', help='Do not perform test on the PC')
        parser.add_argument('--pc', action='store_true', help='Do perform test on the PC')
    
        # VERBOSITY 
        parser.add_argument('--vmode', dest='verbose', action='store_true',
                            help='Enable printing of status messages to stdout.')
    
        args = parser.parse_args()
    
        sys.stdout = Logger()
    
        if args.verbose:
            if args.pc:       
                Main1()
            elif args.nopc:
                Main2()
            else:
                Main1()
                Main2()  
    

This code writes the stdout to file only when verbosity is enabled with the
`--vmode` argument. Can you help me to find a solution?


Answer: Instead of reinventing the wheel, you could use the
[logging](http://docs.python.org/2/library/logging.html) module to handle
printing to terminal and writing into a file. The verbosity part is still up
to you:

    
    
    import logging
    import logging.handlers
    log = logging.getLogger(__name__)
    log.addHandler(logging.StreamHandler())  # Prints to console.
    log.addHandler(logging.handlers.RotatingFileHandler('logfile2.log'))
    log.setLevel(logging.INFO)  # Set logging level here.
    

Since now on, you can use that regular `log` object to perform logging in your
script, and the entries will be both sent to console and to the file:

    
    
    log.info('test')
    log.warning('test')
    

Also, I recommend using
[ConfigDict](http://docs.python.org/2/library/logging.config.html) to handle
registering loggers and handlers - a more declarative alternative to the way
above (you'll still need to instantiate `log` object as above).

