Cloud Logging and Monitoring Queries
Intermediate12 minTrending
Query application logs, create log-based metrics, set up alerting policies, and build dashboards using gcloud CLI.
Prerequisites
- -gcloud CLI installed
- -Cloud Logging and Monitoring APIs enabled
Steps
1
Read recent logs
Fetches the 25 most recent error-level logs from Cloud Run within the last hour.
$ gcloud logging read "resource.type=cloud_run_revision AND severity>=ERROR" --limit 25 --format json --freshness 1h
2
Stream logs in real time
Streams live logs similar to 'tail -f' for quick debugging.
$ gcloud alpha logging tail "resource.type=cloud_run_revision" --format "value(textPayload)"
3
Create a log-based metric
Creates a custom metric that counts error log entries, usable in dashboards and alerts.
$ gcloud logging metrics create error_count --description "Count of error logs" --log-filter "severity>=ERROR"
4
Create an alerting policy
Triggers an alert when the error count exceeds 10 in a 5-minute window.
$ gcloud alpha monitoring policies create --notification-channels projects/my-project-id/notificationChannels/12345 --condition-display-name "High error rate" --condition-filter "metric.type=\"logging.googleapis.com/user/error_count\"" --duration 300s --if "> 10"
Set up notification channels (email, Slack, PagerDuty) first via the Console or API.
5
Export logs to Cloud Storage
Creates a log sink that exports warning and error logs to a Cloud Storage bucket for long-term retention.
$ gcloud logging sinks create my-log-sink storage.googleapis.com/my-log-bucket --log-filter "severity>=WARNING"
Full Script
FAQ
Discussion
Loading comments...