-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.py
76 lines (54 loc) · 1.45 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
import time
starttime = time.time()
def my_clock():
return time.time() - starttime
def len_ignore_n(s):
s = str(s).strip()
s = s.replace("\n" , "")
l = (len(bytes(s , encoding = "utf-8")) - len(s)) // 2 + len(s)
l += 7 * s.count("\t")
return l
def last_len(s):
s = str(s).strip()
return len_ignore_n(s.split("\n")[-1])
class Logger:
'''auto log
'''
def __init__(self , mode = [print] , log_path = None , append = ["clock"] , line_length = 90):
if log_path:
self.log_fil = open(log_path , "w" , encoding = "utf-8")
else:
self.log_fil = None
self.mode = mode
if ("write" in mode) and (not log_path):
raise Exception("Should have a log_path")
self.append = append
self.line_length = line_length
def close(self):
if self.log_fil:
self.log_fil.close()
def log(self , content = ""):
content = self.pre_process(content)
for x in self.mode:
if x == "write":
self.log_fil.write(content + "\n")
self.log_fil.flush()
else:
x(str(content))
def add_line(self , num = -1 , char = "-"):
if num < 0:
num = self.line_length
self.log(char * num)
def pre_process(self , content):
insert_space = self.line_length - last_len(content)
content += " " * insert_space
for x in self.append:
y = ""
if x == "clock":
y = "%.2fs" % (my_clock())
elif x == "time":
y = time.strftime("%Y-%m-%d %H:%M:%S" , time.localtime() )
else:
y = x()
content += "| " + y + " "
return content