import logging

import gunicorn.app.base
from fastapi import FastAPI
from loguru import logger


class InterceptHandler(logging.StreamHandler):
    def emit(self, record):
        # Get corresponding Loguru level if it exists
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = record.levelno

        # Find caller from where originated the logged message
        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename == logging.__file__:
            frame = frame.f_back
            depth += 1

        logger.opt(depth=depth, exception=record.exc_info).log(
            level, record.getMessage()
        )


GUNICORN_CONFIG = dict(
    handlers={
        "console": {
            "class": "__main__.InterceptHandler",
        },
        "error_console": {
            "class": "__main__.InterceptHandler",
        },
    }
)


class GunicornApplication(gunicorn.app.base.BaseApplication):

    def __init__(self, app, options=None):
        self.options = options or {}
        self.application = app
        super().__init__()

    def load_config(self):
        config = {key: value for key, value in self.options.items()
                  if key in self.cfg.settings and value is not None}
        for key, value in config.items():
            self.cfg.set(key.lower(), value)

    def load(self):
        return self.application


options = {
    "bind": "localhost:8080",
    "loglevel": "info",
    "worker_class": "uvicorn.workers.UvicornWorker",
    "logconfig_dict": GUNICORN_CONFIG
}
GunicornApplication(FastAPI(), options=options).run()
