How to create Logs in Python

How to create Logs in Python

Logging in Python

logging image

Logging is a very important and useful tool in any programming language and while building an application. It can help develop a better and neat understanding of the flow of the program.

Logs provide developers an extra debugging eye which keeps the track of the flow of execution. By logging the execution flow you can know where the scripts/code is causing error easily and also know how well your script/code runs without causing any error or exceptions.

In this blog, we will see how we can create a log using python with help of a package called logging in python. The logging library/module comes installed with python, but if you don't have it and want to install then you can simply run the below pip command.

pip install logging

The logging module provides 5 standard levels indicating the severity of events as follows:

  • DEBUG
  • INFO
  • WARNING
  • ERROR
  • CRITICAL

So if you were to log an error then you will use INFO and so on.

Now let us create a simple Log with python code

Firstly we need to import logging module in python

import logging

After importing the module we need to create a logging object

logger = logging.getLogger()

Now after this we need to configure the file name where the logs must be stored

logging.basicConfig(filename='logs.log')

The above code will create a new file name logs.log and all the log messages will be stored in the file. Note: you can give any name to the log file, in my case I have given the name logs

Next, we need to set the Logging level that is the severity

logger.setLevel(logging.DEBUG)

Now that we have done the configuration we can write some log codes

logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

The complete code for logging

logging.PNG

After executing the above code we can see a new file created with filename logs.log Upon opening the log file in a notepad or any text editor we can see the logs

logs.PNG

Hope you got an overview of how to use the logging module to create logs in python. To know more and understand in depth you can check out the logging documentation provided by python : Logging Documentation