如何使用python日志记录文件?

2024-05-14 23:01:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用pythonlogging工具将输出记录到不同的文件(每个模块都有自己的日志文件)。因此,我在每个python模块see examples的开头添加如下内容:

... other imports ...
import logging
logger = logging.getLogger('factory')
fh = logging.FileHandler('log/factory.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(funcName)s:%(lineno)d %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
... code ...

然后使用logger.info("text")来记录消息。但是,没有数据写入名为log/factory.log的文件,尽管它正在创建中!目录log存在,我有权写入该目录。使用logging工具和basicConfig可以很好地工作。。。在


Tags: 模块文件工具目录log内容factoryformatter
1条回答
网友
1楼 · 发布于 2024-05-14 23:01:24

更新

看起来它没有记录,因为logger的日志记录级别设置为logging.WARN。还必须将记录器的级别显式设置为logging.DEBUG。我认为没有创建log/factory.log文件,因为日志消息尚未到达该点。请参见http://dbgr.cc/v获取以下代码的实时演示:

import logging
import os

os.makedirs("log")

logger = logging.getLogger('factory')
fh = logging.FileHandler('log/factory.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(funcName)s:%(lineno)d %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)

# notice that only the warning message is written
logger.debug("DEBUG MESSAGE")
logger.warn("WARNING MESSAGE")
logger.info("INFO MESSAGE")

with open("log/factory.log", "r") as f:
    print f.read()

# now update the level on the Logger to logging.DEBUG:
logger.setLevel(logging.DEBUG)

logger.debug("DEBUG MESSAGE")
logger.warn("WARNING MESSAGE")
logger.info("INFO MESSAGE")

with open("log/factory.log", "r") as f:
    print f.read()

http://dbgr.cc/7演示下面的代码:

^{pr2}$

相关问题 更多 >

    热门问题