pylib Package
This is a py utils lib package, here are log and lots of methods. All methods you can see in file methods.py.
HTTP request metrics
HttpRequestMetricsMiddleware records the medlink_http_request_duration_seconds histogram
independently of HttpRequestLoggingMiddleware. Install each middleware separately, and start the
metrics-only listener from the application's lifespan:
from contextlib import asynccontextmanager
from fastapi import FastAPI
from pylib.gcp_logging import HttpRequestLoggingMiddleware
from pylib.http_metrics import HttpRequestMetricsMiddleware, start_http_metrics_server
@asynccontextmanager
async def lifespan(app: FastAPI):
metrics_server = start_http_metrics_server()
try:
yield
finally:
metrics_server.close()
app = FastAPI(lifespan=lifespan)
app.add_middleware(HttpRequestLoggingMiddleware)
app.add_middleware(HttpRequestMetricsMiddleware, service_tier="api")
The listener uses TCP port 9000 by default and serves only GET /metrics; application traffic,
Services, and probes can remain on port 8080. If PROMETHEUS_MULTIPROC_DIR is unset or empty,
importing pylib sets it to <system-temp>/medlink-pylib-prometheus and creates that directory.
An explicit value is preserved and its directory is created if needed. Import pylib before
importing prometheus_client or constructing Prometheus metrics; if the Prometheus client is
initialized first, set the variable externally before process startup. The default directory is
shared and is not cleared automatically, so stale metrics can remain between runs. For production,
set a writable per-pod emptyDir shared by that pod's workers and clear it once before starting the
process group; do not clear it while workers are active.
The scrape also includes the Prometheus Python client's default GC and runtime collectors, plus
process metrics on Linux. The default python_gc_* and process_* series describe the worker
serving that scrape; they are not aggregated across workers. Pylib registers a GC callback in each
worker and additionally emits
medlink_python_gc_collections_total, medlink_python_gc_objects_collected_total, and
medlink_python_gc_objects_uncollectable_total. These counters are updated by each worker's GC
stop callback and aggregated through the shared multiprocess directory, with generation,
service, and environment labels. Application-defined metrics use the medlink_ prefix, as in
medlink_http_request_duration_seconds.
Local FastAPI middleware harness
examples/fastapi_middleware_demo.py starts a small FastAPI app with both middleware and the
separate metrics listener. It uses uv script metadata for FastAPI, Uvicorn, Starlette, and
prometheus-client; uv must be installed. Run it from the repository root so it imports this
checkout's src/pylib:
PYTHONPATH=src uv run examples/fastapi_middleware_demo.py
The demo currently runs with three Uvicorn workers at 127.0.0.1:8080; request GET /test to
exercise the middleware. To compare two workers, change workers=3 to workers=2 in the demo's
main() function. The harness listens for Prometheus metrics separately at
http://127.0.0.1:9000/metrics. Stop the process with Ctrl-C; each worker closes its metrics
listener during FastAPI lifespan shutdown.
Labels use the Starlette route template (or /__unmatched__), a standard method or OTHER, status
class, service identity from MEDLINK_SERVICE_ID/SERVICE_ID/SERVICE_NAME, service_tier, and
APP_ENV (production normalizes to prod). Successful health probes and /metrics scrapes are
excluded; raw paths, query strings, request bodies, and identifiers are never label values. The
module uses Starlette ASGI types and the package requires Python >=3.10.
The request histogram does not retain individual observations: with fixed labels, request volume
updates existing counters. Each unique label combination creates a retained histogram child with 18
finite buckets, +Inf, sum, and count. Keep route templates and deployment-controlled service,
tier, and environment values bounded; high label cardinality increases per-worker heap and
multiprocess-file storage. Scrapes read and merge those files and build an exposition response in
memory, so a large series set and concurrent scrapes can increase temporary memory use. The
multiprocess directory is not automatically cleaned: stale counter and histogram files persist
across worker restarts in a persistent directory. Clear it once before starting the worker group,
never while workers are active.
Development environment and LSP
The project does not create or select a development environment or declare test-only dependencies.
Install pytest, anyio, and the package runtime dependencies in the Python environment you manage,
then configure your editor and Basedpyright to use that same interpreter. For the local Conda
environment named medlink-pylib:
conda activate medlink-pylib
PYTHONPATH=src python -m pytest -q
If the editor reports unresolved imports after selecting or updating the environment, restart its Python language server.
Usage
from pylib.log import log
log.debug('msg')
log.info('msg')
log.warning('msg')
log.error('msg')
log.critical('msg')
log.log('DEBUG', 'msg')
log.log('INFO', 'msg')
log.log('WARNING', 'msg')
log.log('ERROR', 'msg')
log.log('CRITICAL', 'msg', silence=True)
from pylib.methods import Methods
Methods.get_stack_funcs()
data_desensitived = Methods.mask_sensitive_data(dict_data)
Worker services can use the standard logging API with a logger name inferred from the calling module:
from pylib import logger
logger.info("worker_started")
Importing pylib.logger initializes GCP worker logging once for the current process. configure_worker_logging() remains available for explicit setup; repeated calls in the same process are ignored, while a forked child configures independently.
Metadata
Release files for medlink-pylib 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| medlink_pylib-0.1.0.tar.gz | 37.0 kB | Without provenance | Details for medlink_pylib-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| medlink_pylib-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for medlink_pylib-0.1.0-py3-none-any.whl |
Total release size: 68.8 kB
Release files / medlink_pylib-0.1.0.tar.gz
| Download URL | medlink_pylib-0.1.0.tar.gz |
|---|---|
| Size | 37.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a365e4996730157800238fc91bb5b97fc352f76d34241f44f7d429b2c506014f
|
|
BLAKE2b-256 checksum How to use checksums |
66e1feb7cb84290fb2c839a19ec62e2fb7490697337daca3372c0f61408bbca5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.15
|
Release files / medlink_pylib-0.1.0-py3-none-any.whl
| Download URL | medlink_pylib-0.1.0-py3-none-any.whl |
|---|---|
| Size | 31.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
70463b9b59bef1c61f15041d87f35211cdce70b88e16bebae32552162d9da472
|
|
BLAKE2b-256 checksum How to use checksums |
9ebc8ec635a8b4db832d8661494544edbfd6a35269ebc4bd3820f13ae357f55a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.15
|
Security for medlink-pylib 0.1.0
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.