perf(logs): reuse event sequence for unchanged log files
This commit is contained in:
1 parent
d0125f8f59
commit
159616ea4a
2 files changed
+56
-1
No files matched your search
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from collections import OrderedDict
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
@@ -47,6 +48,7 @@ class LoggingContext:
|
||||
application_log_path: Path
|
||||
logger: logging.Logger
|
||||
_event_lock: threading.RLock = field(default_factory=threading.RLock, repr=False)
|
||||
_event_sequences: OrderedDict = field(default_factory=OrderedDict, repr=False)
|
||||
|
||||
def report_exception(
|
||||
self,
|
||||
@@ -128,7 +130,11 @@ def append_task_event(
|
||||
raise TaskCenterError("event_details", "task event details must be JSON-compatible") from error
|
||||
path = task_directory / "events.jsonl"
|
||||
with context._event_lock:
|
||||
sequence = _next_event_sequence(path)
|
||||
# Reuse only a sequence belonging to this exact, unchanged file. External
|
||||
# appends, rotation, truncation and replacement fall back to the disk tail.
|
||||
cached = context._event_sequences.pop(path, None)
|
||||
stamp = _event_file_stamp(path)
|
||||
sequence = cached[1] if cached is not None and stamp is not None and cached[0] == stamp else _next_event_sequence(path)
|
||||
event = {
|
||||
"sequence": sequence,
|
||||
"timestamp_utc": _utc_now_text(),
|
||||
@@ -153,6 +159,14 @@ def append_task_event(
|
||||
handle.write(encoded)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
written = os.fstat(handle.fileno())
|
||||
final = _event_file_stamp(path)
|
||||
# Windows fstat/Path.stat differ in ctime semantics; retain the full
|
||||
# Path stamp only after handle identity, size and mtime agree.
|
||||
if final is not None and final[:4] == (written.st_dev, written.st_ino, written.st_size, written.st_mtime_ns):
|
||||
context._event_sequences[path] = (final, sequence + 1)
|
||||
while len(context._event_sequences) > 64:
|
||||
context._event_sequences.popitem(last=False)
|
||||
except OSError as error:
|
||||
raise TaskCenterError("event_write_failed", "cannot append task event") from error
|
||||
context.logger.log(
|
||||
@@ -167,6 +181,14 @@ def append_task_event(
|
||||
return event
|
||||
|
||||
|
||||
def _event_file_stamp(path):
|
||||
try:
|
||||
info = path.stat()
|
||||
return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def capture_subprocess_output(
|
||||
context: LoggingContext,
|
||||
*,
|
||||
|
||||
Reference in new issue
Block a user