我正在尝试创建一个捕获所有错误的脚本并将其记录到日志文件中。我想在此文件中包含任何argparse
错误。我已经使用logging
包和sys.excepthook
来驱动日志文件的意外异常。
以下是一个示例代码:
import argparse
import logging
import sys
import traceback
def log_uncaught_exceptions(ex_cls, ex, tb):
logging.critical(''.join(traceback.format_tb(tb)))
logging.critical('{0}: {1}'.format(ex_cls, ex))
logging.basicConfig(
level=logging.DEBUG,
filename='foo.log',
filemode='w',
format='%(asctime)s - %(levelname)s - %(message)s')
sys.excepthook = log_uncaught_exceptions
logging.debug('This is a typical debug line')
parser = argparse.ArgumentParser(description='Foo String')
parser.add_argument('foo',type=int)
args = parser.parse_args()
logging.debug('Input was %i'%(args.foo))
当我用python logger_argparse.py 1
运行时,一切都很好。如果我运行python logger_argparse.py a
,我会在控制台中获得输出而不是日志文件:
usage: logger_argparse.py [-h] foo
logger_argparse.py: error: argument foo: invalid int value: 'a'
如何获取该信息以转至日志文件?
答案 0 :(得分:1)
我找到了一个我不相信非常好的解决方法。但似乎有效:
import argparse
import logging
import sys
import traceback
class argparse_logger(argparse.ArgumentParser):
def _print_message(self, message, file=None):
if file is sys.stderr:
logger.error('Arg Parse did something bad...see below:')
logger.error(message)
else:
super()._print_message(message,file=file)
def log_uncaught_exceptions(ex_cls, ex, tb):
logging.critical(''.join(traceback.format_tb(tb)))
logging.critical('{0}: {1}'.format(ex_cls, ex))
logging.basicConfig(
level=logging.DEBUG,
filename='foo.log',
filemode='w',
format='%(asctime)s - %(levelname)s - %(message)s')
# logging.getLogger('root')
logger = logging.getLogger('root')
sys.excepthook = log_uncaught_exceptions
logger.debug('This is a typical debug line')
parser = argparse_logger(description='Foo String')
parser.add_argument('foo',type=int)
args = parser.parse_args()
logger.debug('Input was %i'%(args.foo))
答案 1 :(得分:1)
您可以在异常处理程序中使用logging.exception吗?
编辑:那么如何从ArgumentParser.error()
进行日志记录?
import sys
import logging
import argparse
class argparse_logger(argparse.ArgumentParser):
def error(self, message):
logging.error(message)
super().error(message)
logging.basicConfig(
level=logging.DEBUG,
filename='foo.log',
filemode='w',
format='%(asctime)s - %(levelname)s - %(message)s')
# parser = argparse.ArgumentParser(description="Foo")
parser = argparse_logger(description="Foo")
parser.add_argument('foo',type=int)
logging.debug("Start")
try:
args = parser.parse_args(sys.argv[1:])
except:
print("Error handling arguments")
raise
logging.debug(f"Finish - {args.foo}")
print(f"Exiting! - {args.foo}")
这将显示以下内容:
J:\>python arg_parse_log.py 5
Exiting! - 5
J:\>more foo.log
2018-02-07 11:34:45,647 - DEBUG - Start
2018-02-07 11:34:45,648 - DEBUG - Finish - 5
J:\>python arg_parse_log.py
usage: arg_parse_log.py [-h] foo
arg_parse_log.py: error: the following arguments are required: foo
Error handling arguments
J:\>more foo.log
2018-02-07 11:34:54,577 - DEBUG - Start
2018-02-07 11:34:54,578 - ERROR - the following arguments are required: foo