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. 

Similar Reads

Why print statement is not Pythonic

Some developers use the concept of printing the statements to validate if the statements are executed correctly or if some error has occurred. But printing is not a good idea. It may solve your issues for simple scripts but for complex scripts, the printing approach will fail.Python has a built-in module logging which allows writing status messages to a file or any other output streams. The file can contain information on which part of the code is executed and what problems have arisen....

Python Logging Levels

There are five built-in levels of the log message....

Useful Handlers

In addition to the base Handler Class, many useful subclasses are provided....

Python Logging Basics

The basics of using the logging module to record the events in a file are very simple.  For that, simply import the module from the library....

Python Logging Exception

...