loguru
loguru copied to clipboard
Issue with Loguru Logging Not Printing in FastAPI Application
I am facing an issue where Loguru is not printing logs in my FastAPI application when running the app with Uvicorn. I've configured Loguru for logging, but no logs appear in the console.
Here’s what I’ve tried so far:
- Removed Loguru's default handlers and added a custom handler for
sys.stdoutwith the format:"{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}" - Ensured that Loguru is properly configured before initializing the FastAPI app.
Code Example:
Here’s a simplified version of my setup:
from fastapi import FastAPI
from loguru import logger
import uvicorn
def configure_logging():
logger.remove()
logger.add("sys.stdout", format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}", level="INFO")
configure_logging()
app = FastAPI()
@app.get("/")
async def read_root():
logger.info("This is an info log")
return {"message": "Hello, world"}
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)
Expected Behavior:
Log messages should appear in the console when I access the / endpoint or start the FastAPI app.
Actual Behavior:
No logs are printed to the console.
Questions:
- Is there something wrong with my Loguru configuration?
- Do I need additional steps to ensure Loguru works correctly with FastAPI and Uvicorn?
- Are there known compatibility issues between Loguru and Uvicorn?
Any help or guidance would be appreciated!
Hi.
It appears there is a small oversight in your code: you're using "sys.stdout" as a str (note the surrounding quotes), instead you should pass the sys.stdout stream-object directly:
import sys
logger.add(sys.stdout, format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}", level="INFO")
Note also that many web frameworks, such as Guvicorn, are implemented in such a way as to manage endpoints in one or more “workers” that are executed in child processes. This can cause unexpected behavior, because Loguru will not be able to synchronize logs by default (since different processes don't have shared memory).
I'd also advise you to take a look at these sections of the documentation: