Posted By

ManishChandraReddy on 12/13/15


Tagged

logging PSO statevariablelogger


Versions (?)

Logging object in python


 / Published in: Python
 

URL: http://www.blog.pythonlibrary.org/2012/08/02/python-101-an-intro-to-logging/

Understanding logger objects in Python Logging module

Full link

import logging to import logging module.

Hierarchy: logging ->handler->formatter

Logging is User API. Handling handles the logging instance's requests to log. Also has its own level. Formatter is the final gate to writing the logs down. Helps format.

logging.BasicConfig to start a basic logger.

  1. The main entry point of the application
  2.  
  3. logger = logging.getLogger("exampleApp") #Creates the logger object
  4. logger.setLevel(logging.INFO) #Logger level set to INFO
  5.  
  6. # create the logging file handler
  7. fh = logging.FileHandler("new_snake.log") #Default FileHandler created. Could have created anything else like SMTP, Stream etc.
  8.  
  9. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') #Formatter object for the handler.
  10. fh.setFormatter(formatter) #Adding formatter to the Handler object
  11.  
  12. # add handler to logger object
  13. logger.addHandler(fh) #Adding the Handler object to the Logger
  14.  
  15. logger.info("Program started")
  16. result = otherMod2.add(7, 8) #To see that the inside logs differently
  17. logger.info("Done!")
  18.  
  19.  
  20. ##For Other functions with different names
  21.  
  22. # otherMod2.py
  23. import logging
  24.  
  25. module_logger = logging.getLogger("exampleApp.otherMod2")
  26.  
  27. #----------------------------------------------------------------------
  28. def add(x, y):
  29. """"""
  30. logger = logging.getLogger("exampleApp.otherMod2.add")
  31. logger.info("added %s and %s to get %s" % (x, y, x+y))
  32. return x+y

Report this snippet  

You need to login to post a comment.