-
Notifications
You must be signed in to change notification settings - Fork 97
/
Logger.py
90 lines (77 loc) · 2.78 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
#!usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/6/9 21:47
# @Author : Fandes
# @FileName: Logger.py
# @Software: PyCharm
import io
import os
import sys, time
from PyQt5.QtCore import QThread
class Logger(QThread):
def __init__(self, log_path="jamtools.log"):
super(Logger, self).__init__()
# sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
self.terminal = sys.stdout
self.log_path = log_path
self.logtime = time.time() - 2
self.loglist = []
self.running = True
self.start()
def run(self) -> None:
if os.path.exists(self.log_path):
try:
ls = os.path.getsize(self.log_path)
print("日志文件大小为:", ls, " 保存于:", self.log_path)
if ls > 2485760:
print("日志文件过大")
with open(self.log_path, "r+", encoding="utf8")as f:
f.seek(ls - 1885760)
log = "已截断日志" + time.strftime("%Y-%m-%d %H:%M:%S:\n", time.localtime(time.time())) + f.read()
f.seek(0)
f.truncate()
f.write(log)
print("新日志大小", os.path.getsize(self.log_path))
except Exception as e:
with open(self.log_path, "w", encoding="utf8")as f:
f.write("已清空日志, {}".format(e))
self.log = open(self.log_path, "a", encoding='utf8')
self.log.write("\n\nOPEN@" + time.strftime("%Y-%m-%d %H:%M:%S:\n", time.localtime(time.time())))
try:
while self.running:
if len(self.loglist):
self.process(self.loglist.pop(0))
else:
time.sleep(0.05)
except:
sys.stdout = self.terminal
print(sys.exc_info(), "log47")
def stop(self):
self.running = False
self.quit()
self.wait(2)
def write(self, message):
self.loglist.append(message)
def process(self, message):
self.terminal.write(message)
self.terminal.flush()
now = time.time()
timestr = ""
if now - self.logtime > 1:
timestr = "\n"+"-" * 20 + "@" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) + "-" * 20 + "\n"
log = timestr + message
self.log.write(log)
if now - self.logtime > 1:
self.logtime = now
self.log.flush()
def flush(self):
pass
if __name__ == '__main__':
st = time.time()
sys.stdout = Logger('hfks.log')
print("fsdafwefs")
print(time.time() - st)
time.sleep(1.5)
print(time.localtime())
time.sleep(1.1)
print("rtyuio" * 50)