简体   繁体   English

Python日志配置文件

[英]Python logging configuration file

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 - 根 - 警告 - 3
2010-12-14 11:39:04,066 - root - ERROR - 4 2010-12-14 11:39:04,066 - 根 - 错误 - 4
2010-12-14 11:39:04,066 - root - CRITICAL - 5 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()

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 WARNING and above (as you can see).记录器的级别会在每条消息到达其处理程序之前对其进行过滤,默认值为WARNING及以上(如您所见)。 Setting the root logger's level to NOTSET as you have, as well as setting it to DEBUG (or whatever is the lowest level you wish to log) should solve your issue.将根记录器的级别设置为NOTSET ,并将其设置为DEBUG (或您希望记录的最低级别)应该可以解决您的问题。

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

level=NOTSET

Just add log level in [logger_root] .只需在[logger_root]添加日志级别。 It is worked.它起作用了。

[logger_root]
level=DEBUG
handlers=screen,file
#!/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。

A simple approach to both write to terminal and file would be as following:写入终端和文件的简单方法如下:

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

And then use it in your code like this:然后在您的代码中使用它,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM