enforcing-nophi-logging
它能做什么
这项技能添加一个安全过滤器,在日志、追踪和错误报告被写入或发送之前,去除其中的受保护健康信息。适合临床文本处理可能把患者细节泄露到日志中的团队。
适用场景
- ✓当 OpenMed 服务记录了可能包含患者细节的请求文本、模型输出或错误信息的时候。
- ✓当日志或错误追踪工具被发送到去标识化边界之外的中央服务的时候。
- ✓当你需要用计数或哈希值代替原始文本的结构化日志字段的时候。
技能链接
https://github.com/maziyarpanahi/openmed/blob/master/skills/enforcing-nophi-logging/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 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_scrubover string span attributes and events before export. - Error trackers: register a
before_sendhook (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
- Inventory sinks. List every place a clinical string can reach: app logs, access logs, OTel spans, error tracker, crash reports, request/response dumps.
- Install the regex pre-filter for structured identifiers (SSN, card, email, phone) — fast, runs on every record.
- 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. - Switch to structured fields. Replace "log the text" with "log counts, labels, offsets, ids".
- 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
评论
- …
同一仓库的更多技能
annotating-variants
5.8k帮你的智能体预测基因变异的作用,把 HGVS 名称转换为基因组位置,并使用免费的公共注释工具添加人群频率。
ask-openmed
5.8k帮你的智能体为临床文本请求选择合适的 OpenMed 工作流程,并在可能涉及患者数据时,先进行隐私检查。
assembling-fhir-bundles
5.8k把多份 FHIR 健康记录打包成一个事务 Bundle,可直接发送给 EHR 系统,并正确链接其中的内部引用。
auditing-deid-leakage
5.8k扫描已去标识化的临床文本,查找残留的标识符,例如社会安全号、银行卡号、电子邮件地址和日期,若仍有残留则阻止发布。