Python日志记录 - 检查日志文件的位置?

zal*_*rak 29 python linux logging file

了解Python日志语句存储位置的方法是什么?

即如果我这样做:

import logging
log = logging.getLogger(__name__)
log.info('Test')
Run Code Online (Sandbox Code Playgroud)

我在哪里可以找到日志文件?还有,当我打电话:

logging.getLogger(__name__)
Run Code Online (Sandbox Code Playgroud)

这是否与记录器的行为/保存方式有关?

Sil*_*Ray 23

logging模块使用附加到记录器的处理程序来决定消息最终存储或显示的方式,位置或方式.您也可以logging默认配置为写入文件.你真的应该阅读文档,但如果你调用logging.basicConfig(filename=log_file_name)哪里log_file_name就是你要写入(请注意,你有什么在别人面前做这个消息的文件的名称logging叫的话),那么所有消息记录到的所有记录(除将在那里写一些进一步的重新配置.请注意记录器设置的级别; 如果内存服务,info则低于默认日志级别,因此您必须level=logging.INFO在参数中包含basicConfig您的消息以在文件中结束.

至于问题的其他部分,logging.getLogger(some_string)返回一个Logger对象,从根记录器插入到层次结构中的正确位置,其名称为值some_string.没有参数调用,它返回根记录器. __name__返回当前模块的名称,因此logging.getLogger(__name__)返回一个Logger名称设置为当前模块名称的对象.这是一种常见的模式logging,因为它会导致记录器结构镜像代码的模块结构,这通常使得日志消息在调试时更有用.


Tar*_*ran 9

要获取简单文件记录器的日志位置,请尝试

logging.getLoggerClass().root.handlers[0].baseFilename
Run Code Online (Sandbox Code Playgroud)

  • 这假设记录器有一个 FileHandler,但情况并非总是如此。最好确保处理程序包含 FileHandler 对象。 (3认同)
  • 它也向我抛出一个异常:“AttributeError:'StreamHandler'对象没有属性'baseFilename'” (3认同)
  • 它向我抛出异常 (2认同)

Edw*_*cer 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)
Run Code Online (Sandbox Code Playgroud)