Python日志配置文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4441842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:45:13  来源:igfitidea点击:

Python logging configuration file

pythonlogging

提问by Scott

I seem to be having some issues while attempting to implement logging into my python project.

我在尝试登录我的 python 项目时似乎遇到了一些问题。

I'm simply attempting to mimic the following configuration:

我只是试图模仿以下配置:

Python Logging to Multiple Destinations

Python 记录到多个目的地

However instead of doing this inside of code, I'd like to have it in a configuration file.

但是,我不想在代码中执行此操作,而是希望将其放在配置文件中。

Below is my config file:

下面是我的配置文件:

[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,)

The problem is that my screen output looks like:
2010-12-14 11:39:04,066 - root - WARNING - 3
2010-12-14 11:39:04,066 - root - ERROR - 4
2010-12-14 11:39:04,066 - root - CRITICAL - 5

问题是我的屏幕输出看起来像:
2010-12-14 11:39:04,066 - root - WARNING - 3
2010-12-14 11:39:04,066 - root - ERROR - 4
2010-12-14 11:39 :04,066 - 根 - 关键 - 5

My file is output, but looks the same as above (although with the extra information included). However the debug and info levels are not output to either.

我的文件是输出,但看起来和上面一样(虽然包含了额外的信息)。然而,调试和信息级别不会输出到任何一个。

I am on Python 2.7

我在 Python 2.7

Here is my simple example showing failure:

这是我显示失败的简单示例:

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

采纳答案by bdeniker

It looks like you've set the levels for your handlers, but not your logger. The logger's level filters every message before it can reach its handlers and the default is WARNINGand above (as you can see). Setting the root logger's level to NOTSETas you have, as well as setting it to DEBUG(or whatever is the lowest level you wish to log) should solve your issue.

看起来您已经为处理程序设置了级别,但没有为记录器设置级别。记录器的级别会在每条消息到达其处理程序之前对其进行过滤,默认值为WARNING及以上(如您所见)。将根记录器的级别设置NOTSET为您拥有的级别,并将其设置为DEBUG(或您希望记录的最低级别)应该可以解决您的问题。

回答by Scott

Adding the following line to the root logger took care of my problem:

将以下行添加到根记录器解决了我的问题:

level=NOTSET

回答by wcc526

#!/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

I think you should add the disable_existing_loggers to false.

我认为您应该将 disable_existing_loggers 添加到 false。

回答by P113305A009D8M

Just add log level in [logger_root]. It is worked.

只需在[logger_root]. 它起作用了。

[logger_root]
level=DEBUG
handlers=screen,file