Python: Logging Errors to a Text File

In this article, let us see how we can catch exceptions and log them onto a text file.

Logging is a tool used in software engineering to track any and all the events that occur when your program runs.

It’s like leaving a trail of breadcrumbs. When something goes wrong, we know where to start looking!

Example#1: Printing Logs To a Text File

Have a look at the following example.

import logging
logging.basicConfig(filename='example.log', level=logging.ERROR)

logging.error('This will be logged in the file')

In the above code

  1. Firstly we import the inbuilt logging module as it takes over a lot of heavy lifting for us when it comes to logging (as opposed to using a simple file handler and writing to it)
  2. Then we use the method basicConfig() to name a file that will be created if something is logged. We also set up the logging level.
example.log
ERROR:root:This will be logged in the file

For those of you who are new to logging levels, Python offers 5 functions depending upon their severity. These are

  1. debug()
  2. info()
  3. warning()
  4. error() &
  5. critical()

In this article, our focus will be on how to use it when it comes to logging errors using option#4 above!

If you wish to learn about the other logging levels, this article here from python.org is a good place to start!

In the previous example, we used the error() method to log a custom message. After the program has finished executing, we will find this message in our file.

Example#2: Logging Errors on Exception

In the following example, a ZeroDivisionError is raised in the try-block, in the except block we catch it and log it to our log file.

import logging

logging.basicConfig(filename='ZeroDivisionError.txt', level=logging.ERROR)

try:
    result = 10 / 0
except ZeroDivisionError as e:
    logging.error("Uh-oh! An error occurred: %s", e)
ERROR:root:Uh-oh! An error occurred: division by zero

We can take this a step further and configure the output message to include other metrics as needed.

For example, you can add the date and time:

2023-09-03 07:30:06,030 - ERROR:root:Uh-oh! An error occurred: division by zero

You can also format the way the output is shown:

ERROR-This is an error message

The messages we log don’t always have to be a “custom messages”. We can also log details like

  1. Name of the Error (Exception Type)
  2. The error message that comes with the Exception (Exception message) and
  3. Series of function calls leading to the error (Stack-trace)

And any combination of the above. As a matter of fact, there is a wealth of information contained in the error message, if you wish to learn the tricks then set aside 10mins of your time and read the following article!

Python: Details contained in an Exception

For visual learners out there we have also made an interesting video on that topic!

And with that invitation, I will end this article!

Congratulations on making it to the end of the article, not many have the perseverance to do so!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Accessing The Caught Exception Object In The “except” Block In Python!

Python “except:” vs “except Exception as e:”

7 Most Common In-Built Exceptions in Python!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn