0% found this document useful (0 votes)
16 views6 pages

User Defined Exception and Logger

Exception handling and logging

Uploaded by

nikambhavesh9147
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views6 pages

User Defined Exception and Logger

Exception handling and logging

Uploaded by

nikambhavesh9147
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

user defined exception and logger

November 15, 2024

1 User-defined Exceptions
By deriving a new class from the default Exception class in Python, we can define our own exception
types.

[1]: class MyCustomError(Exception):


pass

In the above code, MyCustomError is derived from the built-in Exception class. You can use this
in your code by using the raise statement.

[2]: raise MyCustomError("This is a custom error")

---------------------------------------------------------------------------
MyCustomError Traceback (most recent call last)
Cell In[2], line 1
----> 1 raise MyCustomError("This is a custom error")

MyCustomError: This is a custom error

[ ]: # define user-defined exceptions


class WrongAge(Exception):
"Raised when the input value is less than 100"
pass

[ ]: # you need to guess this number


n = 18

try:
input_num = int(input("Enter a age: "))
if input_num < n:
raise WrongAge # calling your custom exception
else:
print("You can work")
except WrongAge:
print("Invalid Age: You are not allowed to work")

1
2 Logging
Logging is a technique for monitoring events that take place when some software is in use.
For the creation, operation, and debugging of software, logging is crucial.
There are very little odds that you would find the source of the issue if your programme fails and
you don’t have any logging records.
Additionally, it will take a lot of time to identify the cause.

[3]: # first import the logging library


import logging

""" In the code above, we first import the logging module, then we call the
basicConfig method to configure the logging.

We set the level to DEBUG, which means that all logs of level
DEBUG and above will be tracked."""

logging.basicConfig(level=logging.DEBUG)

# Logging Level: severity of the event being logged


# Least severe to most severe
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

DEBUG:root:This is a debug message


INFO:root:This is an info message
WARNING:root:This is a warning message
ERROR:root:This is an error message
CRITICAL:root:This is a critical message
Some programmers utilise the idea of “Printing” the statements to check whether they were correctly
performed or if an error had occurred.
However, printing is not a smart move. For basic scripts, it might be the answer to your problems,
however the printing solution will fall short for complex programmes.
A built-in Python package called logging enables publishing status messages to files or other output
streams. The file may provide details about which portion of the code is run and any issues that
have come up.
Here are the different log levels in increasing order of severity:
DEBUG: Detailed information, typically of interest only when diagnosing problems.
INFO: Confirmation that things are working as expected.

2
WARNING: An indication that something unexpected happened, or may happen in the future
(e.g. ‘disk space low’). The software is still working as expected.
ERROR: More serious problem that prevented the software from performing a function.
CRITICAL: A very serious error, indicating that the program itself may be unable to continue
running.

3 Debug
[4]: import logging

logging.basicConfig(level=logging.DEBUG)

def add(x, y):


logging.debug('Variables are %s and %s', x, y)
return x + y

add(1, 2)

DEBUG:root:Variables are 1 and 2

[4]: 3

4 Info
[5]: import logging

logging.basicConfig(level=logging.INFO)

def login(user):
logging.info('User %s logged in', user)

login('Admin User')

INFO:root:User Admin User logged in

5 Warning
[6]: import logging

logging.basicConfig(level=logging.WARNING)

def MyBalance(amount):
if amount < 40000:
logging.warning('Sorry you have Low balance: %s', amount)

3
MyBalance(10000)

WARNING:root:Sorry you have Low balance: 10000

6 Error
[7]: import logging

logging.basicConfig(level=logging.ERROR)

def LetUsDivide(n, d):


try:
result = n / d
except ZeroDivisionError:
logging.error('You are trying to divide by zero, which is not allowed')
else:
return result

LetUsDivide(4, 0)

ERROR:root:You are trying to divide by zero, which is not allowed

7 Critical Errors
[8]: import logging

logging.basicConfig(level=logging.CRITICAL)

def LetUsCheckSystem(sys):
if sys != 'OK':
logging.critical('System failure: %s', sys)

LetUsCheckSystem('You need to handle the issue now')

CRITICAL:root:System failure: You need to handle the issue now

8 Save to a file
[12]: import os

# Specify the directory and file


dir_path = r"D:\Data Science material\basic python"
log_file = 'file123.txt'
full_path = os.path.join(dir_path, log_file)

# Check if the directory exists and create it if necessary


os.makedirs(dir_path, exist_ok=True)

4
# Try writing a test message to the file
with open(full_path, 'w') as f:
f.write('This is a test message')

[13]: import os
print(os.getcwd())

D:\Data Science material\basic python

[15]: import os
import logging

# Specify the directory and file


dir_path = r"D:\Data Science material\basic python"
log_file = 'file123.txt'
full_path = os.path.join(dir_path, log_file)

# Check if the directory exists and create it if necessary


os.makedirs(dir_path, exist_ok=True)

# Set up logging
# Get a logger instance (this will fetch the root logger)
logger = logging.getLogger()

# Set the level of the logger to CRITICAL


# This means it will handle events of level CRITICAL and above
logger.setLevel(logging.CRITICAL)

# Create a FileHandler instance to write logs to a file


handler = logging.FileHandler(full_path)

# Set the format of the logs using a Formatter


# This format includes the log timestamp, log level and log message
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(message)s'))

# Add the handler to the logger


# This connects the logger to the handler so that logs get written to the file
logger.addHandler(handler)

def LetUsCheckSystem(sys):
if sys != 'OK':
logging.critical('System failure: %s', sys)

LetUsCheckSystem('You need to handle the issue now')


handler.close()

5
CRITICAL:root:System failure: You need to handle the issue now

[ ]: import pdb

def addition(a, b):


pdb.set_trace() # Set a breakpoint here
result = a + b
return result

print(addition(5, 7))

[ ]:

You might also like