Basic Logging with Python (create .log files)

There are a lot of things that you program does while being executed. and it is highly likely that your code in execution might face a plethora of pitfalls while its journey. It is always wise to have your code speak for itself and that it maintains its own personal diary of what checkpoints it has crossed and where exactly did it face any error during execution - some people call it as the LOG.

Logging is the means of tracking events that happen when some software run. We as developers add logging calls in our code to indicate that a particular event has taken place.

There are a set of logging functions for our simple logging usage. I've mentioned then as follows.

  1. debug()
  2. info()
  3. warning()
  4. error()
  5. critical()
To use the above methods we are required to import the package called "logging". The above mentioned logging functions are named after the severity of the events that they are used to track. 

Following are the most important levels :
  • DEBUG is nothing but detailed information typically used for diagnosing problems.
  • INFO is a confirmation that things are working as expected.
  • WARNING is an indication that something unexpected has happened and it might need your interference very soon.
  • ERROR is a serious problem because of which the program couldn't perform some function
  • CRITICAL is a serious error, indicating that the program itself maybe be unable to continue running.
In the logging module there are 6 levels with a constant value. You need this value to have control over which logging information will be printed to the file or shown on the console.

Note:Loggers will only write messages with the level greater than or equal to the set level.

The logging levels and their associated values are :

NONSET -          0
INFO        -        10
WARNING -      20
ERROR   -         30
CRITICAL  -     40

We can direct all the log messages to the console or to a file. It is quite common to have log pushed into a log file so that it become easy for the developer to track down any progress of problem.

You need to set up the logging system first using the basicConfig() method. By default the level will be set to "30 (error)". Within the basicConfig() method you specify the filename, the level, the format of the log string and the file mode which decides whether to overwrite or to append to the log file.

Now you have the basics of logging. Let us write a program to compute the perimeter of a triangle.
We will write a program in Python with a function named "perimeter" and include necessary logging information.



When you execute the above file this is what you get to see in the log file later on.



Thanks for reading.

Popular posts from this blog

What really is a Hypertext?

Browser Rendering Phase

Crypto crypto everywhere but not a token to bet your life on