-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlog.py
123 lines (106 loc) · 3.15 KB
/
log.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# Implements writeLog structure
import config
import json
import os.path
class Log:
def __init__(self, id, mode):
"""
Initialization
:param id: serverId; used to naming the log file on disk
:param mode: whether it is a writeLog or a successLog
"""
if not os.path.exists(config.LOG_DIR):
os.makedirs(config.LOG_DIR)
if mode == "W":
self.filename = str(id) + config.WRITE_LOG + '.json'
elif mode == "S":
self.filename = str(id) + config.SUCCESS_LOG + '.json'
self.filepath = os.path.join(config.LOG_DIR, self.filename)
self.data = self.load() if os.path.isfile(self.filepath) else {}
def load(self):
with open(self.filepath, 'r') as f:
data = json.load(f)
return data
def dump(self):
with open(self.filepath, 'w') as f:
json.dump(self.data, f, indent=4)
def __contains__(self, item):
"""
Support "in" operator
:param item:
:return:
"""
return item in self.data
def __getitem__(self, item):
"""
Support get element using []
:param item:
:return:
"""
return self.data[item]
def __iter__(self):
return self.data.__iter__()
def __next__(self):
return self.data.__next__()
def __setitem__(self, key, value):
"""
Support set element using []
:param key:
:param value:
:return:
"""
self.data[key] = value
def __delitem__(self, key):
"""
Support del
:param key:
:return:
"""
del self.data[key]
def __str__(self):
return str(self.data)
def __repr__(self):
return str(self.data)
if __name__ == "__main__":
def unit_test_writeLog():
"""
Unit test for writeLog
:return:
"""
print("Unit test for writeLog")
item = {"key": 1, "value": 2, "serverId": 3, "timeStamp": 4, "messageId": 5}
serverId = 1
messageId = 10
messageId2 = 11
writeLog = Log(serverId, "W")
writeLog[messageId] = ["put", item, [0]*5]
print(writeLog[messageId][2][1])
writeLog[messageId2] = ["put", item, [0]*5]
print(writeLog)
del writeLog[messageId2]
print(writeLog)
writeLog.dump()
writeLog2 = Log(serverId, "W")
print("writeLog2: ", repr(writeLog2))
def unit_test_successLog():
"""
Unit test for successLog
:return:
"""
print("Unit test for successLog")
item = {"key": 1, "value": 2, "serverId": 3, "timeStamp": 4, "messageId": 5}
serverId = 1
messageId = 10
messageId2 = 11
successLog = Log(serverId, "S")
successLog[messageId] = item
print(successLog[messageId])
successLog[messageId2] = item
print(successLog)
del successLog[messageId2]
print(successLog)
successLog.dump()
successLog2 = Log(serverId, "S")
print("writeLog2: ", repr(successLog2))
unit_test_successLog()
unit_test_writeLog()