如何使用Python日志记录到文件?

0 投票
1 回答
5607 浏览
提问于 2025-04-18 10:17

我想用Python的logging功能把输出记录到不同的文件里(每个模块都有自己的日志文件)。所以,我在每个Python模块的开头加了类似下面的代码可以查看示例

... 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("文本")来记录信息。不过,虽然文件log/factory.log被创建了,但里面没有写入任何数据!目录log是存在的,我也有权限往里面写东西。使用logging功能和basicConfig搭配使用是没问题的……

1 个回答

5

更新

看起来日志没有记录是因为 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 上演示下面的代码:

import logging
import os

os.makedirs("log")

formatter = logging.Formatter('%(asctime)s %(levelname)s: %(funcName)s:%(lineno)d %(message)s')

# create logger with 'spam_application'
logger = logging.getLogger('factory')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('log/factory.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)

# just so we can see things as they happen in stdout/stderr
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)

logger.debug("Debug log msg")
logger.info("Info log msg")
logger.warn("Warning log msg")

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

撰写回答