Python logging.basicConfig()














































Python logging.basicConfig()



                  RECORD EVENT IN THE FILE
Description:
                  In this article, we going to learn how to record events in the file. logging module helps to record events in the file.
Module-level function:
logging.basicConfig(): Does basic configuration for the lagging system by creating a StreamHandler with default formatter and adding it to root logger.the functions debug(), info(), warning(), error() and critical() will call basicConfig automatically if no handler defined for root logger. logging.basicConfig() has following keyword argument:
  1. filename - the name of the file to create file handler.
  2. filemode - use to specifies the file mode. default to 'append' (a) mode.
  3. format - use to specifies the format of logged message.
  4. datefmt - use to specifies the date/time 
  5. style - use to specifies the style of format, default to '%'
  6. level - use to set logging level
  7. stream - use to specifies the stream handler .we can either use stream handler or file otherwise it throws ValueError .because it is incompatible with the file.
  8. handlers - If specified, this should be the iterable of already created handlers to add to the root logger.it is incompatible with stream and filename.
  9. force - existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments. 
  10. encoding - use to specifies the encoding along with the file.
  11. error -If this keyword argument is specified along with the filename, its value is used when the FileHandler is created, and thus used when opening the output file. If not specified, the value 'backslashreplace' is used. Note that if None is specified, it will be passed as such to func:open, which means that it will be treated the same as passing 'errors'.
Implementation:
Example 1
# 1. import logging module
import logging

# 2. define file name
# 3. check filemode 
# 4. define logging level info
# 5. check format
logging.basicConfig(filename='intro.txt',level=logging.INFO)

'''
debug(), info(), warning(), error(), critical() function 
automatically called by logging.basicConfig()
'''
logging.debug('this is debug message')
logging.info('this is info message')
logging.warning('this is warning message')
logging.error('this is error message')
logging.critical('this is the critical message')
let run a program nothing will print on the console but we get the record in the file as following:
INFO:root:this is info message
WARNING:root:this is warning message
ERROR:root:this is error message
CRITICAL:root:this is the critical message
let run the program again we get following record in file:
INFO:root:this is info message
WARNING:root:this is warning message
ERROR:root:this is error message
CRITICAL:root:this is the critical message
INFO:root:this is info message
WARNING:root:this is warning message
ERROR:root:this is error message
CRITICAL:root:this is the critical message

Conclusion: 
                      As we run the program two-time records get overwrite hence file mode default to append and format default to logging_level:logger_name: message.

                    let change file mode and format. To modify the format we have to know the LogRecord attribute. LogRecord has the following attribute:
  1. asctime  - Human-Readable time .by default this is the form of 'yyyy-mm-dd h:m:s, millisecons_portion_of_time'
  2. filename - the name of the disk file
  3. funcName - the name of the function containing the logging call.
  4. levelname - name of logging level
  5. levelno - numeric logging level
  6. lineno - number of line of the program where the logging call was issued.
  7. message - logged message
  8. module - name of python program from where the logging call was issued.
  9. msec - milliseconds portion of time
  10. name - the name of the logger
  11. pathname - full path of the file where the logging call was issued.
  12. process - process id
  13. processName - process name 
we can use one of the '%', '{', '$' for printf-style, str.format() or string.Template respectively. we use default style '%'

Example 2
# 1. import logging module
import logging

# 2. define file name
# 3. change filemode to 'w'
# 4. define logging level info
# 5. define format
logging.basicConfig(filename='intro.txt',level=logging.INFO,filemode='w',
format='%(lineno)s %(levelname)s ---> %(message)s at %(asctime)s')

'''
debug(), info(), warning(), error(), critical() function 
automatically called by logging.basicConfig()
'''
logging.debug('this is debug message')
logging.info('this is info message')
logging.warning('this is warning message')
logging.error('this is error message')
logging.critical('this is the critical message')
let run the program we get following record in file

15 INFO ---> this is info message at 2021-03-16 16:47:04,123
16 WARNING ---> this is warning message at 2021-03-16 16:47:04,123
17 ERROR ---> this is error message at 2021-03-16 16:47:04,123
18 CRITICAL ---> this is the critical message at 2021-03-16 16:47:04,123
let run program again!! now time will change
15 INFO ---> this is info message at 2021-03-16 16:47:04,123
16 WARNING ---> this is warning message at 2021-03-16 16:47:04,123
17 ERROR ---> this is error message at 2021-03-16 16:47:04,123
18 CRITICAL ---> this is the critical message at 2021-03-16 16:47:04,123
Conclusion:
                     As we set file mode to write mode record gets overwrite instead of append. we modify the format without setting the style using printf-style. hence default file mode is 'append' and style  default to '%'

Application:

let Record the event of Bank!!!
import logging


logging.basicConfig(filename='bank.txt',style='{',format='{levelname}-->{message} 
at {asctime}',level=logging.INFO)


class Bank:
    def __init__(self,name,password,amount):
        self.name = name
        self.password = password
        self.amount = amount
        logging.info('account created!!!\n welcome '+name)
    def credit(self,amt):
        if self.amount > amt:
            self.amount-= amt
            logging.info(self.name +' credited '+str(amt)+now bank balance is '
+str(self.amount))
        else:
            logging.error('sorry, your bank balance is less than your 
required amount')
    def debit(self,amt):
        self.amount+=amt
        logging.info(self.name +' dedited '+str(amt)+' now bank balance is 
'+str(self.amount))
    def login(self,name,password):
        if self.name==name and self.password==password:
            logging.info(self.name+' login...')
        else:
            logging.warning('Enter correct crediantial!')
    def logout(self):
        logging.info(self.name+' logout...')

b1 = Bank('aarti','aarti123',10000)
b2 = Bank('pooja','pooja123',20000)

b1.login('aarti','aarti123')
b1.credit(50)
b2.login('pooja','pooja122')
b2.login('pooja','pooja123')
b2.debit(100)
b1.credit(10000)
b2.logout()
b1.logout()




we get record of event as following:
INFO-->account created!!!
 welcome aarti at 2021-03-16 15:28:22,780
INFO-->account created!!!
 welcome pooja at 2021-03-16 15:28:22,780
INFO-->aarti login... at 2021-03-16 15:28:22,780
INFO-->aarti credited 50 now bank balance is 9950 at 2021-03-16 15:28:22,780
WARNING-->Enter correct crediantial! at 2021-03-16 15:28:22,780
INFO-->pooja login... at 2021-03-16 15:28:22,781
INFO-->pooja dedited 100 now bank balance is 20100 at 2021-03-16 15:28:22,781
ERROR-->sorry, your bank balance is less than your required amount at 2021-03-16 15:28:22,781
INFO-->pooja logout... at 2021-03-16 15:28:22,781
INFO-->aarti logout... at 2021-03-16 15:28:22,781



More Articles of AARTI SHELAR:

Name Views Likes
Python Beautiful Soup : Scrape the Rate of Movie from IMDb 98 0
Python BeautifulSoup : Scrape the Review of mask from Amazon 180 0
Python Beautiful Soup : Scrape the Redmi mobile detail from Amazon 216 0
Python BeautifulSoup: Scape Internship from Internshala 165 0
Python BeautifulSoup.Tag.find_previous() and Beautiful.Tag.find_all_previous() 20 0
Python BeautifulSoup.Tag.find_next() and BeautifulSoup.Tag.find_all_next() 18 0
Python BeautifulSoup.Tag.find_previous_siblings() and BeautifulSoup.Tag.find_previous_sibling() 27 0
Python BeautifulSoup.Tag.find_next_sibling() and BeautifulSoup.Tag.find_next_siblings() 33 0
Python BeautifulSoup.Tag.find_parent() and BeautifulSoup.Tag.find_parents() 29 0
Python BeautifulSoup.find() 23 0
Python logging.Handler.addFilter() 27 0
Python logging.Handler.removeFilter() 16 0
Beautiful Soup Searching Parse Tree with find_all() 28 0
Beautiful Soup Navigating Parse Tree by Going Back and Forth 21 0
Beautiful Soup Navigating Parse Tree by Going Sideways 22 1
Beautiful Soup Navigating Parse Tree by Going Down 15 0
Beautiful Soup Navigating Parse Tree by Going Up 11 0
Beautiful Soup with NavigableString ,comments and other special string 41 0
Beautiful Soup with tag object 25 0
Python Beautiful Soup introduction 47 0
Python logging.config.dictConfig() 38 0
Python logging.config.fileConfig() 29 0
Python configuring logging 29 0
Python logging.getLogger().hasHandlers() 31 0
Python logging.Filter() 27 0
Python logging.FileHandler() 17 0
Python logging.Handler.setFormatter() 19 0
logging logging.StreamHandler() 25 0
Python logging.Formatter() 18 0
Python logging.getLogger().removeHandler(handler) 39 0
python logging.getLogger().addHandler(handler) 16 0
Python handlers in logging 30 0
Python logging.getLogger().getChild(suffix) 21 0
Python logging.getLogger().isEnabledFor(level) 13 0
python logging.getLogger().setLevel() 20 0
Python logging.log() 25 0
Python logging.exception() 25 0
Python logging method of logger object 17 0
python logging.getLogger().getEffectivelevel() 23 1
python logging.getLogger() 23 0
Python logging.getLogRecordFactory() 27 0
Python logging.basicConfig() 46 0
Python logging introduction 134 0

Comments