add api.log&errorlog->db

This commit is contained in:
2023-11-19 13:24:29 +09:00
parent 991c8e8083
commit a464297511
5 changed files with 61 additions and 3 deletions

View File

@@ -0,0 +1,17 @@
from app.db.schemas import ErrorCreate
from app.db.session import SessionLocal
from app.db.crud import create_log
class APIException(Exception):
def __init__(self,location:str,title:str,content:str):
if(len(content) > 5000):
content =content[0:5000]
self.error = ErrorCreate(location=location,title=title,content=content)
def writedblog(exc: APIException):
db = SessionLocal()
try:
create_log(db,exc.error)
finally:
db.close()

View File

@@ -283,3 +283,11 @@ def get_eventactions(db: Session,eventid: str):
if not eveactions: if not eveactions:
raise HTTPException(status_code=404, detail="Data not found") raise HTTPException(status_code=404, detail="Data not found")
return eveactions return eveactions
def create_log(db: Session, error:schemas.ErrorCreate):
db_log = models.ErrorLog(location=error.location,title=error.title,content=error.content)
db.add(db_log)
db.commit()
db.refresh(db_log)
return db_log

View File

@@ -91,3 +91,11 @@ class EventAction(Base):
eventid = Column(Integer,ForeignKey("event.id")) eventid = Column(Integer,ForeignKey("event.id"))
actionid = Column(Integer,ForeignKey("action.id")) actionid = Column(Integer,ForeignKey("action.id"))
class ErrorLog(Base):
__tablename__ = "errorlog"
id = Column(Integer, primary_key=True, index=True)
location = Column(String(200))
title = Column(String(50))
content = Column(String(5000))

View File

@@ -140,3 +140,8 @@ class Event(Base):
class Config: class Config:
orm_mode = True orm_mode = True
class ErrorCreate(BaseModel):
location:str
title:str
content:str

View File

@@ -11,6 +11,11 @@ from app.core.auth import get_current_active_user
from app.core.celery_app import celery_app from app.core.celery_app import celery_app
from app import tasks from app import tasks
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
import logging
from app.core.apiexception import APIException, writedblog
from app.db.crud import create_log
from fastapi.responses import JSONResponse
import asyncio
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
@@ -37,6 +42,21 @@ app.add_middleware(
# request.state.db.close() # request.state.db.close()
# return response # return response
@app.on_event("startup")
async def startup_event():
logger = logging.getLogger("uvicorn.access")
handler = logging.handlers.RotatingFileHandler("Log/api.log",mode="a",maxBytes = 100*1024, backupCount = 3)
handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
logger.addHandler(handler)
@app.exception_handler(APIException)
async def api_exception_handler(request: Request, exc: APIException):
loop = asyncio.get_event_loop()
loop.run_in_executor(None,writedblog,exc)
return JSONResponse(
status_code=400,
content={"detail": f"{exc.error.content}"},
)
@app.get("/api/v1") @app.get("/api/v1")
async def root(): async def root():