How Do You Log a Traceback?
00:00 Getting an exception and its resulting Python traceback means that you need to decide what to do about it. Usually, fixing your code is the first step, but sometimes the problem is with unexpected or incorrect input.
00:30 This code works well. When you run the script, giving a URL as a command-line argument, it will call the URL and then print the HTTP status code and the content from the response. It even works if the response was a HTTP error status.
However, sometimes the URL your script is given to retrieve doesn’t exist, or the host server is down. In those cases, this script will now cause an uncaught
ConnectionError exception and print a traceback.
If you move up the final exceptions traceback, you can see that the problem all started in our code with line 4 of
urlcaller.py. If you wrap the offending line in a
except block, catching the appropriate exception will allow your script to continue to work with more inputs.
This version of our
urlcaller script uses an
else clause with the
except block. If you’re unfamiliar with this feature of Python, then check out the section on the
else clause in the Real Python course called Python Exceptions: An Introduction. Now when you run the script with a URL that will result in a
ConnectionError being raised, you’ll get a printed
-1 for the status code and the content
ConnectionError. This works great. However, in most real systems, you don’t want to just silence the exception and the resulting traceback, but you want to log the traceback.
Logging tracebacks allows you to have a better understanding of what goes wrong in your programs. Let’s take a look at the final version of your script. You can log the traceback in the script by importing the
logging package, getting a logger, and calling
.exception() function on that logger in an
except portion of the
If you want to learn more about Python’s logging system, you should definitely check out the Logging in Python course here at Real Python. Now when you run the script for a problematic URL, it will print the expected
ConnectionError, but it will also log the traceback. By default, Python will send log messages to
stderr (standard error). This looks like we haven’t suppressed the traceback output at all. However, if you call it again and then redirect the
stderr, you can see that the logging system is working and we can save our logs off for later. And if we
cat the log file, we can view the logged traceback.
Become a Member to join the conversation.