hyades
hyades

Reputation: 3170

How to get filename from a python logger

I have the following code

job_logger = logging.getLogger("abc")
job_handler = logging.FileHandler(filename)
job_logger.addHandler(job_handler)
print job_logger.something

I want to know the filename from the job_logger object. Any ideas?

Upvotes: 23

Views: 24489

Answers (3)

celaeno
celaeno

Reputation: 834

a comment rather, but with code formatting baseFilename exists only in FileHandler subclass, thus

for handler in job_logger.handlers:
    if hasattr(handler, "baseFilename"):
        print(f"writing log to {getattr(handler, 'baseFilename')}")

Upvotes: 1

Albert Alomar
Albert Alomar

Reputation: 127

You can get a list of the handlers used in a logger using:

>>>handlers = job_logger.handlers
>>>handlers
[<FileHandler ./mypath/job_logger.log (NOTSET)>]

As in your case you only have one, @starrify solution should be enough:

>>>handlers[0].baseFilename
'./mypath/job_logger.log'

In case you have more handlers and some are not FileHandlers you can filter them with a list comprehension:

>>> log_paths = [handler.baseFilename for handler in job_logger.handlers if isinstance(handler, logging.FileHandler)]
>>> next(iter(log_paths))
'./mypath/job_logger.log'

Upvotes: 4

starrify
starrify

Reputation: 14751

Assuming the job_logger object has only one handler for now.

>>> handler = job_logger.handlers[0]
>>> filename = handler.baseFilename
>>> print(filename)
'/tmp/test_logging_file'

And when there're multiple handlers, design your logic to get them all or get the very last one.

Upvotes: 25

Related Questions