Мониторинг, журналирование и наблюдаемость
Поддерживайте рабочий сервер Supabase в стабильном состоянии: анализируйте журналы, отслеживайте ключевые показатели, добавляйте инструментирование в Edge Functions и настраивайте оповещения до того, как небольшие проблемы приведут к сбоям.
«Мониторинг, журналирование и наблюдаемость» — бесплатный урок Supabase Backend as a Service на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Supabase Backend as a Service, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Supabase Backend as a Service содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Observability Matters
Deploying is only half the job. Once your backend serves real traffic you need to see what it is doing. Observability is the practice of understanding system state from its outputs.
- Logs tell you what happened
- Metrics tell you how much and how fast
- Traces tell you where time was spent
The Supabase Logs Explorer
Supabase exposes logs for every service in the dashboard under Logs: API gateway, Postgres, Auth, Storage, and Edge Functions. Each is queryable with SQL-like syntax.
Filtering by status code and path quickly surfaces failing requests.
Querying Logs
The Logs Explorer accepts SQL over structured log events. Here we count API errors grouped by path over the last hour.
select path, count(*) as errors
from edge_logs
where status_code >= 500
group by path
order by errors desc;Structured Logging in Edge Functions
Inside Edge Functions, prefer structured JSON logs over plain strings. They are far easier to filter and aggregate later.
console.log(JSON.stringify({
level: 'info',
event: 'order_created',
orderId: order.id,
userId: user.id,
durationMs: Date.now() - start
}));Log Levels
Use consistent levels so you can filter noise from signal.
debugfor development detailinfofor normal eventswarnfor recoverable problemserrorfor failures needing attention
In production, avoid logging at debug to control cost and volume.
Key Database Metrics
Watch a handful of Postgres metrics closely:
- Active connections vs the pool limit
- Cache hit ratio (aim above 99%)
- Slow query count
- Disk and CPU usage
Supabase surfaces these on the Reports page.
Finding Slow Queries
Enable pg_stat_statements to see which queries consume the most total time. This is the single most useful tool for performance triage.
select query, calls, mean_exec_time, total_exec_time
from pg_stat_statements
order by total_exec_time desc
limit 10;Never Log Secrets
Logs are persisted and often shared. Never write passwords, tokens, full card numbers, or service-role keys into logs.
- Redact sensitive fields before logging
- Log identifiers, not raw payloads
- Treat log access as a security boundary
Correlating Requests
Attach a request ID to every log line in a function so you can reconstruct a single request's full journey across logs.
const requestId = crypto.randomUUID();
console.log(JSON.stringify({ requestId, event: 'start' }));
// ... work ...
console.log(JSON.stringify({ requestId, event: 'done' }));Alerting
Logs you never look at help no one. Set up alerts for the conditions that matter: error-rate spikes, connection exhaustion, disk nearing capacity.
Forward logs to an external sink (e.g. via webhooks or a log drain) when you need richer alerting than the dashboard provides.
Retention and Cost
Logs cost money and storage. Decide a retention policy deliberately.
- Keep high-value audit logs longer
- Sample or drop chatty debug logs
- Archive to cheap storage before deletion if needed for compliance
Quick Check
Test your observability knowledge.
Recap
You now have a foundation for production observability.
- Use the Logs Explorer and structured JSON logs
- Apply consistent log levels and request IDs
- Track connections, cache hit ratio, and slow queries
- Use
pg_stat_statementsfor performance triage - Never log secrets; set alerts and a retention policy
Часто задаваемые вопросы
Урок «Мониторинг, журналирование и наблюдаемость» бесплатный?
Да — полный текст урока «Мониторинг, журналирование и наблюдаемость» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Supabase Backend as a Service, подпишись на CoddyKit PRO. Курс Supabase Backend as a Service содержит 4 уроков всего.
Чему я научусь в уроке «Мониторинг, журналирование и наблюдаемость»?
Поддерживайте рабочий сервер Supabase в стабильном состоянии: анализируйте журналы, отслеживайте ключевые показатели, добавляйте инструментирование в Edge Functions и настраивайте оповещения до того,… Ты практикуешь Supabase Backend as a Service с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Supabase Backend as a Service?
Предыдущий опыт не требуется. Supabase Backend as a Service на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Мониторинг, журналирование и наблюдаемость»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Supabase Backend as a Service?
Да. Каждый урок Supabase Backend as a Service включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Управление окружениями и CI/CD
- Резервное копирование, восстановление и аварийное восстановление
- Аудит безопасности и лучшие практики
- Мониторинг, журналирование и наблюдаемость