0% found this document useful (0 votes)
30 views

Exception and Logging Code

The code defines a CustomException class to handle specific exceptions in a project. It overrides common exception methods and adds functionality to generate detailed error messages including the file name and line number where the exception occurred. Additionally, the code sets up a logging configuration to log messages to a file in the logs directory with a timestamped name, specifying the log format and an INFO level.

Uploaded by

Md Ahsan Ali
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Exception and Logging Code

The code defines a CustomException class to handle specific exceptions in a project. It overrides common exception methods and adds functionality to generate detailed error messages including the file name and line number where the exception occurred. Additionally, the code sets up a logging configuration to log messages to a file in the logs directory with a timestamped name, specifying the log format and an INFO level.

Uploaded by

Md Ahsan Ali
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

class CustomException(Exception):

"""
Custom exception class for handling specific exceptions in the project.
"""

def __init__(self, error_message: str, error_detail: sys):


"""
Initialize the CustomException.

:param error_message: The error message.


:param error_detail: The details of the error.
"""
super().__init__(error_message)
self.error_message =
CustomException.get_detailed_error_message(error_message, error_detail)

@staticmethod
def get_detailed_error_message(error_message: str, error_detail: sys) -> str:
"""
Generate a detailed error message including the error type, file name, line
number, and error message.

:param error_message: The error message.


:param error_detail: The details of the error.
:return: The detailed error message.
"""
_, _, exec_tb = error_detail.exc_info() # -------- error_type,
error_value, error_traceback = sys.exc_info()
exception_block = exec_tb.tb_frame
line_number = exec_tb.tb_lineno
file_name = exception_block.f_code.co_filename
error_message = f"Error occurred in script: [{file_name}] at line number:
[{line_number}] error message: [{error_message}]"
return error_message

def __str__(self):
"""
Return the string representation of the CustomException.

:return: The error message.


"""
return self.error_message

def __repr__(self):
"""
Return the string representation of the CustomException for debugging
purposes.

:return: The error message.


"""
return CustomException.__name__.str()

import logging
import os
from datetime import datetime

LOG_FILE = f"{datetime.now().strftime('%m_%d_%Y_%H_%M_%S')}.log"
logs_path = os.path.join(os.getcwd(), "logs", LOG_FILE)
os.makedirs(logs_path, exist_ok=True)

LOG_FILE_PATH = os.path.join(logs_path, LOG_FILE)

logging.basicConfig(
filename=LOG_FILE_PATH,
format="[%(asctime)s] %(lineno)d %(name)s - %(levelname)s - %(message)s",
level=logging.INFO,
)

Certainly! Let's break down the code and explain each part in detail.

The code you provided consists of two main parts: a custom exception class called
CustomException and a logging configuration.

CustomException class:

This class is defined as a subclass of the built-in Exception class, indicating


that it is a custom exception.
The purpose of this class is to handle specific exceptions in the project and
provide detailed error messages.
The class has an __init__ method that takes two parameters: error_message (a string
representing the error message) and error_detail (an object of the sys module).
Inside the __init__ method, the super().__init__(error_message) line is called to
initialize the base Exception class with the provided error_message.
The error_message attribute of the CustomException instance is set by calling the
get_detailed_error_message static method, passing the error_message and
error_detail as arguments.
The get_detailed_error_message static method is responsible for generating a
detailed error message that includes the error type, file name, line number, and
the original error message.
It uses the exc_info() function from the sys module to retrieve information about
the exception that occurred.
It extracts the execution traceback (exec_tb) from the exception information.
It retrieves the frame object (exception_block) from the traceback, which contains
information about the code block where the exception occurred.
It gets the line number (line_number) and file name (file_name) from the frame
object.
Finally, it constructs the detailed error message by combining the file name, line
number, and the original error message.
The __str__ method is defined to return the string representation of the
CustomException instance, which is the error_message attribute.
The __repr__ method is defined to return the string representation of the
CustomException class name for debugging purposes.
Logging configuration:

The code sets up a logging configuration to log messages to a file.


It imports the necessary modules: logging, os, and datetime.
It generates a log file name based on the current timestamp using
datetime.now().strftime('%m_%d_%Y_%H_%M_%S') and appends the ".log" extension.
It creates a directory named "logs" in the current working directory using
os.path.join(os.getcwd(), "logs", LOG_FILE) and os.makedirs(logs_path,
exist_ok=True). The exist_ok=True argument ensures that the directory is created if
it doesn't already exist.
It sets the LOG_FILE_PATH by joining the logs_path and LOG_FILE using
os.path.join().
It configures the logging using logging.basicConfig():
The filename parameter is set to LOG_FILE_PATH, specifying the file path where the
logs will be written.
The format parameter defines the format of the log messages, including the
timestamp, line number, logger name, log level, and message.
The level parameter is set to logging.INFO, indicating that only log messages with
a severity level of INFO or higher will be logged.
Overall, this code provides a custom exception class that can be used to handle
specific exceptions in the project and generate detailed error messages. It also
sets up a logging configuration to log messages to a file with a specific format
and log level.

You might also like