Guest User

Untitled

a guest
Jun 22nd, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. import logging
  2. logging.basicConfig(level=logging.INFO)
  3. logger = logging.getLogger(__name__)
  4.  
  5. logger.info('Start reading database')
  6. # read database here
  7. records = {'john': 55, 'tom': 66}
  8. logger.debug('Records: %s', records)
  9. logger.info('Updating records ...')
  10. # update records here
  11. logger.info('Finish updating records')
  12. You can run it and see
  13.  
  14. INFO:__main__:Start reading database
  15. INFO:__main__:Updating records ...
  16. INFO:__main__:Finish updating records
  17. What’s different between the “print” approach you asked. Well, of course there are benefits:
  18.  
  19. You can control message level and filter out not important ones
  20. You can decide where and how to output later
  21. There are different importance levels you can use, debug, info, warning, error and critical. By giving different level to logger or handler, you can write only error messages to specific log file, or record debug details when debugging. Let’s change the logger level to DEBUG and see the output again
  22.  
  23. logging.basicConfig(level=logging.DEBUG)
  24. The output:
  25.  
  26. INFO:__main__:Start reading database
  27. DEBUG:__main__:Records: {'john': 55, 'tom': 66}
  28. INFO:__main__:Updating records ...
  29. INFO:__main__:Finish updating records
  30. As you can see, we adjust the logger level to DEBUG, then debug records appear in output. You can also decide how these messages are processed. For example, you can use a FileHandler to write records to a file.
  31.  
  32. import logging
  33.  
  34. logger = logging.getLogger(__name__)
  35. logger.setLevel(logging.INFO)
  36.  
  37. # create a file handler
  38. handler = logging.FileHandler('hello.log')
  39. handler.setLevel(logging.INFO)
  40.  
  41. # create a logging format
  42. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  43. handler.setFormatter(formatter)
  44.  
  45. # add the handlers to the logger
  46. logger.addHandler(handler)
  47.  
  48. logger.info('Hello baby')
Add Comment
Please, Sign In to add comment