Open yuanjie-ai opened 1 year ago
You'll need to use InterceptHandler
as in README.md to propagate any other logger message through loguru sink.
Sample of my configuration (uvicorn/django-ninja)
class InterceptHandler(logging.Handler):
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 = sys._getframe(6), 6
while frame and 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())
logger.remove() # Will remove all handlers already configured
# Line below will attach a new handler (InterceptHandler) which catches messages (starting from "WARNING" level) by any other package logger
# and map it to loguru level. It'll also properly set tracebacks etc.
logging.basicConfig(handlers=[InterceptHandler()], level="WARNING", force=True)
# This line is adding default loguru handler which sends messages to sink
logger.add(sys.stdout)
The title of this ticket exactly matches this blog post Unify Python logging for a Gunicorn/Uvicorn/FastAPI application.
Please provide more details regarding the difficulties you're experiencing and the questions that this article was unable to address.
@yuanjie-ai Can this be closed?
how to Unify Python logging(loguru) for a Gunicorn/Uvicorn/FastAPI application?