ElefEnt
ElefEnt

Reputation: 2127

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.

Upvotes: 8

Views: 4106

Answers (1)

Bas Swinckels
Bas Swinckels

Reputation: 18488

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

Upvotes: 13

Related Questions