简体   繁体   中英

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?

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.

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'

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')}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM