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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14097061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:26:19  来源:igfitidea点击:

Easier way to enable verbose logging

pythonpython-2.7

提问by user1934146

I want to add a debug print statement test, if I enable --verbosefrom the command line and if I have the following in the script.

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

logger.info("test")

I went through the following questions, but couldn't get the answer...

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

采纳答案by Johnsyweb

You need to combine the wisdom of the Argparse Tutorialwith Python's Logging HOWTO. Here's an example...

您需要将Argparse 教程的智慧与Python 的 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')

Run the help:

运行帮助:

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

Running in verbose mode:

以详细模式运行:

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

Running silently:

默默奔跑:

> ./verbose.py   
> 

回答by Matthew Leingang

I find both --verbose(for users) and --debug(for developers) useful. Here's how I do it with loggingand argparse:

我发现--verbose(对于用户)和--debug(对于开发人员)都很有用。这是我使用loggingand 的方法argparse

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)

So if --debugis set, the logging level is set to DEBUG. If --verbose, logging is set to INFO. If neither, the lack of --debugsets the logging level to the default of WARNING.

因此,如果--debug设置为 ,则日志记录级别设置为DEBUG。如果--verbose,日志记录设置为INFO。如果两者都没有,则缺少--debug将日志记录级别设置为默认值WARNING.

回答by Stephan

You can explicity specify a level as an integer after the -vflag:

您可以在-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) 

回答by Stickley

Here is a more concise method, that does bounds checking, and will list valid values in help:

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

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

Usage:

用法:

demo.py --log DEBUG

回答by jcomeau_ictx

if you want to enable logging.DEBUG level for a script you don't want to (or cannot) edit, you can customize your startup:

如果要为不想(或不能)编辑的脚本启用 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

enter the following:

输入以下内容:

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

then you can just:

那么你可以:

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

from Paul Ollis at http://nedbatchelder.com/blog/201001/running_code_at_python_startup.html

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



2017-07-18: I've since switched to a different method:

2017-07-18:从那以后我改用了不同的方法:

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

what this does is, if you're running without optimization (as in python script.py) you get the DEBUG-level stuff, whereas if you run with python -OO script.pyyou don't. no environment variables to set.

这样做的作用是,如果您在没有优化的情况下运行(如python script.py),您将获得调试级别的东西,而如果您在运行时python -OO script.py则不会。无需设置环境变量。

回答by RubenLaguna

Another variant would be to count the number of -vand use the count as an index to the a listwith the actual levels from logging:

另一种变体是计算 的数量-v并将计数用作 a 的索引,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")

This works for -vvvv, -vvv, -vv, -v, -v -v, etc, If no -vthen logging.WARNINGis selected if more -vare provided it will step to INFOand DEBUG

这适用于-vvvv, -vvv, -vv, -v,-v -v等,如果没有,-vlogging.WARNING选择如果-v提供更多,它将步进INFODEBUG

回答by handle

Here's another take on having argparse count the -v option to increase verbosity up two levels from the default WARNING to INFO (-v) to DEBUG (-vv). This does not map to the constants defined by loggingbut rather calculates the value directly, limiting the input:

这是另一种让 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