perf: cache log

This commit is contained in:
fit2cloud-chenyw
2025-07-18 11:12:12 +08:00
parent a790ee3c84
commit bf5c0af9d0
+10 -3
View File
@@ -1,13 +1,12 @@
import logging
from fastapi_cache import FastAPICache
from fastapi_cache.decorator import cache as original_cache
from functools import partial, wraps
from typing import Optional, Set, Any, Dict, Tuple, Callable
from inspect import Parameter, signature
import logging
from contextlib import asynccontextmanager
import asyncio
logger = logging.getLogger(__name__)
# 锁管理
_cache_locks = {}
@@ -66,7 +65,7 @@ def custom_key_builder(
base_key += f"{value}:"
except (IndexError, KeyError, AttributeError) as e:
logger.warning(f"Failed to evaluate keyExpression '{keyExpression}': {str(e)}")
logging.warning(f"Failed to evaluate keyExpression '{keyExpression}': {str(e)}")
return base_key
@@ -128,13 +127,19 @@ def cache(
)
async with _get_cache_lock(cache_key):
logging.info(f"Using cache key: {cache_key}")
print(f"Using cache key: {cache_key}")
backend = FastAPICache.get_backend()
cached_value = await backend.get(cache_key)
if cached_value is not None:
logging.info(f"Cache hit for key: {cache_key}, the value is: {cached_value}")
print(f"Cache hit for key: {cache_key}, the value is: {cached_value}")
return cached_value
result = await func(*args, **kwargs)
await backend.set(cache_key, result, expire)
logging.info(f"Cache miss for key: {cache_key}, result cached.")
print(f"Cache miss for key: {cache_key}, result cached.")
return result
return wrapper
@@ -161,6 +166,8 @@ def clear_cache(
async with _get_cache_lock(cache_key):
await FastAPICache.clear(key=cache_key)
result = await func(*args, **kwargs)
logging.info(f"Clearing cache for key: {cache_key}")
print(f"Clearing cache for key: {cache_key}")
return result
return wrapper