Metadata-Version: 2.4
Name: medlink-pylib
Version: 0.0.17
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.22.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` is independent of `HttpRequestLoggingMiddleware`: it records the
`medlink_http_request_duration_seconds` histogram but does not write logs or add business routes to
the metrics listener. Install both when an application needs both behaviors:

```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")
```

`start_http_metrics_server()` listens on the dedicated port `9000` by default and serves
Prometheus exposition only at `GET /metrics`; a non-metrics path returns an empty `404`. The
caller declares that TCP container port for scraping and closes the returned handle in the app's
lifespan. The middleware preserves the established labels: `route` is the Starlette route template
(or `/__unmatched__`), `method` is a standard HTTP method or `OTHER`, `status_class` is `1xx` through
`9xx`, `service` defaults from `MEDLINK_SERVICE_ID`/`SERVICE_ID`/`SERVICE_NAME`, `service_tier`
defaults to `api`, and `environment` comes from `APP_ENV` (`production` is normalized to `prod`).
Paths, query strings, request bodies, and entity identifiers are not metric labels. Successful
health probes and the `/metrics` scrape itself are excluded; failed probes are recorded. Buckets
include the internal API alert thresholds through 15 seconds.

For multi-process apps, set `PROMETHEUS_MULTIPROC_DIR` in the parent environment before Python
imports this module or starts workers. It must be writable and shared only by workers in one pod;
mount a per-pod `emptyDir` so replacement pods start clean. Do not clear the directory from an
individual worker. If it is absent when the scrape is requested, the listener returns `503` rather
than exposing incomplete worker-local samples. Single-process apps should set the same directory
so all consumers follow one predictable setup path.

The API is Starlette-ASGI based and does not require importing FastAPI in the library. Other
FastAPI services can adopt it with the same two registrations and their own lifespan-managed
listener; their business port remains independent of the scrape port. The package requires Python
`>=3.10`, matching its Starlette runtime dependency.

Version `0.0.17` is the intended release containing this API; consumers should update their minimum
dependency only after the package is available from PyPI.

# 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)
```
