loguru icon indicating copy to clipboard operation
loguru copied to clipboard

Issue with Loguru Logging Not Printing in FastAPI Application

Open BennisonDevadoss opened this issue 9 months ago • 1 comments

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:

  1. Removed Loguru's default handlers and added a custom handler for sys.stdout with the format:
    "{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}"
    
  2. 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:

  1. Is there something wrong with my Loguru configuration?
  2. Do I need additional steps to ensure Loguru works correctly with FastAPI and Uvicorn?
  3. Are there known compatibility issues between Loguru and Uvicorn?

Any help or guidance would be appreciated!


BennisonDevadoss avatar Jan 19 '25 17:01 BennisonDevadoss

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:

Delgan avatar Jan 19 '25 17:01 Delgan