Python Logging Exception
Raising exceptions during logging can be useful in certain scenarios to indicate exceptional conditions or errors in your application. By raising an exception, you can halt the normal flow of execution and notify the caller or the logging system about the encountered issue.
In this code, we are raising an Exception that is being caught by the logging. exception.
Python3
import logging logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s - %(levelname)s - %(message)s' ) def perform_operation(value): if value < 0 : raise ValueError( "Invalid value: Value cannot be negative." ) else : # Continue with normal execution logging.info( "Operation performed successfully." ) try : input_value = int ( input ( "Enter a value: " )) perform_operation(input_value) except ValueError as ve: logging.exception( "Exception occurred: %s" , str (ve)) |
Output :
Enter a value: -1 2023-06-15 18:25:18,064 - ERROR - Exception occurred: Invalid value: Value cannot be negative. ValueError: Invalid value: Value cannot be negative.
Logging in Python
Logging is a means of tracking events that happen when some software runs. Logging is important for software developing, debugging, and running. If you don’t have any logging record and your program crashes, there are very few chances that you detect the cause of the problem. And if you detect the cause, it will consume a lot of time. With logging, you can leave a trail of breadcrumbs so that if something goes wrong, we can determine the cause of the problem.
There are a number of situations like if you are expecting an integer, you have been given a float and you can a cloud API, the service is down for maintenance, and much more. Such problems are out of control and are hard to determine.