-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.py
94 lines (83 loc) · 2.56 KB
/
logger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from datetime import datetime
import os
class Logger:
"""
Logger class with three levels of logging namely INFO, DEBUG, EXCEPTION and two
modes of writing log namely command line and external file logging
"""
# Static variables
# right-padding
PADDING = 9
# current directory
CURR_DIRECTORY = os.getcwd()
def __init__(self, filename=None, mode="console"):
"""
Parametrized Contructor
@params
filename = name of the file
mode = console/file
"""
# If no file name is provided make a default one
if filename is None:
today = datetime.now().today()
# making the file name unique
self.filename = f"log[{today}].log"
else:
self.filename = filename
# Default logging mode is console
self.mode = mode
# append subdirectory to filename
# if log folder doesnot exists in current directory make one
path = self.CURR_DIRECTORY + "/log"
if not os.path.isdir(path):
os.mkdir(path)
# append path
self.filename = path + "/" + self.filename
def clear(self):
"""Clears the log file"""
if self.mode == "file":
with open(self.filename, "r+") as file:
file.truncate(0)
else:
os.system("cls" if os.name in ("nt", "dos") else "clear")
def log(self, msg, level="INFO"):
"""
Functions log message with specified level
@params
msg = message to be displayed
level = log level [INFO, DEBUG, ERROR]
"""
log_type = level.ljust(self.PADDING)
now = datetime.now().today()
log_message = f"{log_type}|{now.hour}:{now.minute}| {msg}\n"
if self.mode == "file":
try:
with open(self.filename, "a") as file:
file.write(log_message)
except Exception as e:
print(f"An error has occured while logging: {e}")
else:
print(log_message)
def info(self, msg):
"""
Log info
@params
msg = info message to be displayed
"""
self.log(msg, "INFO")
def debug(self, msg):
"""
Log Debug
@params
msg = debug message to be displayed
"""
self.log(msg, "DEBUG")
def error(self, msg):
"""
Log Exception
@params
msg = error message to be displayed
"""
self.log(msg, "ERROR")
# Creating logger instance
logger = Logger(mode="file")