본문으로 건너뛰기
Skillpedia
보안5.8k · #14693

enforcing-nophi-logging

하는 일

이 스킬은 로그, 추적 정보, 오류 보고서에 쓰이기 전이나 전송되기 전에 보호 대상 건강 정보(PHI)를 제거하는 안전 필터를 추가합니다. 임상 텍스트 처리가 로그로 환자 정보를 새게 할 수 있는 팀을 위한 스킬입니다.

사용하는 경우

  • ✓OpenMed 서비스가 환자 정보가 들어 있을 수 있는 요청 텍스트, 모델 출력, 오류 메시지를 기록할 때.
  • ✓비식별화 경계 밖에 있는 중앙 서비스로 로그나 오류 추적기가 전송될 때.
  • ✓원문 텍스트 대신 개수나 해시를 담은 구조화된 로그 필드가 필요할 때.

스킬 링크

https://github.com/maziyarpanahi/openmed/blob/master/skills/enforcing-nophi-logging/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/maziyarpanahi/openmed/blob/master/skills/enforcing-nophi-logging/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“우리 OpenMed API가 요청 텍스트를 기록하고 가끔 스택 트레이스를 오류 추적기로 보냅니다. 환자 정보가 저장되지 않도록 필터를 추가해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트는 로깅 설정에 빠른 패턴 필터와 모델 대체 수단을 추가해 기록이 출력되기 전에 정리되도록 하고, 확인할 수 없는 기록은 차단합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Enforcing No-PHI Logging

Logs are a top breach vector: a clinical string lands in a log line, gets shipped to a centralized log store and an error tracker, and is now PHI sitting outside the de-id boundary. OpenMed's local-first stance says no raw PHI in logs, caches, or error reports — this skill enforces it with a redaction guard that runs before any record is emitted.

When to use this skill

  • An OpenMed service logs request text, model output, or exception messages.
  • You ship logs/traces to a centralized store or error tracker (Sentry, ELK).
  • You need a logging.Filter (or OTel processor) that redacts PHI pre-emit.
  • You want structured, no-PHI log fields (offsets, hashes, counts) for debugging.

Quick start — a redacting logging.Filter

import logging
import re
import openmed

# Cheap regex pre-filter for the highest-risk structured identifiers. This runs
# on every record, so keep it fast; the model is the fallback for free-text PHI.
_FAST_PATTERNS = [
    (re.compile(r"\b\d{3}-\d{2}-\d{4}\b"), "[SSN]"),
    (re.compile(r"\b\d{16}\b"), "[CARD]"),
    (re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b"), "[EMAIL]"),
    (re.compile(r"\b(?:\+?\d[\d().\-\s]{7,}\d)\b"), "[PHONE]"),
]

class NoPHIFilter(logging.Filter):
    """Redact PHI from a log record before it is emitted. Fail closed."""

    def __init__(self, model_name: str | None = None, use_model: bool = True):
        super().__init__()
        self.model_name = model_name
        self.use_model = use_model

    def filter(self, record: logging.LogRecord) -> bool:
        try:
            message = record.getMessage()
            record.msg = self._scrub(message)
            record.args = ()                 # message already rendered & scrubbed
        except Exception:
            # Never let the logger leak on error — drop the message, keep the level.
            record.msg = "[REDACTED: scrub error]"
            record.args = ()
        return True                          # keep the (now-clean) record

    def _scrub(self, text: str) -> str:
        for pattern, tag in _FAST_PATTERNS:
            text = pattern.sub(tag, text)
        if not self.use_model:
            return text
        # Model fallback for free-text PHI (names, locations, dates). Replace by
        # offset, right-to-left, so earlier offsets stay valid.
        spans = openmed.extract_pii(text, model_name=self.model_name) \
            if self.model_name else openmed.extract_pii(text)
        for e in sorted(spans.entities, key=lambda s: s.start, reverse=True):
            text = text[:e.start] + f"[{e.label}]" + text[e.end:]
        return text

# Attach to every handler that might emit clinical text.
handler = logging.StreamHandler()
handler.addFilter(NoPHIFilter(model_name="OpenMed/Privacy-PII-Detection"))
logging.getLogger("openmed.service").addHandler(handler)

Prefer structured, no-PHI fields

Don't log the note and scrub it — log about it without the text in the first place:

logger.info(
    "deidentified note",
    extra={
        "doc_id": doc_id,                       # opaque id, not the text
        "phi_entity_count": len(result.entities),
        "phi_labels": sorted({e.label for e in result.entities}),
        "char_len": len(text),
        # offsets/hashes for debugging; never the plaintext span
        "phi_offsets": [(e.start, e.end) for e in result.entities],
    },
)

Redaction is the safety net; not logging PHI is the actual fix.

OpenTelemetry / error trackers

  • Spans: add a SpanProcessor.on_end (or attribute hook) that runs the same _scrub over string span attributes and events before export.
  • Error trackers: register a before_send hook (e.g. Sentry) that scrubs exception messages, breadcrumbs, and request bodies. Stack traces often embed the offending input — scrub the message, not just the frames.

Workflow

  1. Inventory sinks. List every place a clinical string can reach: app logs, access logs, OTel spans, error tracker, crash reports, request/response dumps.
  2. Install the regex pre-filter for structured identifiers (SSN, card, email, phone) — fast, runs on every record.
  3. Add the model fallback (openmed.extract_pii) for free-text PHI on the sinks that carry clinical narrative; skip it on hot paths where regex suffices.
  4. Switch to structured fields. Replace "log the text" with "log counts, labels, offsets, ids".
  5. Fail closed. On any scrub error,
자주 묻는 질문

모든 로그 줄을 필터링하나요?

네. 각 기록에 대해 흔한 식별자는 빠른 패턴 필터로, 자유 텍스트의 세부 정보는 모델로 처리합니다.

필터가 실패하면 어떻게 되나요?

안전하지 않은 기록이 출력되지 않도록 실패 시 차단하는 방식으로 설계되어 있습니다.

추적 정보와 오류 보고서도 다루나요?

네. 일반 로그뿐 아니라 OpenTelemetry 스팬과 오류 추적기도 다룹니다.

상세 정보

작성자의 원본 설명

Add a logging and telemetry guard that scrubs or blocks PHI from logs, traces, and error reports around an OpenMed deployment. Use when the user wants a Python logging.Filter that redacts protected health information before records are emitted, wants to keep PHI out of OpenTelemetry spans or error trackers, needs structured no-PHI log fields, or is worried that logs and stack traces are leaking patient data. Trigger on \"scrub logs\", \"redact PHI from logs\", \"no-PHI logging\", \"logging filter\", \"telemetry redaction\", \"logs leaking patient data\", or \"OpenTelemetry redaction\" in an Op

repo: maziyarpanahi/openmed

인기도

GitHub 스타
5.8k
순위
#14693
라이선스
Apache-2.0
업데이트
2026. 11. 2.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬