改进python代码

vkr*_*ris 0 python

我面临以下情况:

我设置了DEBUG = True/False,基于此我进行了日志记录.

传统的做法是

if DEBUG:
   logger.log(whatever)
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来编写这段代码?使用闭包/ lambda函数等..?

lah*_*her 7

查看日志库的手册:http://docs.python.org/library/logging.html

您可以直接在代码或配置文件中配置...

例如

import logging
logging.basicConfig(filename='example.log',level=logging.INFO)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
Run Code Online (Sandbox Code Playgroud)

(看它怎么只显示信息和警告信息)

或者,从文件中:

import logging
import logging.config

logging.config.fileConfig('logging.conf')

# create logger
logger = logging.getLogger('simpleExample')

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
Run Code Online (Sandbox Code Playgroud)

有关日志记录配置格式,请参阅config部分.http://docs.python.org/howto/logging.html#configuring-logging

logging.getLogger(...)的相关性是它允许您为代码的不同部分设置不同的日志级别.

编辑:如果您担心昂贵的操作,最好使用以下内容:

if logger.isEnabledFor(logging.DEBUG):
    logger.debug('Message with %s, %s', expensive_func1(),
                                        expensive_func2())
Run Code Online (Sandbox Code Playgroud)

HTH