【发布时间】:2013-01-02 14:26:18
【问题描述】:
了解 Python 日志语句存储位置的方法是什么?
即如果我这样做:
import logging
log = logging.getLogger(__name__)
log.info('Test')
在哪里可以找到日志文件?另外,当我打电话时:
logging.getLogger(__name__)
这是否与记录器的行为/保存方式有关?
【问题讨论】:
了解 Python 日志语句存储位置的方法是什么?
即如果我这样做:
import logging
log = logging.getLogger(__name__)
log.info('Test')
在哪里可以找到日志文件?另外,当我打电话时:
logging.getLogger(__name__)
这是否与记录器的行为/保存方式有关?
【问题讨论】:
对此有一些很好的答案,但最佳答案对我不起作用,因为我使用的是不同类型的文件处理程序,并且 handler.stream 不提供路径,而是提供文件句柄,并获取路径其中有些不明显。这是我的解决方案:
import logging
from logging import FileHandler
# note, this will create a new logger if the name doesn't exist,
# which will have no handlers attached (yet)
logger = logging.getLogger('<name>')
for h in logger.handlers:
# check the handler is a file handler
# (rotating handler etc. inherit from this, so it will still work)
# stream handlers write to stderr, so their filename is not useful to us
if isinstance(h, FileHandler):
# h.stream should be an open file handle, it's name is the path
print(h.stream.name)
【讨论】:
很好的问题@zallarak。不幸的是,虽然它们很容易创建,但 Loggers 很难检查。这将获取所有Handlers 的文件名以获取logger:
filenames = []
for handler in logger.handlers:
try:
filenames.append(handler.fh.name)
except:
pass
try 块处理文件名查找失败时发生的异常。
【讨论】:
要获取简单文件记录器的日志位置,请尝试
logging.getLoggerClass().root.handlers[0].baseFilename
【讨论】:
要查找日志文件位置,请尝试在您的环境中的 Python shell 中实例化您的 log 对象并查看以下值:
log.handlers[0].stream
【讨论】:
logging 模块使用附加到记录器的处理程序来决定消息最终存储或显示的方式、位置或什至。您也可以默认配置logging 以写入文件。您真的应该阅读docs,但是如果您调用logging.basicConfig(filename=log_file_name),其中log_file_name 是您希望写入消息的文件的名称(请注意,您必须在调用logging 中的任何其他内容之前执行此操作。 ),然后记录到所有记录器的所有消息(除非稍后发生进一步的重新配置)将被写入那里。请注意记录器设置的级别;如果有记忆,info 低于默认日志级别,因此您还必须在 basicConfig 的参数中包含 level=logging.INFO,以便您的消息最终出现在文件中。
关于您问题的另一部分,logging.getLogger(some_string) 返回一个Logger 对象,该对象从根记录器插入到层次结构中的正确位置,名称为some_string 的值。不带参数调用,它返回根记录器。 __name__ 返回当前模块的名称,所以logging.getLogger(__name__) 返回一个名称设置为当前模块名称的Logger 对象。这是与logging 一起使用的常见模式,因为它会导致记录器结构反映代码的模块结构,这通常会使记录消息在调试时更加有用。
【讨论】:
example_logger = logging.getLogger('example') 配置的记录器对象)上设置处理程序。因此,您可以删除现有的处理程序并再次调用基本配置。或者,您可以创建一个不同的记录器对象example2_logger = logging.getLogger('example') 并在此对象上设置不同的配置。