Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a module to log errors in memory?

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.

like image 484
ElefEnt Avatar asked Apr 01 '14 10:04

ElefEnt


1 Answers

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
like image 135
Bas Swinckels Avatar answered Oct 29 '22 04:10

Bas Swinckels