Reputation: 237
How can I log into a file as well as to to wxpython txt ctrl ?
Background I have wxpython GUI based application which enumerates python test files and executes them. With the help of http://broadcoder.blogspot.com/2009/10/redirecting-python-logging-to.html I was able to redirect python logging messages to the txtctrl. However I will also like to redirect logging messages to log files also. I import my testfiles like this:
logging.info('Started')
testid = __import__(str)
reload(testid)
testOut = testid.main()
In each of my testfiles I simply use import logging and my logging messages get redirected to the txt ctrl. However I would also like that the test log messages also be redirected to a log file based on the name of the file. How do I redirect my log messages to both? If I use logging.basicConfig in my test file messages are still directed only to the text ctrl. My TestGUI.py in which I import say 5 python test files. In my test file files I simply use import logging while I setup the logger in my TestGUI.py file
self.logr = logging.getLogger('')
self.logr.setLevel(logging.INFO)
hdlr = WxLog(self.log)
hdlr.setFormatter(logging.Formatter('%(message)s '))
self.logr.addHandler(hdlr)
In my test file I do something like this:
logger = logging.getLogger('')
fh = logging.FileHandler("log.html",mode='w')
formatter = logging.Formatter('%(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
a= 5
b= 6
logging.info('a=5')
logging.info('b=6')
c= a+b
logging.info('adding b and c')
fh.close()
I get ValueError: I/O operation on closed file when I run this test more than once .
Upvotes: 1
Views: 819
Reputation: 14335
One Logger can have multiple handlers ! so you can achieve this easily.
example
import logging
logger = logging.getLogger('myapp')
hdlr = logging.FileHandler('var/myapp.log')
hdlr2 = logging.FileHandler('var/myapp2.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
hdlr2.setFormatter(formatter)
logger.addHandler(hdlr)
logger.addHandler(hdlr2)
logger.setLevel(logging.INFO)
logger.info('a log message')
Upvotes: 5