Стек мониторинга GCP
Cloud Functions → Cloud Logging → Log-based Metrics
↓
Cloud Monitoring → Alerts → Notification Channels
↓
Cloud Trace (distributed tracing)
↓
Error Reporting (автоматическое обнаружение ошибок)
Cloud Logging
Cloud Functions автоматически отправляет stdout/stderr в Cloud Logging.
Просмотр логов
# Все логи функции за последний час
gcloud logging read \
'resource.type="cloud_function" AND resource.labels.function_name="visitor-counter"' \
--limit=50 \
--format="table(timestamp, textPayload)"
# Только ошибки
gcloud logging read \
'resource.type="cloud_function" AND severity>=ERROR' \
--limit=20
# Поиск по тексту
gcloud logging read \
'resource.type="cloud_function" AND textPayload:"Visitor count"' \
--limit=10
Структурированное логирование
import json
import logging
import google.cloud.logging
# Setup Cloud Logging client
client = google.cloud.logging.Client()
client.setup_logging()
logger = logging.getLogger(__name__)
def visitor_counter(request):
# Structured log (автоматически в Cloud Logging)
logger.info('Counter incremented', extra={
'json_fields': {
'action': 'increment',
'count': count,
'source': request.headers.get('Referer', 'direct')
}
})
Log-based Metrics
Создайте метрики из логов:
# Метрика: количество успешных запросов
gcloud logging metrics create visitor-count-success \
--description="Successful visitor counter requests" \
--log-filter='resource.type="cloud_function" AND textPayload:"Visitor count"'
# Метрика: количество ошибок
gcloud logging metrics create visitor-count-errors \
--description="Visitor counter errors" \
--log-filter='resource.type="cloud_function" AND severity>=ERROR AND resource.labels.function_name="visitor-counter"'
Cloud Monitoring
Встроенные метрики Cloud Functions
| Метрика | Описание | Для CRC |
|---|---|---|
| function/execution_count | Количество выполнений | Трафик |
| function/execution_times | Время выполнения | Производительность |
| function/user_memory_bytes | Использование памяти | Оптимизация |
| function/active_instances | Активные экземпляры | Масштабирование |
| function/network_egress | Исходящий трафик | Стоимость |
Создание алертов
# Алерт: ошибки > 5 за 5 минут
gcloud alpha monitoring policies create \
--display-name="CRC Function Errors" \
--condition-display-name="High error rate" \
--condition-filter='resource.type = "cloud_function" AND metric.type = "cloudfunctions.googleapis.com/function/execution_count" AND metric.labels.status != "ok"' \
--condition-threshold-value=5 \
--condition-threshold-duration=300s \
--notification-channels=CHANNEL_ID
# Notification channel (email)
gcloud alpha monitoring channels create \
--display-name="CRC Alerts Email" \
--type=email \
[email protected]
Error Reporting
Error Reporting автоматически обнаруживает и группирует ошибки из Cloud Functions.
# Просмотр ошибок
gcloud beta error-reporting events list --limit=10
# Ошибки группируются по stack trace:
# - Количество вхождений
# - Первое и последнее появление
# - Затронутые сервисы
Настройка в Python
from google.cloud import error_reporting
error_client = error_reporting.Client()
def visitor_counter(request):
try:
count = increment_counter()
return (json.dumps({'count': count}), 200, headers)
except Exception as e:
# Автоматически отправляется в Error Reporting
error_client.report_exception()
logger.error(f'Error: {e}')
return (json.dumps({'error': 'Service unavailable'}), 503, headers)
Cloud Trace
Cloud Trace показывает распределённые трейсы: путь запроса через сервисы.
# Cloud Functions 2nd gen автоматически интегрируется с Cloud Trace
# Каждый HTTP-запрос создаёт trace span
# Для кастомных spans:
from opentelemetry import trace
tracer = trace.get_tracer(__name__)
def visitor_counter(request):
with tracer.start_as_current_span("increment_counter"):
count = increment_counter()
with tracer.start_as_current_span("build_response"):
return (json.dumps({'count': count}), 200, headers)
Dashboard
# Создание через Google Cloud Console:
# Monitoring → Dashboards → Create Dashboard
# Add Chart: Cloud Functions → Execution count (by status)
# Add Chart: Cloud Functions → Execution times (P50, P95, P99)
# Add Chart: Cloud Functions → Active instances
# Add Chart: Firestore → Read/Write operations
Сравнение мониторинга
| Параметр | AWS CloudWatch | Azure Monitor | GCP Cloud Monitoring |
|---|---|---|---|
| Логи | CloudWatch Logs | Log Analytics | Cloud Logging |
| Метрики | CloudWatch Metrics | Azure Metrics | Cloud Monitoring |
| Трейсинг | X-Ray | App Insights | Cloud Trace |
| Ошибки | -- (через CloudWatch) | App Insights | Error Reporting |
| Язык запросов | CloudWatch Insights | KQL | MQL / Log filters |
| Бесплатно | 5 GB logs, 10 metrics | 5 GB logs | 50 GB logs, 150 MB traces |