Metadata-Version: 2.4
Name: medlink-pylib
Version: 0.0.20
Summary: py utils lib
Author-email: Jacob Jiang <mingjing@medlink.global>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/mingjingjiang/medlink-pylib
Project-URL: Issues, https://github.com/mingjingjiang/medlink-pylib/issues
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: prometheus-client<0.27,>=0.26.0
Requires-Dist: starlette>=0.52.1
Dynamic: license-file

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

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

```bash
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`:

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

```python
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.
