Create log.py
Browse files
log.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class Log:
|
| 2 |
+
def __init__(self, path):
|
| 3 |
+
dirname = os.path.dirname(path)
|
| 4 |
+
os.makedirs(dirname, exist_ok=True)
|
| 5 |
+
f = open(path, "a+")
|
| 6 |
+
|
| 7 |
+
# Check that the file is newline-terminated
|
| 8 |
+
size = os.path.getsize(path)
|
| 9 |
+
if size > 0:
|
| 10 |
+
f.seek(size - 1)
|
| 11 |
+
end = f.read(1)
|
| 12 |
+
if end != "\n":
|
| 13 |
+
f.write("\n")
|
| 14 |
+
self.f = f
|
| 15 |
+
self.path = path
|
| 16 |
+
|
| 17 |
+
def log(self, event):
|
| 18 |
+
event["_event_id"] = str(uuid.uuid4())
|
| 19 |
+
json.dump(event, self.f)
|
| 20 |
+
self.f.write("\n")
|
| 21 |
+
|
| 22 |
+
def state(self):
|
| 23 |
+
state = {"complete": set(), "last": None}
|
| 24 |
+
for line in open(self.path):
|
| 25 |
+
event = json.loads(line)
|
| 26 |
+
if event["type"] == "submit" and event["success"]:
|
| 27 |
+
state["complete"].add(event["id"])
|
| 28 |
+
state["last"] = event
|
| 29 |
+
return state
|