Python日志 - 如何查看日志文件的位置?
如何知道Python的日志信息存储在哪里?
比如,如果我执行:
import logging
log = logging.getLogger(__name__)
log.info('Test')
我可以在哪里找到日志文件?另外,当我调用:
logging.getLogger(__name__)
这和日志记录器的行为或保存方式有什么关系吗?
5 个回答
这里有一些不错的回答,但最好的那个对我没用,因为我用的是不同类型的文件处理器。而这个处理器的 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)
要找到一个简单文件记录器的日志位置,可以试试下面的代码:
logging.getLoggerClass().root.handlers[0].baseFilename
logging
模块通过将处理器附加到记录器来决定消息最终如何、在哪里存储或显示,甚至是否存储。你可以默认设置logging
将日志写入文件。虽然建议你查看一下文档,但如果你调用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
时常见的模式,因为它使得记录器的结构与代码的模块结构相对应,这样在调试时,日志消息会更加有用。