如何使用Python日志记录到文件?
我想用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()