简体   繁体   English

Python FastAPI/Uvicorn - 外部记录器无法工作?

[英]Python FastAPI/Uvicorn - External logger wont work?

I am using logtail.com and for some reason it wont log ONLY in my FastAPI/UVICORN app, I tried using the package in an a different test python file and it worked?我正在使用 logtail.com 并且出于某种原因它不会仅在我的 FastAPI/UVICORN 应用程序中登录,我尝试在不同的测试 python 文件中使用 package 并且它有效吗? I dont understand what I am missing.我不明白我错过了什么。 I call the logger and it should work but it does not, additionally I even do a log INSTANTLY after I instantiate the logger and it does not work.我调用记录器,它应该可以工作,但它不工作,此外,我什至在实例化记录器后立即执行日志,但它不工作。 Code below.下面的代码。

#
# Logger.py
#

from logtail import LogtailHandler
import logging

class Logger:
    def __init__(self):
        handler = LogtailHandler(source_token="XXXXXXX")
        logger = logging.getLogger(__name__)
        logger.handlers = []
        logger.setLevel(logging.DEBUG) # Set minimal log level
        logger.addHandler(handler) # asign handler to logger
        logger.debug('I am using Logtail!')

    def info(self, message):
        self.log.info(message)
        
    def error(self, message):
        self.log.error(message)
    
    def debug(self, message):
        self.log.debug(message)
        
    def warning(self, message):
        self.log.warning(message)
        
    def critical(self, message):
        self.log.critical(message)
        
    def exception(self, message):
        self.log.exception(message)
#
# __init__ 
#

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from abe.routes import main, bc_handler

app = FastAPI(title="ABE-Backend", openapi_url="/openapi.json")
app.include_router(main.router)
app.include_router(bc_handler.router)

from abe.utils.logger import Logger

logger = Logger()

#create tables
# models.Base.metadata.create_all(bind=engine)

origins = [
    
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

if __name__ == "__main__":
    # Use this for debugging purposes only
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="debug")
    logger.info("Starting server on port 8000, with cors origins: "+str(origins))

It should work, but only after you shutdown the API.它应该可以工作,但只有在您关闭 API 之后。

Logging inside the main function before calling uvicorn.run() and inside endpoint routes should work as you expected.在调用uvicorn.run()和内部端点路由之前登录主 function 应该可以按预期工作。

uvicorn.run() is a sync function. So the interpreter waits until the function has finished (API has shutdown) and executes the following statements afterwards. uvicorn.run()是同步 function。因此解释器会一直等到 function 完成(API 已关闭),然后执行以下语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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