gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:38:27 27 4
gpt4 key购买 nike

如何获取给定 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com