Da die Abrechnung auf Elementen basiert, reicht es nicht aus, die HTTP-Anfragen zu zählen. Ich verwende den google.cloud.monitoring_v3-Client.
Derzeit filtere ich nach serviceruntime.googleapis.com/api/request_count. Dies gibt die Anzahl der API-Aufrufe zurück, nicht jedoch die Anzahl der verarbeiteten Elemente. Gibt es einen bestimmten metric.type-Filter, um die Elementanzahl zurückzugeben?
Dies ist mein aktueller Code:
Code: Select all
from google.cloud import monitoring_v3
from google.oauth2 import service_account
import datetime
credentials = service_account.Credentials.from_service_account_file(GCP_MONITOR_KEY)
client = monitoring_v3.MetricServiceClient(credentials=credentials)
project_name = f"projects/{GCP_PROJECT_ID}"
now = datetime.datetime.now()
start_of_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
interval = monitoring_v3.TimeInterval({
"end_time": {"seconds": int(now.timestamp())},
"start_time": {"seconds": int(start_of_month.timestamp())}
})
# Query Distance Matrix API usage
print("Fetching Distance Matrix API usage...")
results = client.list_time_series(
request={
"name": project_name,
"filter": 'metric.type="serviceruntime.googleapis.com/api/request_count"',
"interval": interval,
"view": monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL
}
)
# Calculate total elements used
total_elements = 0
for result in results:
for point in result.points:
total_elements += point.value.int64_value
# Display results
print(f"\n Distance Matrix API Usage (Current Month)")
print(f"=" * 50)
print(f"Total elements used: {total_elements:,}")
print(f"Free tier limit: 10,000")
print(f"Remaining free: {max(0, 10000 - total_elements):,}")
if total_elements > 10000:
billable = total_elements - 10000
cost = (billable / 1000) * 10.00 # $10 per 1000 for Advanced tier
print(f"\n Estimated cost: ${cost:.2f}")
else:
print(f"\n Still within free tier!")
percent_used = (total_elements / 10000) * 100
print(f" ({percent_used:.1f}% of free tier used)")
Full version