So I would like to log errors in memory (I don't want to write any logfile) and access them later to display them in a bulk after the program execution. It would look like:
...
Program executing ...
...
Errors occured !
Error 1 : ...
Error 2 : ...
I am not asking how to do it myself but if some existing module is capable of that. I would like to use standard modules as much as possible.
You could pass a StringIO buffer to a StreamHandler of the standard logging module. In Python2:
import logging, StringIO
print 'Setting up logging ...'
stream = StringIO.StringIO()
logger = logging.getLogger()
handler = logging.StreamHandler(stream)
logger.addHandler(handler)
print 'Starting main program ...'
logger.warning('This is serious')
logger.error('This is really bad')
print 'Finished main, printing log messages ...'
print stream.getvalue()
As commented by Hettomei, the imports should be changed slightly for Python3:
import logging, io
print('Setting up logging ...')
stream = io.StringIO()
logger = logging.getLogger()
handler = logging.StreamHandler(stream)
logger.addHandler(handler)
print('Starting main program ...')
logger.warning('This is serious')
logger.error('This is really bad')
print('Finished main, printing log messages ...')
print(stream.getvalue())
In both cases, you get the desired result:
Setting up logging ...
Starting main program ...
Finished main, printing log messages ...
This is serious
This is really bad
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With