I am Migrating my code from Python flask to Fast-API. I am facing an issue in adding loggers to fast API, It will display
"AttributeError: 'FastAPI' object has no attribute 'logger'"
Please refer the code for more info
from fastapi import FastAPI, HTTPException
import uvicorn
from logging.handlers import RotatingFileHandler
import logging
app = FastAPI()
if __name__ == '__main__':
formatter = logging.Formatter(
"[%(asctime)s.%(msecs)03d] %(levelname)s [%(thread)d] - %(message)s", "%Y-%m-%d %H:%M:%S")
handler = RotatingFileHandler('/log/abc.log', backupCount=0)
logging.getLogger().setLevel(logging.NOTSET)
app.logger.addHandler(handler)
handler.setFormatter(formatter)
app.logger.info('****************** Starting Server *****************') # "AttributeError: 'FastAPI' object has no attribute 'logger'"
uvicorn.run()
You should import the fastapi logger and then manipulate it. from fastapi.logger import logger
from fastapi import FastAPI, HTTPException
from fastapi.logger import logger as fastapi_logger
import uvicorn
from logging.handlers import RotatingFileHandler
import logging
app = FastAPI()
if __name__ == '__main__':
formatter = logging.Formatter(
"[%(asctime)s.%(msecs)03d] %(levelname)s [%(thread)d] - %(message)s", "%Y-%m-%d %H:%M:%S")
handler = RotatingFileHandler('/log/abc.log', backupCount=0)
logging.getLogger().setLevel(logging.NOTSET)
fastapi_logger.addHandler(handler)
handler.setFormatter(formatter)
fastapi_logger.info('****************** Starting Server *****************')
uvicorn.run()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With