I’m trying to force myself to move away from using the print() function as I’m pretty much using print all the time to cater for logging, and using the logging package instead.
This is a basic example of using logging in a basic python app:
12345678910111213141516
importlogginglogging.basicConfig(level=logging.INFO,format="%(asctime)s [%(levelname)s] %(name)s%(message)s",handlers=[logging.StreamHandler()])messagestring={'info':'info message','warn':'this is a warning','err':'this is a error'}logger=logging.getLogger('thisapp')logger.info('message: {}'.format(messagestring['info']))logger.warning('message: {}'.format(messagestring['warn']))logger.error('message: {}'.format(messagestring['err']))
When running this example, this is the output that you will see:
1234
$ python app.py
2021-07-19 13:07:43,647 [INFO] thisapp message: info message
2021-07-19 13:07:43,647 [WARNING] thisapp message: this is a warning
2021-07-19 13:07:43,647 [ERROR] thisapp message: this is a error