Spaces:
Sleeping
Sleeping
Download app/logging_utils.py from notsn/headless_scilab: direct link, hf CLI and curl.
- Browser
- Download file 1.64 kB
-
https://huggingface.co/spaces/notsn/headless_scilab/resolve/main/app/logging_utils.py
- Command line
-
hf download hf://spaces/notsn/headless_scilab/app/logging_utils.py
-
curl -L -o logging_utils.py https://huggingface.co/spaces/notsn/headless_scilab/resolve/main/app/logging_utils.py
1.64 kB
| from __future__ import annotations | |
| from contextlib import contextmanager | |
| from contextvars import ContextVar | |
| from datetime import datetime, timezone | |
| import json | |
| import logging | |
| import sys | |
| from typing import Any | |
| _correlation_id: ContextVar[str] = ContextVar("correlation_id", default="-") | |
| class JsonFormatter(logging.Formatter): | |
| def format(self, record: logging.LogRecord) -> str: | |
| base: dict[str, Any] = { | |
| "ts": datetime.now(timezone.utc).isoformat(), | |
| "level": record.levelname, | |
| "logger": record.name, | |
| "message": record.getMessage(), | |
| "correlation_id": _correlation_id.get(), | |
| "service": getattr(record, "service", None), | |
| } | |
| if record.exc_info: | |
| base["exception"] = self.formatException(record.exc_info) | |
| extra_fields = getattr(record, "extra_fields", None) | |
| if isinstance(extra_fields, dict): | |
| base.update(extra_fields) | |
| return json.dumps(base, ensure_ascii=False) | |
| def configure_logging(level: str) -> None: | |
| root = logging.getLogger() | |
| root.setLevel(level) | |
| root.handlers.clear() | |
| handler = logging.StreamHandler(sys.stdout) | |
| handler.setFormatter(JsonFormatter()) | |
| root.addHandler(handler) | |
| def set_correlation_id(value: str): | |
| return _correlation_id.set(value) | |
| def reset_correlation_id(token) -> None: | |
| _correlation_id.reset(token) | |
| def correlation_scope(value: str): | |
| token = set_correlation_id(value) | |
| try: | |
| yield | |
| finally: | |
| reset_correlation_id(token) | |
| def get_correlation_id() -> str: | |
| return _correlation_id.get() | |