This repository has been archived by the owner on Mar 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logs.py
79 lines (67 loc) · 2.83 KB
/
logs.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
#!usr/bin/env python3
# Logging module, originally created by Suaj commited for FakeOS
import os.path
from datetime import datetime, date
# The only purpose of this function is to save some lines in the main file
def ask_for_logging():
while True:
log_conf = input("Do you want to create log files about the\
program's excecution? [Y/n/exit]\n")
if log_conf.lower() in ("y", "yes", "1"):
return True
elif log_conf.lower() in ("n", "no", "2", "0"):
return False
elif log_conf.lower() == "exit":
print("Exiting...")
exit()
else:
print("Please enter a valid option.")
# When the user turns off logging, we simply convert every call to the
# functions into nothing so we don't have to change the code.
class Logging:
def __init__(self, conf, verbose=False, path=f"{date.today()} Log.txt"):
self.conf = conf
if self.conf:
self.verbose = verbose
self.path = path
self.header = "This file was generated by FakeOS on\
{} at {}.\n\n".format(date.today(), datetime.now().strftime("%H:%M:%S"))
if os.path.isfile(self.path):
with open(self.path, "r+") as self.file:
self.file.seek(0)
self.file_content = self.file.readline()
# Write the header, if the file is empty
if len(self.file_content) == 0:
self.file.writelines(self.header)
else: # Create the file and apply the header
with open(self.path, "w") as self.file:
self.file.writelines(self.header)
else:
pass
# Log the given text to a file
# The last parameter allows us to individually control the printing
# regardless of the "verbose" option earlier.
# Errorlvl has a default value because most logs are about information
def log(self, text, errorlvl=0, printlog=False):
if self.conf:
self.text = text
self.errorlvl = errorlvl
# UERROR = User Error. Errorlvl is just playing with the index
self.errorlvls = ("INFO", "UERROR", "ERROR", "FATAL ERROR")
self.errorlvl = self.errorlvls[self.errorlvl]
with open(f"{self.path}", "a", encoding="utf-8") as self.file:
self.text2file = "{} - {}: {}\n".format(
datetime.now().strftime("%H:%M:%S"), self.errorlvl,
self.text)
self.file.writelines(self.text2file)
if self.verbose or printlog:
print(self.text)
else:
pass
# Debug
if __name__ == "__main__":
log = Logging(ask_for_logging(), verbose=True)
log.log("Normal log")
log.log("User error log", 1)
log.log("Oops log", 2)
log.log("UH OH", 3)