Start with logging module in Python - Python for Data Analytics

Python Programs | Python Tricks | Solution for problems | Data Cleaning | Data Science

Start with logging module in Python

If you are dealing with nested codes and complex logic then logging comes first in mind when you think of debugging your code. logging in python will let you print command line logs as well as let you create log file and write your all logs to deal with them later.

logging module of python has numerous of easy method that makes our work so easy. It easily let you set the structure of log lines with help logging module's basicConfig() method.

So log can either be error message or Information or just a warning for making this thing easier logging module contain five logging levels that you can set as to specify your log message as one of:
  • DEBUG ( 0 )
  • INFO ( 1 )
  • WARNING ( 2 )
  • ERROR ( 3 )
  • CRITICAL ( 4 )
To set logging level you have to pass it inside basicConfig() method's level attribute, like to set logging level as debug message we have to pass it like:


import logging
logging.basicConfig( level = logging.DEBUG )

or, either you can pass the number value corresponding to it.



To set log file name that you want to generate you have to pass filename to  basicConfig() like this:

import logging
logging.basicConfig( filename = "test.log", level = logging.DEBUG )

The code below contains the program that store employee name and as employee get added it will write a Info log to the log file that we create by passing the value of filename in basicConfig method.

import logging

class Employee:
  def __init__(self,first,last):
    self.first = first    self.last = last
    logging.info('Create Employee : {} - {}'.format(self.first,self.last))


logging.basicConfig(filename='test.log',level=logging.DEBUG)
emp_1 = Employee('John','Doe')
emp_2 = Employee('Jane','Austin')

**Code above will generate a log file of name test.log in your working directory. 




2 comments:

  1. thank you for sharing informative post.
    web programming tutorial
    welookups

    ReplyDelete
  2. here might be requirement to scrape data from website and analyze them for several reasons, such as, for advertising, fund, modern hardware, electronic contraptions, autos or land, from different websites.
    scraper bot

    data extraction services

    web crawling services

    web scraping services

    ReplyDelete