import logging logging.basicConfig(filename='example.log', level=logging.ERROR) logger = logging.getLogger() try: # Some code that may raise an exception except Exception as e: logger.error('An error occurred: %s', e)
import logging logger = logging.getLogger() logger.setLevel(logging.ERROR) console_handler = logging.StreamHandler() console_handler.setLevel(logging.ERROR) formatter = logging.Formatter('%(levelname)s - %(message)s') console_handler.setFormatter(formatter) logger.addHandler(console_handler) try: # Some code that may raise an exception except Exception as e: logger.error('An error occurred: %s', e)In this example, we create a logger object and configure it to log messages of level ERROR and above. We then create a console handler and configure it to log messages of level ERROR and above as well. Finally, we add the console handler to the logger and use the `Logger.error()` method to log any error that occurs in the try block. Package/library used: python logging