Skip to main content

EmergencyLogging

A Python logging handler that stays silent during normal operation and only writes logs when something goes wrong.

The problem

Verbose debug logging helps diagnose issues, but writing every DEBUG and INFO message to a file or console creates noise that obscures what matters. The usual workaround — raising the log level to WARNING — means you lose the context that would have explained why the warning happened.

How it works

EmergencyHandler wraps any standard logging.Handler. It buffers DEBUG and INFO records silently. The moment a WARNING, ERROR, or CRITICAL is emitted, it flushes the buffered context followed by the triggering message — then clears the buffer and starts over.

Normal operation:        DEBUG INFO DEBUG INFO DEBUG INFO  →  (nothing written)
Something goes wrong:    DEBUG INFO DEBUG INFO ERROR       →  DEBUG INFO DEBUG INFO ERROR

The buffer holds the most recent N records (default 30). Older records are dropped as new ones arrive, so the buffer always contains the last N lines of context leading up to the problem.

Installation

pip install emergency-logging

Manual

No dependencies outside the standard library. Copy emergency_logging.py directly into your project.

Requires Python 3.8+.

Usage

Basic — wrap the default stderr handler

import logging
from emergency_logging import EmergencyHandler

logger = logging.getLogger("myapp")
logger.setLevel(logging.DEBUG)
logger.addHandler(EmergencyHandler())

logger.debug("connecting to database")   # buffered
logger.info("query executed in 4 ms")    # buffered
logger.error("connection pool exhausted") # flushes both lines above, then this

With a custom handler and buffer size

import logging
from emergency_logging import EmergencyHandler

stream = logging.StreamHandler()
stream.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))

logger = logging.getLogger("myapp")
logger.setLevel(logging.DEBUG)
logger.addHandler(EmergencyHandler(target_handler=stream, buffer_size=50))

With RotatingFileHandler

The log file stays empty during normal operation and only grows when an incident occurs — keeping file sizes minimal while preserving full diagnostic context when you need it.

import logging
from logging.handlers import RotatingFileHandler
from emergency_logging import EmergencyHandler

rotating = RotatingFileHandler("app.log", maxBytes=1024 * 1024, backupCount=5)
rotating.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(name)s: %(message)s"))

logger = logging.getLogger("myapp")
logger.setLevel(logging.DEBUG)
logger.addHandler(EmergencyHandler(target_handler=rotating, buffer_size=30))

API

EmergencyHandler(target_handler=None, buffer_size=30)

Parameter Type Default Description
target_handler logging.Handler StreamHandler() The handler that receives flushed records
buffer_size int 30 Maximum number of DEBUG/INFO records to buffer; oldest are dropped when exceeded

The handler passes through WARNING, ERROR, and CRITICAL records immediately (after flushing the buffer). DEBUG and INFO records are only ever written as part of a flush.

Comparison to MemoryHandler

Python's standard library includes logging.handlers.MemoryHandler, which is the closest built-in equivalent. Here's how they differ:

MemoryHandler EmergencyHandler
Flush trigger ERROR (default) or buffer full WARNING (default)
Buffer full behaviour Flushes the entire buffer immediately Drops the oldest record, keeps the newest N
After a flush Buffer cleared Buffer cleared
Most recent context guaranteed No — a busy logger flushes everything on capacity Yes — you always get the last N lines before the incident

The practical difference: MemoryHandler doesn't miss anything in the log. EmergencyHandler behaves like a ring buffer — it silently discards unimportant records that are too old to matter and always preserves the most recent context window.

Use a regular handler for full bookkeeping and an EmergencyHandler for focused incident output. The regular handler captures everything for audit trails or offline analysis; the EmergencyHandler surfaces only what's relevant when something goes wrong.

import logging
from logging.handlers import RotatingFileHandler
from emergency_logging import EmergencyHandler

logger = logging.getLogger("myapp")
logger.setLevel(logging.DEBUG)

# Full audit log — every record, always
audit = RotatingFileHandler("audit.log", maxBytes=10 * 1024 * 1024, backupCount=5)
audit.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s"))
logger.addHandler(audit)

# Incident log — only emits when WARNING or above fires, with recent context
incident = RotatingFileHandler("incidents.log", maxBytes=1024 * 1024, backupCount=3)
incident.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s"))
logger.addHandler(EmergencyHandler(target_handler=incident, buffer_size=30))

audit.log grows continuously and is the source of truth. incidents.log stays small and contains only the context windows around each problem — easy to tail in production or attach to a bug report.

Running the demos

python3 demo.py

Running the tests

python3 -m unittest test_emergency_logging -v

Metadata

Release files for emergency-logging 0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for emergency-logging 0.2
File Size Uploaded Provenance Actions
emergency_logging-0.2.tar.gz 4.4 kB Without provenance Details for emergency_logging-0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for emergency-logging 0.2
File Interpreter ABI Platform Actions
emergency_logging-0.2-py3-none-any.whl Python 3 none any Details for emergency_logging-0.2-py3-none-any.whl

Total release size: 9.2 kB

Release files / emergency_logging-0.2.tar.gz

Download URL emergency_logging-0.2.tar.gz
Size 4.4 kB
Tags Source
SHA-256 checksum
How to use checksums
9a016036910b84d0aa81c9fa236281669f0d46e2348b2a3e80045d61f878f673
BLAKE2b-256 checksum
How to use checksums
843f03ecab5d41168851ebfac8189c128ca4ea9acc7e36a566cb234f4fc8e061
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release files / emergency_logging-0.2-py3-none-any.whl

Download URL emergency_logging-0.2-py3-none-any.whl
Size 4.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
90b2259112ed0bb04f6851d0c36315a57573e9de10779085c05f091a2225b96a
BLAKE2b-256 checksum
How to use checksums
b3a1ed45b8013b2d050d09736ea6548d5cba5d53485c2dfde2b63104d0801b74
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Security for emergency-logging 0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page