I am trying to make a script that takes all errors and logs them to a log file. I want to include any argparse
errors to this file. I already use the logging
package and a sys.excepthook
to drive unexpected exceptions to the log file.
Here's an example code:
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))
When I run it with python logger_argparse.py 1
everything works great. If I run python logger_argparse.py a
I get the output in the console and not the log file:
usage: logger_argparse.py [-h] foo
logger_argparse.py: error: argument foo: invalid int value: 'a'
How do I get that information to go to the log file?
I found a workaround that I don't believe is very good. But it seems to be working:
Can you use logging.exception in an exception handler? Edit: so how about just logging from
ArgumentParser.error()
?This will show the following: