python日志记录模块没有写任何文件

时间:2013-04-09 03:47:21

标签: python file logging

我正在尝试编写一个服务器,将异常记录到控制台和文件中。我从食谱中删了一些代码。这是:

logger = logging.getLogger('server_logger')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('server.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

此代码完美地记录到控制台,但没有记录到该文件。该文件已创建,但没有任何内容写入它。我试过关闭处理程序,但这没有做任何事情。也没有冲洗它。我搜索了互联网,但显然我是唯一有这个问题的人。有谁知道问题是什么?谢谢你的回答。

5 个答案:

答案 0 :(得分:24)

尝试拨打

logger.error('This should go to both console and file')

而不是

logging.error('this will go to the default logger which you have not changed the config of')

答案 1 :(得分:4)

尝试将import和basicConfig置于脚本的初始位置。像这样:

import logging
logging.basicConfig(filename='log.log', level=logging.INFO)
.
.
import ...
import ...

答案 2 :(得分:1)

我知道这个问题可能有点过于陈旧但我发现上述方法有点过分。我遇到了类似的问题,我能够解决它:

import logging

logging.basicConfig(format = '%(asctime)s %(message)s',
                    datefmt = '%m/%d/%Y %I:%M:%S %p',
                    filename = 'example.log',
                    level=logging.DEBUG)

这将写入example.log所有级别调试或更高级别的日志。

logging.debug("This is a debug message")会将This is a debug message写入example.log。水平对于此工作很重要。

答案 3 :(得分:1)

为了同时写入终端和文件,您可以执行以下操作:

import logging.config

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("log_file.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

代码中的用法:

logger.info('message')
logger.error('message')

答案 4 :(得分:0)

放置

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

的前面
logging.basicConfig(...)

另请参见 Logging module not writing to file