"""Versioned Prod ingress log format, installed through the existing D3 publisher.""" import json import re FORMAT_BEGIN = "# NexusCRM Prod HTTP log format begin" FORMAT_END = "# NexusCRM Prod HTTP log format end" def strip_access_logging(content: str) -> str: """Remove only the exact generated http-level block when replacing its server.""" pattern = (rf"(?m)^{re.escape(FORMAT_BEGIN)}\n" r"log_format nexuscrm_prod_http_v1_slot_\d+ escape=json '[^\n]*';\n" rf"{re.escape(FORMAT_END)}\n") stripped = re.sub(pattern, "", content) if FORMAT_BEGIN in stripped or FORMAT_END in stripped: raise ValueError("malformed owned Prod log-format block") return stripped def with_access_logging(server: str, slot: str, release: str, *, marker: str = "") -> str: if not re.fullmatch(r"slot-\d+", slot) or not re.fullmatch(r"[A-Za-z0-9_.-]+", release): raise ValueError("unsafe Prod log identity") name = "nexuscrm_prod_http_v1_" + slot.replace("-", "_") log_path = f"/var/log/nginx/nexuscrm-prod-d3-{slot}.access.log" directive = f"access_log {log_path};" if server.count(directive) != 1: raise ValueError("expected exactly one Prod ingress access log") fields = { "schema": "nexuscrm.prod.http.v1", "msec": "$msec", "method": "$request_method", "uri": "$uri", "status": "$status", "request_time": "$request_time", "nginx_request_id": "$request_id", "upstream_request_id": "$upstream_http_x_request_id", "release": release, } # All variable values are JSON strings and escaped by nginx. No client IP, # cookies, Authorization header, body, or user ID is logged in this stream. payload = json.dumps(fields, separators=(",", ":")) return (f"{FORMAT_BEGIN}\nlog_format {name} escape=json '{payload}';\n{FORMAT_END}\n" + (marker + "\n" if marker else "") + server.replace(directive, f"access_log {log_path} {name};"))