如何读取日志文件?

How can I read log file?

我正在学习登录 python。但是,我无法在任何地方找到日志文件。下面是一个示例代码

import logging

logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(filename='my_app.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('This will get logged')

file = open('my_app.log', 'r')

很遗憾,结果是。

FileNotFoundError: [Errno 2] No such file or directory: 'my_app.log'

我很纳闷。怎么了?

感谢 Felix,我找到了解决方案。结合两个 logging.basicConfig 行有帮助。工作代码如下所示:

import logging

logging.basicConfig(filename='my_app.log',
                    filemode='w',
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    level=logging.DEBUG)
logging.debug('This will get logged')

显然后面的 logging.basicConfig 命令将被忽略

您可以修改您的代码如下:

import logging

logging.basicConfig(filename="my_app.log",
                                    filemode='a',
                                    format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                                    datefmt='%H:%M:%S',
                                    level=logging.DEBUG)
logging.debug('This will get logged')

file = open('my_app.log', 'r')

问题似乎是您在 logging.basicConfig(filename='my_app.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s') 之前设置了 logging.basicConfig(level=logging.DEBUG) 相反,您可以将它们组合为:

logging.basicConfig(filename="my_app.log",
                                    filemode='a',
                                    format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                                    datefmt='%H:%M:%S',
                                    level=logging.DEBUG)