-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlogging.py
More file actions
44 lines (33 loc) · 1.41 KB
/
logging.py
File metadata and controls
44 lines (33 loc) · 1.41 KB
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
"""Custom logging function to ensure format conformity."""
from contextlib import contextmanager
import sys
import time
from typing import Generator, Optional
from .consts import Pid, Seqno
def log(pid: Pid, seqno: Seqno, msg: str, *, timestamp: Optional[float] = None) -> None:
"""Writes a log entry to stderr."""
timestamp = timestamp or time.time()
time_micro = int(timestamp * 1e6)
print(f"[{pid}, seqno={seqno}, time={time_micro}] {msg}", file=sys.stderr)
sys.stderr.flush()
def log_begin(pid: Pid, seqno: Seqno, event: str, *, timestamp: Optional[float] = None) -> None:
"""Logs the start of an event."""
return log(pid, seqno, "begin: " + event, timestamp=timestamp)
def log_end(pid: Pid, seqno: Seqno, event: str, *, timestamp: Optional[float] = None) -> None:
"""Logs the end of an event."""
return log(pid, seqno, "end: " + event, timestamp=timestamp)
@contextmanager
def log_duration(pid: Pid, seqno: Seqno, event: str) -> Generator[None, None, None]:
"""Logs the start and end of an event executed inside this context manager."""
log_begin(pid, seqno, event)
try:
yield
finally:
log_end(pid, seqno, event)
@contextmanager
def log_at_end(pid: Pid, seqno: Seqno, event: str) -> Generator[None, None, None]:
"""Logs the end of an event after this context manager finishes."""
try:
yield
finally:
log_end(pid, seqno, event)