42 lines
1.3 KiB
Python
42 lines
1.3 KiB
Python
import json
|
|
import logging
|
|
from datetime import datetime, timezone
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
|
|
|
|
SAFE_EXTRA = ("monitor_id", "url", "status", "http_status", "latency_ms", "error")
|
|
|
|
|
|
def redact_url(value: str) -> str:
|
|
try:
|
|
parts = urlsplit(value)
|
|
host = parts.hostname or ""
|
|
if parts.port:
|
|
host = f"{host}:{parts.port}"
|
|
return urlunsplit((parts.scheme, host, parts.path, "", ""))
|
|
except (TypeError, ValueError):
|
|
return "[invalid-url]"
|
|
|
|
|
|
class JsonFormatter(logging.Formatter):
|
|
def format(self, record: logging.LogRecord) -> str:
|
|
payload: dict[str, object] = {
|
|
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
"level": record.levelname,
|
|
"logger": record.name,
|
|
"event": record.getMessage(),
|
|
}
|
|
for key in SAFE_EXTRA:
|
|
if hasattr(record, key):
|
|
value = getattr(record, key)
|
|
payload[key] = redact_url(str(value)) if key == "url" else value
|
|
return json.dumps(payload, separators=(",", ":"), default=str)
|
|
|
|
|
|
def configure_logging(level: str) -> None:
|
|
handler = logging.StreamHandler()
|
|
handler.setFormatter(JsonFormatter())
|
|
root = logging.getLogger()
|
|
root.handlers = [handler]
|
|
root.setLevel(level.upper())
|