Python日志记录配置文件 [英] Python logging configuration file

查看:207
本文介绍了Python日志记录配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

I'm simply attempting to mimic the following configuration:

将Python记录到多个目标位置

但是,我希望将其存储在配置文件中,而不是在代码内部进行

However instead of doing this inside of code, I'd like to have it in a configuration 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,)

问题是我的屏幕输出如下所示:
2010-12-14 11:39:04,066-根-警告-3
2010-12-14 11:39:04,066-根-错误-4
2010-12-14 11:39:04,066-根-严重-5

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

我的文件已输出,但外观与上面相同(尽管包含了额外的信息).但是,调试和信息级别均不会输出到任何一个.

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.

我使用的是python 2.7

I am on 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()

推荐答案

似乎您已经为处理程序设置了级别,但没有为记录器设置级别.记录器的级别会过滤每条消息,然后才能到达其处理程序,默认值为WARNING及更高版本(如您所见).将根记录器的级别设置为NOTSET,并将其设置为DEBUG(或您希望记录的最低级别)应该可以解决您的问题.

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

这篇关于Python日志记录配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆