Python – Logging into a file and into the console

Python allows decent built-in logging. As I am going to explain in the video below, the built-in logging is actually rather neat – it allows everyone to log into a file or into the console within minutes – just the time needed to write a few lines of code.

Nice trees before they become logs

Now, the MCE for logging looks like this:

With the code above, we create a logger object and we ask it to kindly format the output as per the formatter. Then it is forced to write into a file.log, that is created (if not present) in the same folder, as the file in which the code is written. This is how the logfile looks like, if you are using fancy editor like PyCharm Community:

In general, we have 5 types of common handlers, that can be attached to a logger:

  1. StreamHandler
    • Send events to the console.
  2. FileHandler
    • Save events to a file.
  3. SMTPHandler
    • Send events to an email address.
  4. HTTPHandler
    • Send events to a web server.
  5. QueueHandler
    • Send events to a different thread.

Additionally, there are 5 different levels of logging with different usage. The idea is that you can select which level you are interested in. In that case it only logs events for that level and above:

  • CRITICAL – 50 – Serious errors in core functionalities
  • ERROR – 40 – Errors in some functionalities
  • WARNING – 30 – Unexpected behaviors that can lead to errors, (usually an information for usage of an old, obsolete library)
  • INFO – 20 – Informational for expected behaviors
  • DEBUG – 10 – For diagnosis of problem, turn this one on to see everything

The rest of the code that I have used for the YouTube video is this one:

The YouTube video is below. The most of the code, came from the book: “Python How-To 63 techniques to improve your Python code”…  ( If you are interested in the books, then discount code for all manning books (40%) is here: watchcui40.

Enjoy! 🙂

Tagged with: , , , , , ,