Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'FastAPI' object has no attribute 'logger'

Tags:

python

fastapi

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()
like image 457
Srinivas H S Avatar asked Jan 16 '20 05:01

Srinivas H S


1 Answers

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()
like image 83
Finch_Powers Avatar answered Nov 06 '22 13:11

Finch_Powers