如何获取Python日志模块当前记录的文件?

15 投票
5 回答
23866 浏览
提问于 2025-04-16 01:42

有没有办法做到这一点呢?如果 logging.config.fileConfig('some.log') 是设置器,那获取器是什么呢?我只是好奇这个东西是否存在。

5 个回答

10

我需要在一个非常简单的日志记录环境中做类似的事情,下面这个程序解决了我的问题。

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    

我在找TimedRotatingFileHandler使用的文件,你可能需要换一种查找的处理器类型,可能是FileHandler。

不太确定在任何复杂的日志记录环境中会怎么样。

20

对于我简单使用的单文件日志,这个方法有效。

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

logging.config.fileConfig('some.log') 这个命令会尝试从 some.log 文件中读取日志的设置。

我觉得没有一种通用的方法可以获取日志的输出文件,因为日志不一定总是会写入一个文件。(它可能会发送到系统日志、通过网络传输等等。)

撰写回答