I’m using the python logging module. How can I get all of the previously outputted logs that have been written-out by logger
since the application started?
Let’s say I have some large application. When the application first starts, it sets-up logging with something like this
JavaScript
x
13
13
1
import loggging
2
3
logging.basicConfig(
4
filename = '/path/to/log/file.log,
5
filemode = 'a',
6
format = '%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
7
datefmt = '%H:%M:%S',
8
level = logging.DEBUG
9
)
10
11
logging.info("===============================================================================")
12
logging.info( "INFO: Starting Application Logging" )
13
A few hours or days later I want to be able to get the history of all of the log messages ever written by logging
and store that to a variable.
How can I get the history of messages written by the python logging
module since the application started?
Advertisement
Answer
If you’re writing to a log file, then you can simply get the path to the log file and then read its contents
JavaScript
1
10
10
1
import logging
2
logger = logging.getLogger( __name__ )
3
4
# attempt to get debug log contents
5
if logger.root.hasHandlers():
6
logfile_path = logger.root.handlers[0].baseFilename
7
8
with open(logfile_path) as log_file:
9
log_history = log_file.read()
10