#  Copyright (C) 2023
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Vasya Svintsov <v.svintsov@techokert.ru>

import logging
import os

from typing import Optional

from http_tools.request_tracing import CONTEXT_VAR_REQUEST_ID


class RequestTracingFormatter(logging.Formatter):
    def __init__(self, fmt: Optional[str] = None, *args, **kwargs) -> None:
        if fmt is None:
            fmt = '<%(asctime)s/%(name)s:%(lineno)s/%(request_id)s/%(levelname)s>-  %(message)s'
        super().__init__(fmt, *args, **kwargs)

    def format(self, record: logging.LogRecord) -> str:
        record.name = f'{os.getpid()}/{record.name.rsplit(".")[0].rsplit("/")[-1]}'
        record.request_id = f'request_id:{req_id if (req_id := CONTEXT_VAR_REQUEST_ID.get()) else None}'
        return super().format(record)
