lundi 4 juillet 2016

how to capture log data in stdout as well as in log file in python

I am running testsuite using in Flask-Python. Below is my sample code to configure logging. I want the output in stdout as well as in log file i.e.logger.log in my case

class StreamToLogger(object):
    def __init__(self, logger, log_level=logging.INFO):
        self.logger = logger
        self.log_level = log_level
        self.linebuf = ''

    def write(self, buf):
        for line in buf.rstrip().splitlines():
            self.logger.log(self.log_level, line.rstrip())



logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s:%(levelname)s:%(name)s:%(message)s',
                    filename="logger.log",
                    filemode='w'
                    )

stdout_logger = logging.getLogger('STDOUT')
sl = StreamToLogger(stdout_logger, logging.INFO)
sys.stdout = sl

stderr_logger = logging.getLogger('STDERR')
sl = StreamToLogger(stderr_logger, logging.ERROR)
sys.stderr = sl

suite = suite()
tests = unittest.TextTestRunner(descriptions=True, verbosity=2).run(suite)

When I run testsuite it actully write the data to logger.log but not on console or stdout. I also tried with

tests = unittest.TextTestRunner(descriptions=True, verbosity=2, 
                                stream=sys.stdout).run(suite)

Need solution for this problem. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire