-
-
Save BlackHacked/18375ad01352c6937a93d31cc56a2ad5 to your computer and use it in GitHub Desktop.
From: Dima
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment