Enforcing Nophi Logging logo

Enforcing Nophi Logging

CommunityPopular
maziyarpanahi
enforcing-nophi-logging

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 OpenMed deployment.

Overview

Publishermaziyarpanahi
Repositoryopenmed
Skill nameenforcing-nophi-logging
Stars
5.3K
Forks
677
Bundled files
Instructions only
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by maziyarpanahi on GitHub. Read the source before you install it.

Installation

Install the Enforcing Nophi Logging AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/maziyarpanahi/openmed.git /tmp/openmed
mkdir -p .claude/skills
cp -r /tmp/openmed/skills/enforcing-nophi-logging .claude/skills/enforcing-nophi-logging
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Enforcing Nophi Logging in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Enforcing Nophi Logging on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Enforcing Nophi Logging is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

python
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:

python
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, drop the message content, not the redaction.
  6. Test it. Unit-test that known PHI strings never survive a round trip through the filter, including in exception messages.

Hand-off to / from OpenMed

  • Uses openmed.extract_pii (and optionally the regex pre-filter) as the PHI detector — the same engine documented in extracting-pii-entities.
  • From building-with-openmed: this is the runtime guard for the local-first, no-PHI-in-artifacts rule.
  • Pairs with gating-deid-leakage: the gate proves the model doesn't leak; this guard proves your logs and traces don't leak.
  • To auditing-deidentification-runs: route audit output through the same no-PHI discipline (offsets/hashes, never plaintext).

Edge cases & gotchas

  • record.args must be cleared after scrubbing. If you rewrite record.msg but leave %s args, the formatter re-injects raw PHI downstream.
  • Scrub before fan-out. Filters on one handler don't protect others — attach to every handler, or scrub at the record/formatter layer.
  • Latency budget. The model fallback costs inference per record; gate it behind a level threshold or reserve it for narrative-bearing sinks.
  • Regex alone is not de-id. It catches structured identifiers; names, locations, and dates need the model. Use both, model last.
  • Exception messages are PHI carriers. f"failed on {note}" leaks; scrub exception text and error-tracker payloads, not just logger.info calls.
  • Fail closed, never open. A scrub error must redact the content, never emit the unscrubbed original.
  • No raw PHI even in DEBUG. "It's only debug logs" is how breaches happen; the guard applies at every level.

Standards & references

Frequently asked questions

What does the Enforcing Nophi Logging AI skill do?

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 OpenMed deplo...

Why use Enforcing Nophi Logging on TypingMind?

Because you install it once and use it with any model. Enforcing Nophi Logging is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Enforcing Nophi Logging in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/maziyarpanahi/openmed/tree/master/skills/enforcing-nophi-logging. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Enforcing Nophi Logging?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Enforcing Nophi Logging?

As many as you like. As long as a model supports skills, you can use Enforcing Nophi Logging with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Enforcing Nophi Logging AI skill free?

Yes. It is published on GitHub by maziyarpanahi under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇