文件处理程序的日志级别与记录器的日志级别 [英] Log level of file handler vs. that of logger

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

问题描述

要在没有 basicConfig的情况下在Python中设置日志记录,我们将完成以下步骤:

To set up logging in Python without basicConfig we would go through the steps:

  1. 设置文件处理程序.
  2. 设置文件处理程序的日志记录级别.
  3. 设置格式化程序.
  4. 将文件处理程序指向格式化程序.
  5. 获取记录器对象.
  6. 设置记录器对象的记录级别.
  7. 将文件处理程序作为处理程序添加到logger对象.
  8. 在记录器上使用.info().warning()等方法.
  1. Set up a file handler.
  2. Set the logging level of the file handler.
  3. Set up a formatter.
  4. Point the file handler to the formatter.
  5. Get the logger object.
  6. Set the logging level of the logger object.
  7. Add the file handler as a handler to the logger object.
  8. Use the .info(), .warning(), etc method on the logger.

这些步骤由以下代码执行:

These steps are executed by the following code:

import logging

file_handler = logging.FileHandler('./out.log', 'a')
file_handler.setLevel(logging.DEBUG)

format_string = '%(asctime)s\t%(levelname)s: %(message)s'
formatter = logging.Formatter(format_string)
file_handler.setFormatter(formatter)

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.addHandler(file_handler)

logger.info('visible info')
logger.debug('invisible debug')

设置文件处理程序的日志记录级别和设置记录器的日志记录级别有什么区别?

What is the difference between setting the logging level for the file handler and setting the logging level for the logger?

推荐答案

好的,下面是一些代码:

Okay, so here is a small bit of code to work out:

import logging


# Declare a function to log all 5 levels with different information
def log_all_levels(logger):
    logger.debug("Debug from logger {}".format(logger.name))
    logger.info("Info from logger {}".format(logger.name))
    logger.warning("Warning from logger {}".format(logger.name))
    logger.error("Error from logger {}".format(logger.name))
    logger.critical("Fatal from logger {}".format(logger.name))


# This file handler will track errors from all loggers
all_errors_handler = logging.FileHandler('errors.log')
all_errors_handler.setLevel(logging.ERROR)

# This file handler will only be used in a specific region of code
foo_info_handler = logging.FileHandler('foo_info.log')
foo_info_handler.setLevel(logging.INFO)
foo_info_handler.addFilter(lambda r: r.levelno == logging.INFO)

# The following loggers will be used in the main execution
foo_logger = logging.getLogger("Foo")
nameless_logger = logging.getLogger("nameless")
foo_logger.setLevel(logging.INFO)
nameless_logger.setLevel(logging.DEBUG)
loggers = (foo_logger, nameless_logger)

# Set each logger up to use the file handlers
# Each logger can have many handlers, each handler can be used by many loggers
for logger in loggers:
    logger.addHandler(all_errors_handler)
    debug_file_handler = logging.FileHandler('{}.log'.format(logger.name))
    debug_file_handler.setLevel(logging.DEBUG)
    logger.addHandler(debug_file_handler)
    if logger.name == "Foo":
        logger.addHandler(foo_info_handler)


# Let's run some logging operations
for logger in loggers:
    log_all_levels(logger)

有2个记录器-foo_logger设置为信息级别,而nameless_logger设置为调试级别.它们都使用错误和调试处理程序,但是只有foo_logger使用foo_file_handler.现在,存在具有不同级别的记录器和文件处理程序,它们之间以多对多关系连接在一起.

There are 2 loggers - foo_logger set to the info level and nameless_logger set to the debug level. Both of them use the errors and debug handlers, however only the foo_logger uses the foo_file_handler. There are now loggers and file handlers with different levels, connected together in a many-to-many relationship.

您可以找到:

  1. errors.log将包含来自两个记录器的错误.对于现实生活中的情况非常不言自明-阅读仅包含错误的日志有助于调试代码.
  2. Foo.lognameless.log将包含有关这些记录器的所有可能信息,并遵守其级别.因此,前者将包含信息和更多信息,而后者将跟踪调试和更高级别.每个对象的日志记录可能会创建很多文件,但是在尝试检测一些特定于对象的错误时,这可能至关重要.
  3. foo_info是一个非常特殊的文件处理程序,它允许来自关联记录器的信息级别.当您输入潜在的不安全或未经测试的代码区域并且想要查看该代码块中到底发生了什么时,而不必浏览所有程序日志,此类文件可以节省生命.
  1. errors.log will contain errors from both loggers. Quite self-explanatory for a real life scenario - reading through logs containing just the errors helps debugging the code.
  2. Foo.log and nameless.log will contain everything possible about those loggers, respecting their levels. So the former will contain info and greater, whereas the latter will track debug and greater levels. Logging per object will potentially create a lot of files, but it might be crucial when trying to detect some object-specific errors.
  3. foo_info is a very special file handler and it only allows info level from the associated logger. Such files can be a life saver when you enter a potentially unsafe or untested area of code and would like to see what exactly is happening within that code block, without having to browse through all your program log.

使用日志记录还可以做很多其他事情-设置自己的日志记录规则,创建日志记录层次结构,创建日志记录器工厂-可能性无穷无尽.日志记录应具有灵活性-例如,通过允许记录器对象和文件处理程序具有不同的单独的记录级别,并允许程序员根据需要将它们组合在一起.

There are many other things you can do with logging - set up your own logging rules, make a logging hierarchy, create a logger factory - possibilities are endless. Logging should allow flexibility - for example by allowing logger objects and file handlers to have different and separate logging levels, and letting the programmer combine them together as needed.

我希望小代码练习以及我的解释能消除任何进一步的疑问-但我建议您看一下 docs 如果您仍然需要更多示例.

I hope the small code exercise alongside with my explanations cleared any further doubts - but I do recommend to have a look at Logging Cookbook or the docs if you still need more examples.

这篇关于文件处理程序的日志级别与记录器的日志级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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