In this notes, we are looking at a simple but yet useful and powerful logging in Python

In [77]:

import logging
#levels of logging are 
#1 debug - detailed info
#2 info - confirmation that things went according to plan
#3 warning - something unexpected happened
#4 error - some function failed
#5 critical - something failed and application must close
from imp import reload
reload(logging) # this will help our logging to be saved to file

logging.basicConfig(filename='logFile3.log',format='%(asctime)s %(message)s', level=logging.DEBUG) # the logging will only log the level you set it to and any 
#other levels ABOVE it but NOT below it

 

In [78]:
#lets define a simple function
def main():
    try:
        #mathFail = 1/0   # this will give an error which can be catched
        if 1<2:
            logging.debug('Entered into one of the if statements')
            print('we are in the IF STATEMENT')
            
            #this error will not break our entire script so we will catch the error and give some info
            try:
                urllib2.urlopen('http://www.google.com').read()
                logging.info('Opened url fine')
            except Exception as e:
                logging.error('urllib2 url visit failed and the reason was %s' % str(e))
        else:
            logging.debug('Entered into the else statement')
            print('We are in the ELSE STATEMENT')
    except Exception as e:
        print(str(e))
        logging.critical(e)

 

In [79]:
main()

 

we are in the IF STATEMENT
Could not open url

 

Similar Posts

2 Comments

    1. Hi Angeline,
      Glad you like the content. Yes, I do allow guest posting. You can forward guest articles to siradaba [at] yahoo [dot] co.uk
      Please put “Guest Post” as part of the email subject so it can be spotted quickly.
      Many thanks
      Ben

Leave a Reply

Your email address will not be published. Required fields are marked *