Skip to content

Commit 0b8bfcc

Browse files
exception handling and logger copmpleted
1 parent 86df049 commit 0b8bfcc

7 files changed

Lines changed: 44 additions & 0 deletions

File tree

networksecurity/.DS_Store

2 KB
Binary file not shown.
189 Bytes
Binary file not shown.

networksecurity/exception/__init__.py

Whitespace-only changes.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import sys
2+
from networksecurity.logging.logger import logger
3+
4+
class NetworkSecurityException(Exception):
5+
def __init__(self, error_message, error_details: sys):
6+
self.error_message = error_message
7+
_, _, exc_tb = error_details.exc_info()
8+
self.line_number = exc_tb.tb_lineno
9+
self.file_name = exc_tb.tb_frame.f_code.co_filename
10+
11+
def __str__(self):
12+
return "Error occurred in python script name [{0}] line number [{1}] with error message [{2}]".format(
13+
self.file_name, self.line_number, self.error_message)
14+
15+
if __name__ == "__main__":
16+
try:
17+
logger.info("This is a test log message")
18+
a = 1 / 0 # This will cause an exception
19+
except Exception as e:
20+
error = NetworkSecurityException(e, sys)
21+
logger.error(str(error)) # Log the error
197 Bytes
Binary file not shown.
644 Bytes
Binary file not shown.

networksecurity/logging/logger.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import logging
2+
import os
3+
from datetime import datetime
4+
5+
# Create a unique log file name based on the current timestamp
6+
LOG_FILE = f"{datetime.now().strftime('%m_%d_%Y_%H_%M_%S')}.log"
7+
8+
# Define the logs directory and ensure it exists
9+
logs_dir = os.path.join(os.getcwd(), "logs")
10+
os.makedirs(logs_dir, exist_ok=True)
11+
12+
# Define the full log file path
13+
LOG_FILE_PATH = os.path.join(logs_dir, LOG_FILE)
14+
15+
# Configure the logging
16+
logging.basicConfig(
17+
filename=LOG_FILE_PATH,
18+
format="[%(asctime)s] %(lineno)d %(name)s - %(levelname)s - %(message)s",
19+
level=logging.INFO,
20+
)
21+
22+
# Define and configure a logger object
23+
logger = logging.getLogger("networksecurity")

0 commit comments

Comments
 (0)