Python日志配置文件

48

我在尝试将日志记录功能添加到我的Python项目中时遇到了一些问题。

我只是想模仿以下配置:

Python Logging to Multiple Destinations

但是,我希望将其放在配置文件中,而不是在代码中实现。

以下是我的配置文件:

[loggers]
keys=root

[logger_root]
handlers=screen,file

[formatters]
keys=simple,complex

[formatter_simple]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

[formatter_complex]
format=%(asctime)s - %(name)s - %(levelname)s - %(module)s : %(lineno)d - %(message)s

[handlers]
keys=file,screen

[handler_file]
class=handlers.TimedRotatingFileHandler
interval=midnight
backupCount=5
formatter=complex
level=DEBUG
args=('logs/testSuite.log',)

[handler_screen]
class=StreamHandler
formatter=simple
level=INFO
args=(sys.stdout,)

问题在于我的屏幕输出看起来像:
2010-12-14 11:39:04,066 - root - 警告 - 3
2010-12-14 11:39:04,066 - root - 错误 - 4
2010-12-14 11:39:04,066 - root - 严重 - 5

我的文件已经输出,但是与上面的内容相同(尽管包含了额外的信息)。然而,调试和信息级别都没有输出。

我使用的是Python 2.7

这是一个简单的示例,显示了失败:

import os
import sys
import logging
import logging.config

sys.path.append(os.path.realpath("shared/"))
sys.path.append(os.path.realpath("tests/"))

class Main(object):

  @staticmethod
  def main():
    logging.config.fileConfig("logging.conf")
    logging.debug("1")
    logging.info("2")
    logging.warn("3")
    logging.error("4")
    logging.critical("5")

if __name__ == "__main__":
  Main.main()
5个回答

29

看起来你已经为你的处理程序设置了级别,但没有为记录器设置。记录器的级别会过滤掉每个消息,直到它能够到达处理程序,默认级别是WARNING及以上(正如你所看到的)。像你所做的那样将根记录器的级别设置为NOTSET,以及将其设置为DEBUG(或任何你想要记录的最低级别),应该可以解决你的问题。


16

将下面这行代码添加到根记录器中解决了我的问题:

level=NOTSET

6
只需在[logger_root]中添加日志级别,它就可以正常工作。
[logger_root]
level=DEBUG
handlers=screen,file

我也遇到了同样的问题。 - P113305A009D8M
但是,我在 [logger_root] 下添加了日志级别,并且它运行良好。 - P113305A009D8M
只需在logger_root下添加日志级别 @Scott - P113305A009D8M

5

同时输出到终端和文件的简单方法如下:

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')

2
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import logging.handlers
from logging.config import dictConfig

logger = logging.getLogger(__name__)

DEFAULT_LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
}
def configure_logging(logfile_path):
    """
    Initialize logging defaults for Project.

    :param logfile_path: logfile used to the logfile
    :type logfile_path: string

    This function does:

    - Assign INFO and DEBUG level to logger file handler and console handler

    """
    dictConfig(DEFAULT_LOGGING)

    default_formatter = logging.Formatter(
        "[%(asctime)s] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] [PID:%(process)d TID:%(thread)d] %(message)s",
        "%d/%m/%Y %H:%M:%S")

    file_handler = logging.handlers.RotatingFileHandler(logfile_path, maxBytes=10485760,backupCount=300, encoding='utf-8')
    file_handler.setLevel(logging.INFO)

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)

    file_handler.setFormatter(default_formatter)
    console_handler.setFormatter(default_formatter)

    logging.root.setLevel(logging.DEBUG)
    logging.root.addHandler(file_handler)
    logging.root.addHandler(console_handler)



[31/10/2015 22:00:33] [DEBUG] [yourmodulename] [yourfunction_name():9] [PID:61314 TID:140735248744448] this is logger infomation from hello module

我认为你应该将disable_existing_loggers设置为false。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接