RWKV-Runner/backend-python/utils/log.py

50 lines
1.4 KiB
Python
Raw Permalink Normal View History

2023-06-03 17:12:59 +08:00
import json
import logging
from typing import Any
from fastapi import Request
2023-08-04 22:27:55 +08:00
from pydantic import BaseModel
from enum import Enum
2023-06-03 17:12:59 +08:00
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(levelname)s\n%(message)s")
fh = logging.handlers.RotatingFileHandler(
2023-11-05 21:00:31 +08:00
"api.log", mode="a", maxBytes=3 * 1024 * 1024, backupCount=3, encoding="utf-8"
2023-06-03 17:12:59 +08:00
)
fh.setFormatter(formatter)
logger.addHandler(fh)
2023-08-04 22:27:55 +08:00
class ClsEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, BaseModel):
return obj.dict()
if isinstance(obj, Enum):
return obj.value
return super().default(obj)
2023-06-03 17:12:59 +08:00
def quick_log(request: Request, body: Any, response: str):
2023-06-13 22:47:17 +08:00
try:
logger.info(
f"Client: {request.client if request else ''}\nUrl: {request.url if request else ''}\n"
+ (
2023-08-04 22:27:55 +08:00
f"Body: {json.dumps(body.__dict__, ensure_ascii=False, cls=ClsEncoder)}\n"
2023-06-13 22:47:17 +08:00
if body
else ""
)
+ (f"Data:\n{response}\n" if response else "")
2023-06-03 17:12:59 +08:00
)
2023-06-13 22:47:17 +08:00
except Exception as e:
logger.info(f"Error quick_log request:\n{e}")
2023-06-03 17:12:59 +08:00
async def log_middleware(request: Request):
2023-06-13 22:47:17 +08:00
try:
logger.info(
f"Client: {request.client}\nUrl: {request.url}\nBody: {await request.body()}\n"
)
except Exception as e:
logger.info(f"Error log_middleware request:\n{e}")