Skip to content

Commit 607f3db

Browse files
authored
[FEAT] Added custom logger function (#17)
* chore: replace print with logger * feat: create custom logger function * chore: add gitignore file * config: use dictConfig to tweak logger * chore: call the configure logging function * feat: check log directory and file existence * chore: replace print with logger * chore: change log level to warn * chore: customize warn level message
1 parent ea07379 commit 607f3db

File tree

4 files changed

+107
-7
lines changed

4 files changed

+107
-7
lines changed

.gitignore

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,12 @@ venv_*/
9898
.nvimrc
9999
.vimrc
100100

101+
/logs/*
101102
mypy.ini
103+
*.DS_Store
104+
102105
# Output Directories
103106
output
104107
result
105108
results
106-
outputs
109+
outputs

school_center.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,17 @@
99
import math
1010
import csv
1111
import random
12+
import logging
1213
import argparse
1314
import os
1415
from typing import Dict, List
1516

17+
from utils.custom_logger import configure_logging
18+
19+
20+
configure_logging()
21+
22+
logger = logging.getLogger(__name__)
1623

1724
def create_dir(dirPath:str):
1825
"""
@@ -201,11 +208,10 @@ def is_allocated(scode1: str, scode2:str) -> bool:
201208

202209
if to_allot > 0:
203210
remaining+=to_allot
204-
print(f"{to_allot}/{s['count']} left for {s['scode']} {s['name-address']} centers: {len(centers_for_school)}")
211+
logger.warn(f"{to_allot}/{s['count']} left for {s['scode']} {s['name-address']} centers: {len(centers_for_school)}")
205212

206213

207-
print("Remaining capacity at each center (remaining_capacity cscode):")
208-
print(sorted([(v,k) for k, v in centers_remaining_cap.items() if v != 0]))
209-
print(f"Total remaining capacity across all centers: {sum({k:v for k, v in centers_remaining_cap.items() if v != 0}.values())}")
210-
print(f"Students not assigned: {remaining}")
211-
214+
logger.info("Remaining capacity at each center (remaining_capacity cscode):")
215+
logger.info(sorted([(v,k) for k, v in centers_remaining_cap.items() if v != 0]))
216+
logger.info(f"Total remaining capacity across all centers: {sum({k:v for k, v in centers_remaining_cap.items() if v != 0}.values())}")
217+
logger.info(f"Students not assigned: {remaining}")

utils/custom_file_handler.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
"""File handler with a few tweaks."""
2+
3+
from logging import FileHandler
4+
5+
6+
class CustomFileHandler(FileHandler):
7+
"""Custom logging file handler that adds an extra line at the EOF."""
8+
9+
def close(self):
10+
if self.stream is not None:
11+
self.stream.write("")
12+
super().close()

utils/custom_logger.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""Custom logging module with some formatting."""
2+
3+
import os
4+
import sys
5+
import logging.config
6+
from os.path import abspath, dirname, join, exists
7+
8+
9+
ROOT_DIR: str = abspath(dirname(dirname(__file__)))
10+
LOGS_DIR: str = join(ROOT_DIR, "logs")
11+
LOGS_TARGET: str = join(ROOT_DIR, "logs", "custom_logs.log")
12+
CUSTOM_FILE_HANDLER_PATH = "utils.custom_file_handler.CustomFileHandler"
13+
14+
if not exists(LOGS_DIR):
15+
os.makedirs(LOGS_DIR)
16+
17+
if not exists(LOGS_TARGET):
18+
with open(LOGS_TARGET, "a", encoding="utf-8") as file:
19+
os.utime(LOGS_TARGET, None)
20+
21+
22+
LOGGING_CONFIG: dict = {
23+
"version": 1,
24+
"formatters": {
25+
"standard": {
26+
"datefmt": "%y-%m-%d %H:%M:%S",
27+
"format": "🚀 %(asctime)s - %(name)s - %(levelname)s - %(message)s \n",
28+
},
29+
"warn": {
30+
"datefmt": "%y-%m-%d %H:%M:%S",
31+
"format": "🔔 %(asctime)s - %(name)s - %(levelname)s - %(message)s \n",
32+
},
33+
"error": {
34+
"datefmt": "%y-%m-%d %H:%M:%S",
35+
"format": "❌ %(asctime)s - %(name)s - %(levelname)s - %(message)s \n",
36+
},
37+
},
38+
"handlers": {
39+
"file_error": {
40+
"mode": "a",
41+
"level": "ERROR",
42+
"encoding": "utf-8",
43+
"formatter": "error",
44+
"filename": LOGS_TARGET,
45+
"class": CUSTOM_FILE_HANDLER_PATH,
46+
},
47+
"console_info": {
48+
"level": "INFO",
49+
"stream": sys.stdout,
50+
"formatter": "standard",
51+
"class": "logging.StreamHandler",
52+
},
53+
"console_warn": {
54+
"level": "WARN",
55+
"formatter": "warn",
56+
"stream": sys.stdout,
57+
"class": "logging.StreamHandler",
58+
},
59+
"console_error": {
60+
"level": "ERROR",
61+
"stream": sys.stderr,
62+
"formatter": "error",
63+
"class": "logging.StreamHandler",
64+
},
65+
},
66+
"loggers": {
67+
"": {
68+
"level": "INFO",
69+
"propagate": True,
70+
"handlers": ["file_error", "console_info", "console_warn", "console_error"],
71+
}
72+
},
73+
}
74+
75+
76+
# Call this once to initialize logger
77+
def configure_logging() -> None:
78+
"""Pass the logging configuration to logger."""
79+
logging.config.dictConfig(LOGGING_CONFIG)

0 commit comments

Comments
 (0)