开发者

How to get file the Python logging module is currently logging to?

Is there a way to do this? If logging.config.fileConfig('so开发者_Go百科me.log') is the setter, what's the getter? Just curious if this exists.


For my basic usage of a single file log, this worked

logging.getLoggerClass().root.handlers[0].baseFilename


I needed to do something similar in a very simple logging environment, the following routine did the trick

def _find_logger_basefilename(self, logger):
    """Finds the logger base filename(s) currently there is only one
    """
    log_file = None
    parent = logger.__dict__['parent']
    if parent.__class__.__name__ == 'RootLogger':
        # this is where the file name lives
        for h in logger.__dict__['handlers']:
            if h.__class__.__name__ == 'TimedRotatingFileHandler':
                log_file = h.baseFilename
    else:
        log_file = self._find_logger_basefilename(parent)

    return log_file    

I was looking for the file used by the TimedRotatingFileHandler you might need to change the type of handler you search for, probably FileHandler.

Not sure how it would go in any sort of complex logging environment.


Below simple logic for single file handler:

>>> import logging
>>> logger = logging.getLogger("test")
>>> handler = logging.FileHandler("testlog.log")
>>> logger.addHandler(handler)
>>> print logger.handlers[0].baseFilename
/home/nav/testlog.log
>>>


logging.config.fileConfig('some.log') is going to try to read logging configuration from some.log.

I don't believe there is a general way to retrieve the destination file -- it isn't always guaranteed to even be going to a file. (It may go to syslog, over the network, etc.)


In my case, I used to initialize a single logger (in my main script) and use that in all my packages by doing locallogger = logging.getLogger(__name__). In this setup to get the logging file path I had to modify @John's answer as follows

def find_rootlogger_basefilename():
"""Finds the root logger base filename
"""
log_file = None
rootlogger = logging.getLogger('')
for h in rootlogger.__dict__['handlers']:
    if h.__class__.__name__ == 'FileHandler':
        log_file = h.baseFilename
        break
    elif h.__class__.__name__ == 'TimedRotatingFileHandler':
        log_file = h.baseFilename
        break

return log_file   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜