简体   繁体   English

如何关闭日志语句而不从代码中删除它们

[英]How to turn off logging statements without removing them from the code

If there are logging statements spread throughout a codebase, how do I set up the logger so I don't have to comment out each call to the logger when deploying the code into production? 如果在整个代码库中存在日志记录语句,如何设置记录器,以便在将代码部署到生产环境中时不必注释掉对记录器的每次调用?

Here's my current code: 这是我目前的代码:

import logging


logging.basicConfig(filename='./example.log', level=logging.DEBUG, 
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M')

logging.debug('debug failed')
logging.info('info failed')
logging.warning('A warning')

Instead of using the basicConfig , you can set up the logger more explicitly with the handlers you want, based on any criteria. 您可以根据任何条件,使用所需的处理程序更明确地设置记录器,而不是使用basicConfig

import logging

log = logging.getLogger("FOO")
log.setLevel(logging.DEBUG)

# needs a handler
log.info('info')
#No handlers could be found for logger "FOO"

ch = logging.StreamHandler()
log.addHandler(ch)
log.info('info')
# info

log.removeHandler(ch)

noop = logging.NullHandler()
log.addHandler(noop)
# nothing happens here
log.info('info')

You can have a conditional statement that either adds the handler you want if you are running in debug mode, or you can add a NullHandler that just absorbs the log messages. 如果在调试模式下运行,您可以使用条件语句添加所需的处理程序,也可以添加仅吸收日志消息的NullHandler You can also configure the levels individually of each handler, so that you would always see warnings and above. 您还可以单独配置每个处理程序的级别,以便始终看到警告及其上方。 Each handler can have its own level, in addition to the main logger. 除主记录器外,每个处理程序都可以拥有自己的级别。

You can refer to the tutorials on how to get more specific with levels, handlers, and formatting. 您可以参考有关如何使用级别,处理程序和格式更具体的教程

There are a couple of really simple answers here. 这里有几个非常简单的答案。 The first is to simply comment out the basicConfig(...) statement. 首先是简单地注释掉basicConfig(...)语句。 That will have the effect not setting up any of the loggers, handlers or formatters which means your debug(), info(), etc calls will be effectively no-ops. 这将导致没有设置任何记录器,处理程序或格式化程序的效果,这意味着您的debug(),info()等调用将实际上是无操作。

Another simple answer is to set the logging level in the basicConfig() call to something higher than DEBUG . 另一个简单的答案是将basicConfig()调用中的日志记录级别设置为高于DEBUG CRITICAL + 1 would make sure that you never see a log message. CRITICAL + 1将确保您永远不会看到日志消息。

However you mentioned something about moving this code into production, so what you probably want to do is provide -q and -v command line options (assuming this is a CLI tool). 但是,您提到了将此代码转移到生产中的内容,因此您可能要做的是提供-q-v命令行选项(假设这是一个CLI工具)。 My usual approach is to start at WARNING level, and for each -q move towards quieter logging by increasing the filter level. 我通常的方法是从WARNING级别开始,并且每个-q通过增加过滤器级别来实现更安静的日志记录。 Conversely, for each -v , move towards more verbose logging. 相反,对于每个-v ,转向更详细的日志记录。 Here is a snippet of code that does exactly that. 这是一段完全相同的代码片段。

from argparse import ArgumentParser
from logging import basicConfig, CRITICAL, ERROR, WARNING, INFO, DEBUG

parser = ArgumentParser()
parser.add_argument("-v", "--verbose", action="count")
parser.add_argument("-q", "--quiet", action="count")

arguments = parser.parse_args()

raw_log_level = 2 + (arguments.verbose or 0) - (arguments.quiet or 0)
if raw_log_level <= 0: 
    log_level = CRITICAL
elif raw_log_level == 1:
    log_level = ERROR
elif raw_log_level == 2:     # default
    log_level = WARNING
elif raw_log_level == 3: 
    log_level = INFO
else:         
    log_level = DEBUG

basicConfig(level=log_level)

There are levels of logging. 有记录级别。 Based on the severity of the logging level, it will print it. 根据日志记录级别的严重性,它将打印它。

Level   Numeric value
CRITICAL    50
ERROR   40
WARNING     30
INFO    20
DEBUG   10
NOTSET  0

Based on the logging level it will print the statements. 根据日志记录级别,它将打印语句。

the level you have specified here is level=logging.DEBUG. 你在这里指定的级别是level = logging.DEBUG。 So all but notset logging levels should print out. 所以除了未设置的日志记录级别应打印出来。 If you would want to print out only critical levels, please change the level=logging.CRITICAL 如果您只想打印出关键级别,请更改level = logging.CRITICAL

http://docs.python.org/release/2.5/lib/module-logging.html has more information http://docs.python.org/release/2.5/lib/module-logging.html有更多信息

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

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