更简单的方法来启用详细日志记录

时间:2012-12-31 03:19:20

标签: python python-2.7

如果我从命令行启用--verbose并且脚本中有以下内容,我想添加一个调试print语句测试。

logger.info("test")

我经历了以下问题,但无法得到答案......

7 个答案:

答案 0 :(得分:101)

我发现--verbose(对于用户而言)和--debug(对于开发人员)都很有用。以下是我使用loggingargparse执行此操作的方法:

import argparse
import logging

parser = argparse.ArgumentParser()
parser.add_argument(
    '-d', '--debug',
    help="Print lots of debugging statements",
    action="store_const", dest="loglevel", const=logging.DEBUG,
    default=logging.WARNING,
)
parser.add_argument(
    '-v', '--verbose',
    help="Be verbose",
    action="store_const", dest="loglevel", const=logging.INFO,
)
args = parser.parse_args()    
logging.basicConfig(level=args.loglevel)

因此,如果设置了--debug,则日志记录级别将设置为DEBUG。如果--verbose,则日志记录设置为INFO。如果不是,则缺少--debug会将日志记录级别设置为默认值WARNING

答案 1 :(得分:68)

您需要将Argparse Tutorial的智慧与Python's Logging HOWTO结合起来。这是一个例子......

> cat verbose.py 
#!/usr/bin/env python

import argparse
import logging

parser = argparse.ArgumentParser(
    description='A test script for http://stackoverflow.com/q/14097061/78845'
)
parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")

args = parser.parse_args()
if args.verbose:
    logging.basicConfig(level=logging.DEBUG)

logging.debug('Only shown in debug mode')

运行帮助:

> ./verbose.py -h
usage: verbose.py [-h] [-v]

A test script for http://stackoverflow.com/q/14097061/78845

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity

以详细模式运行:

> ./verbose.py -v
DEBUG:root:Only shown in debug mode

默默地跑:

> ./verbose.py   
> 

答案 2 :(得分:45)

这是一个更简洁的方法,它执行边界检查,并将在帮助中列出有效值:

parser = argparse.ArgumentParser(description='This is a demo.')
parser.add_argument("-l", "--log", dest="logLevel", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help="Set the logging level")

args = parser.parse_args()
if args.logLevel:
    logging.basicConfig(level=getattr(logging, args.logLevel))

用法:

demo.py --log DEBUG

答案 3 :(得分:16)

另一个变体是计算-v的数量,并使用该计数作为list的索引,其实际级别来自logging

import argparse
import logging

parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='count', default=0)
args = parser.parse_args()

levels = [logging.WARNING, logging.INFO, logging.DEBUG]
level = levels[min(len(levels)-1,args.verbose)]  # capped to number of levels

logging.basicConfig(level=level,
                    format="%(asctime)s %(levelname)s %(message)s")

logging.debug("a debug message")
logging.info("a info message")
logging.warning("a warning message")

这适用于-vvvv-vvv-vv-v-v -v等,如果没有-v则{{1}如果提供的logging.WARNING越多,它就会被选中,它将逐步转移到-vINFO

答案 4 :(得分:8)

您可以明确指定级别为-v标志后的整数:

parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", const=1, default=0, type=int, nargs="?",
                    help="increase verbosity: 0 = only warnings, 1 = info, 2 = debug. No number means info. Default is no verbosity.")
args = parser.parse_args()

logger = logging.getLogger()
if args.verbose == 0:
    logger.setLevel(logging.WARN) 
elif args.verbose == 1:
    logger.setLevel(logging.INFO) 
elif args.verbose == 2:
    logger.setLevel(logging.DEBUG) 

答案 5 :(得分:2)

这是另一个让argparse计算-v选项以增加从默认WARNING到INFO(-v)到DEBUG(-vv)两个级别的详细程度。这不会映射到logging定义的常量,而是直接计算值,限制输入:

print( "Verbosity / loglevel:", args.v )
logging.basicConfig( level=10*(3-max(0,min(args.v,3))) )
logging.debug("debug") # 10
logging.info("info") # 20
logging.warning("warning") # 30 - The default level is WARNING, which means that only events of this level and above will be tracked
logging.error("error") # 40
logging.critical("critical") # 50

答案 6 :(得分:1)

如果要为不想(或不能)编辑的脚本启用logging.DEBUG级别,可以自定义启动:

jcomeau@aspire:~$ python -c "import site; site._script()"
[snip]...
USER_BASE: '/home/jcomeau/.local' (exists)
USER_SITE: '/home/jcomeau/.local/lib/python2.7/site-packages' (exists)
ENABLE_USER_SITE: True
jcomeau@aspire:~$ mkdir -p ~/.local/lib/python2.7/site-packages
jcomeau@aspire:~$ vi ~/.local/lib/python2.7/site-packages/usercustomize.py

输入以下内容:

import os, logging
if os.getenv('DEBUGGING'):
    logging.basicConfig(level = logging.DEBUG)

然后你可以:

jcomeau@aspire:~$ mkdir -p /tmp/some/random/
jcomeau@aspire:~$ echo 'import logging; logging.debug("test")' >> /tmp/some/random/script.py
jcomeau@aspire:~$ DEBUGGING=1 python /tmp/some/random/script.py 
DEBUG:root:test

来自Paul Ollis http://nedbatchelder.com/blog/201001/running_code_at_python_startup.html


2017-07-18:我已经换成了另一种方法:

logging.basicConfig(level=logging.DEBUG if __debug__ else logging.INFO)

这样做,如果你在没有优化的情况下运行(如在python script.py中),你会获得DEBUG级别的东西,而如果你使用python -OO script.py运行,则不会。没有要设置的环境变量。