Skip to content
Advertisement

How to get all previous logs written during current run (python logging)

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

import loggging

logging.basicConfig(
 filename = '/path/to/log/file.log,
 filemode = 'a',
 format = '%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
 datefmt = '%H:%M:%S',
 level = logging.DEBUG
)

logging.info("===============================================================================")
logging.info( "INFO: Starting Application Logging" )

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

import logging
logger = logging.getLogger( __name__ )

# attempt to get debug log contents
if logger.root.hasHandlers():
   logfile_path = logger.root.handlers[0].baseFilename

   with open(logfile_path) as log_file:
      log_history = log_file.read()
Advertisement