启用详细日志记录的更简单方法 [英] Easier way to enable verbose logging

查看:68
本文介绍了启用详细日志记录的更简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

logger.info("test")

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

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

Python 日志记录 - 是否有低于 DEBUG 的内容?

推荐答案

你需要结合 Argparse 的智慧使用 Python 的日志记录 HOWTO 的教程.这是一个例子...

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

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

这篇关于启用详细日志记录的更简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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