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

Ale*_*lex 0 python logging

我想使用 pythonlogging工具将输出记录到不同的文件(每个模块都有自己的日志文件)。因此,我在每个 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 ...
Run Code Online (Sandbox Code Playgroud)

然后用于logger.info("text")记录消息。但是,log/factory.log尽管正在创建名为的文件,但没有数据写入!该目录log存在并且我有权写入该目录。使用该logging设施basicConfig工作正常......

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

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()
Run Code Online (Sandbox Code Playgroud)