-
Notifications
You must be signed in to change notification settings - Fork 6
/
logger.py
67 lines (55 loc) · 1.66 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
"""
Thread synchronised log recorder for FlatTrack
"""
import datetime
import os
import traceback
from threading import RLock
class LogContext(object):
"""
A Logger Class
"""
def __init__(self):
self.lock = RLock()
self.count = 0
self.maxwrite = 3000
folder = os.path.abspath(os.path.dirname(__file__))
self.filename = os.path.join(os.path.dirname(folder), "plugin.log")
def set_filename(self, filename):
self.filename = filename
def rotate_log(self):
"""
Rotate the current log file
:return:
"""
with self.lock:
try:
self.count = 0
filename = self.filename
moved = filename + ".old"
if os.path.exists(moved):
os.unlink(moved)
if os.path.exists(filename):
os.rename(filename, moved)
except Exception as err:
print("rotate_log failed..: {}".format(err))
self.write("Log rotated to {}".format(moved))
def write(self, message):
"""
Write a log message
:param message:
:return:
"""
with self.lock:
self.count += 1
timestamp = datetime.datetime.utcnow().isoformat()
try:
with open(self.filename, "a") as logfile:
logfile.write(timestamp + " ")
logfile.write(message)
logfile.write("\n")
except Exception as err:
print(str(err))
if self.count > self.maxwrite:
self.rotate_log()
LOG = LogContext()