python - 如何在 getLogger() 之后从日志中获取日志文件路径

标签 python logging

如何获取给定 python 实例的日志文件路径 logging调用 getLogger() 后的对象?

我的 python 应用程序在主 python 脚本中设置日志记录如下。

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

然后同一应用程序中的其他脚本使用 getLogger() 获取该日志记录配置如下

import logging

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

在仅使用 getLogger() 获取日志配置的第二个脚本中,我想知道日志文件的路径。

在使用 getLogger() 设置日志后,如何确定日志文件的完整路径?

最佳答案

您可以通过检查根记录器的处理程序并检查其 baseFilename

来获取日志文件的文件名(如果有的话)

tl;博士

例如,从这个更新你的例子

import logging

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

对此

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) )

解决方案

实际上,getLogger() 设置的日志记录实例可以写入零个或多个 个日志文件。

您可以使用 hasHandlers() 检查是否有任何日志文件被写入root logger 上的功能(名为 logger.root)。

logger.root.hasHandlers():

hasHandlers() 如果大于零 Handlers 将返回 True被日志记录对象使用。

从那里,您可以通过使用 logger.root.handlers 遍历根记录器中的处理程序列表来获取处理程序列表。

在上面的示例中,我们只获取第一个处理程序(列表中的第 0 项)。

logger.root.handlers[0]

我没有在任何地方找到它的文档,但是如果你 check the code of the logging module's FileHandler class ,然后您可以看到它有一个名为 baseFilename 的实例变量,其中包含 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)

所以只需将名为baseFilename 的实例变量附加到第一个文件处理程序的末尾,您就可以获得日志文件的绝对路径

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

关于python - 如何在 getLogger() 之后从日志中获取日志文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72910245/

相关文章:

python - 如何在 Python 中使用 gunicorn 的日志记录模块

Java 日志记录 : log everything >debug but only when an error occured

python - 尽管有 --pylab inline 选项,但 Matplotlib 输出未在 IPython Notebook 中内联显示

python - 如何使用正则表达式对列标题进行分组?

javascript - IE8 中的 console.log 发生了什么?

linux - 系统日志问题

javascript - Node 记录未捕获的异常(Winston V3)

python - 导入错误 : No module named 'tweepy.streaming' ; 'tweepy' is not a package

python - AttributeError:未知属性 axisbg

python - 水印两个 pdf - 第一个的每一页和第二个的每一页