How to get log file path from logging after getLogger()

Viewed 84

How can I get the path to the log file for a given instance of the python logging object after calling getLogger()?

My python application sets-up logging in the main python script as follows.

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( "Starting Application Logging" )

Then other scripts in the same app get that logging config with getLogger() as follows

import logging

logger = logging.getLogger( __name__ )
logger.info( "Logging Config Imported in Second Script" )

In the second script that only gets the logging config with getLogger(), I want to know the path to the log file.

How can I determine the full path to the log file after setting-up logging with getLogger()?

2 Answers

I think it's better you use addHandler, there you have an example

import logging
import sys

logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s', 
                              '%m-%d-%Y %H:%M:%S')

stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.DEBUG)
stdout_handler.setFormatter(formatter)

file_handler = logging.FileHandler('logs.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)

logger.addHandler(file_handler)
logger.addHandler(stdout_handler)

You can get the filename (if any) of the log file by inspecting the handlers of the root logger and checking its baseFilename

tl;dr

For example, update your example from this

import logging

logger = logging.getLogger( __name__ )
logger.info( "Logging Config Imported in Second Script" )

to this

import logging

logger = logging.getLogger( __name__ )
logger.info( "Logging Config Imported in Second Script" )

if logger.root.hasHandlers():
   logfile_path = logger.root.handlers[0].baseFilename
   logger.info( "Logging to File " + str(logfile_path) )

Solution

Actually, your instance of logging set by getLogger() can be writing to zero or many log files.

You can check to see if there are any log files being written-to by using the hasHandlers() function on the root logger (named logger.root).

logger.root.hasHandlers():

hasHandlers() will return True if there are more than zero Handlers being used by the logging object.

From there, you can get the list of handlers by iterating through the list of handlers in the root logger with logger.root.handlers.

In the example above, we just grab the first handler (the 0th item in the list).

logger.root.handlers[0]

I didn't find it documented anywhere, but if you check the code of the logging module's FileHandler class, then you can see it has an instance variable named baseFilename with the path to the file for the FileHandler

class FileHandler(StreamHandler):
    """
    A handler class which writes formatted logging records to disk files.
    """
    def __init__(self, filename, mode='a', encoding=None, delay=False, errors=None):
        """
        Open the specified file and use it as the stream for logging.
        """
...
        self.baseFilename = os.path.abspath(filename)

(source)

So just tack-on the instance variable named baseFilename to the end of the first file handler, and you get the absolute path to the log file

logfile_path = logger.root.handlers[0].baseFilename
Related