简体   繁体   中英

FastAPI: Exception handler not running logging as instructed

I have a basic logger set up using the logging library in Python 3.10.4. I'm attempting to make the FastAPI exception handler log any exceptions it handles, to no avail. The handler is running, as I can see that my custom Response is returned, but no log.

logging.basicConfig(filename='mylan.log')
logger = logging.getLogger("MyLAN")
logger.setLevel(logging.DEBUG)
discord_handler = DiscordHandler(webhook_url, agent, notify_users=notify_users, emit_as_code_block=False, max_size=2000)

# Add log level to handlers
discord_handler.setLevel(logging.DEBUG)

# Add format to handlers
discord_handler.setFormatter(FORMAT)

# Add the handlers to the Logger
logger.addHandler(discord_handler)

logger.debug("Logger created")

app = FastAPI()
logger.debug('test') # This works
@app.exception_handler(Exception)
def handle_exception(req, exc):
    logger.debug("Something's brokey") # This does not
    return Response("Internal Server Error Test", status_code=500)

I can also confirm that the logger works, as it logs a simple message on startup which is saved successfully.

I'm not even getting any errors in stdout that might guide me towards a solution.

Anyone have any ideas?

It works for me as written. Here's the code I tested. It's basically identical to what you have, but it's runnable, and includes a /error route that raises a KeyError to test the exception handler:

import logging
from fastapi import FastAPI, Response
from discord_handler import DiscordHandler

webhook_url = "https://discord.com/api/webhooks/..."

logging.basicConfig(filename="mylan.log")
logger = logging.getLogger("MyLAN")
logger.setLevel(logging.DEBUG)
discord_handler = DiscordHandler(
    webhook_url,
    "Example",
    notify_users=[],
    emit_as_code_block=True,
    max_size=2000,
)

# Add log level to handlers
discord_handler.setLevel(logging.DEBUG)

# Add the handlers to the Logger
logger.addHandler(discord_handler)

logger.debug("Logger created")

app = FastAPI()
logger.debug("test")  # This works


@app.exception_handler(Exception)
def handle_exception(req, exc):
    logger.debug("Something's broken")  # This does not
    return Response("Internal Server Error Test", status_code=500)


@app.get("/error")
def error():
    raise KeyError("example")

When this code starts up, I see in my discord channel:

Logger created...
test...

And when I make a request to /error , I see:

Something's broken...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM