Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Capturing Python Log Output In A Variable

While working on a Sublime Text plugin, I needed to capture logging output in a variable so I could display it easily. For once, Stack Overflow 1 didn't have an immediate solution. After a couple hours of hacking around, I came up with the following which I hope saves others the hassle of having to build it themselves.

import logging import io

### Create the logger logger = logging.getLogger('basic _ logger') logger.setLevel(logging.DEBUG)

### Setup the console handler with a StringIO object log _ capture _ string = io.StringIO() ch = logging.StreamHandler(log _ capture _ string) ch.setLevel(logging.DEBUG)

### Optionally add a formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter)

### Add the console handler to the logger logger.addHandler(ch)

### Send log messages. logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message')

### Pull the contents back into a string and close the stream log _ contents = log _ capture _ string.getvalue() log _ capture _ string.close()

### Output as lower case to prove it worked. print(log _ contents.lower())

*Note that once you call '.close()', it's possible to run into problems if the same running process tries to call the function again.*

This approach will work with external files too. If you assign the same logger (in this case 'basic _ logger') it will output properly. For example, if you have an module in an external file called 'external _ logger _ test.py' with the content :

import logging

def log _ test() :

logger = logging.getLogger('basic _ logger')

logger.warning('Log note from external file')

All you have to do is import it as usual in your main file (e.g. ` import external _ logger _ test ` ) and then call the function :

external _ logger _ test.log _ test()

Of course, you have to do this before you call the ` log _ contents = log _ capture _ string.getvalue() ` . That's where the log data stops flowing.

_ Links and Notes _

1. Stack Overflow - Friend to developers around the world. Far and away the most useful development research site there is.