arrow_back

Creating and Alerting on Logs-based Metrics

Join Sign in

Creating and Alerting on Logs-based Metrics

1 hour 30 minutes 1 Credit

GSP091

Google Cloud Self-Paced Labs

Overview

Log-based metrics are Cloud Monitoring metrics that are based on the content of log entries. These metrics can help you identify trends, extract numeric values out of the logs, and set up an alert when a certain log entry occurs by creating a metric for that event. You can use both system and user-defined log-based metrics in Cloud Monitoring to create charts and alerting policies.google

The log-based metrics interface is divided into two metric-type panes: System metrics and User-defined metrics.

System-defined log-based metrics are provided by Cloud Logging for use by all Google Cloud projects.They calculated only from logs that have been ingested by Logging. If a log has been explicitly excluded from ingestion, it isn't included in these metrics.

User-defined log-based metrics are created by you to track things in your Google Cloud project. For example, you might create a log-based metric to count the number of log entries that match a given filter.

Creating an alert from a metric lets you create an alerting policy based on the log-based metric.

In this lab you will learn how to:

  • Create a log-based alert

  • Create a system-defined log-based metric

  • Create a user-defined log-based metric

  • Create an alert for the user-defined log-based metric

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

What you need

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
  • Time to complete the lab.

Note: If you already have your own personal Google Cloud account or project, do not use it for this lab.

Note: If you are using a Chrome OS device, open an Incognito window to run this lab.

How to start your lab and sign in to the Google Cloud Console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is a panel populated with the temporary credentials that you must use for this lab.

    Open Google Console

  2. Copy the username, and then click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.

    Sign in

    Tip: Open the tabs in separate windows, side-by-side.

  3. In the Sign in page, paste the username that you copied from the left panel. Then copy and paste the password.

    Important: You must use the credentials from the left panel. Do not use your Google Cloud Training credentials. If you have your own Google Cloud account, do not use it for this lab (avoids incurring charges).

  4. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Cloud Console opens in this tab.

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

In the Cloud Console, in the top right toolbar, click the Activate Cloud Shell button.

Cloud Shell icon

Click Continue.

cloudshell_continue.png

It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example:

Cloud Shell Terminal

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

You can list the active account name with this command:

gcloud auth list

(Output)

ACTIVE: * ACCOUNT: student-01-xxxxxxxxxxxx@qwiklabs.net To set the active account, run: $ gcloud config set account `ACCOUNT`

You can list the project ID with this command:

gcloud config list project

(Output)

[core] project = <project_ID>

(Example output)

[core] project = qwiklabs-gcp-44776a13dea667a6

A virtual machine was created when this lab started. Make sure you see the green Lab Running light on the page where you started the lab before continuing.

Additionally, connect to a Google Kubernetes Engine cluster and validate that it's been created correctly.

  1. Set the zone in gcloud:

gcloud config set compute/zone us-west1-b
  1. Then Authorize Cloud Shell.

  2. Set the project ID:

export PROJECT_ID=$(gcloud info --format='value(config.project)')
  1. Deploy a standard GKE cluster, which will prompt you to authorize and enable the GKE API.

gcloud container clusters create gmp-cluster --num-nodes=1 --zone us-west1-b

Click Check my progress to verify the objective. Deploy the GKE cluster

Task 1. Log-based alert

Log-based alerts notify you whenever a specific message appears in your logs. Try it out by setting up a log-based alert to tell you when a VM stops running.

  1. From Cloud Console, in the Search bar, type in “logs explorer”, then click on the Logs Explorer result.

  2. Click the Show Query slide bar.

  3. Enter the following parameters to create Log Based Alert:

resource.type="gce_instance" protoPayload.methodName="v1.compute.instances.stop"
  1. Click Create alert link.

  2. Add the following parameters, click Next to move to the next parameter.

  • Alert name: stopped vm
  • Choose logs to include in the alert: will auto-fill with the query you entered
  • Set notification frequency and autoclose duration: Time between notifications is 5 min and Incident autoclose duration is 1 hr. Click Next.

alert-details.png

Who should be notified (optional):

  • Click on dropdown arrow next to Notification Channels, then click on Manage Notification Channels.

  • A Notification channels page will open in new tab.

  • Scroll down the page and click on ADD NEW for Email.

  • Enter your personal email in the Email Address field and a Display name.

  • Click Save.

  • When done, return to the Logs Explorer tab you were in previously.

  • Refresh the Notification Channels, then select the channel you just created. Click OK.

  1. Click Save.

Click Check my progress to verify the objective. Create the Log-based alert

You will now cause your VM to stop.

  1. Go to the 2nd Cloud Console tab, and navigate to Navigation menu > Compute Engine > VM instances.

  2. Check the box next to instance1, then click Stop at the top of the page, then click Stop again in the pop-up window. The green check mark will turn to a gray circle when the instance has been stopped.

  3. In the Search bar, type "monitoring", then choose the Monitoring option.

  4. Click on the Alerting tab. You'll see that your alert has registered. Under Alert Policies click the View all link and you'll see the log-based alert you created listed.

log-based-alert-in-alerts

Task 2. Log-based metric

Using log-based metrics you can define a metric that tracks errors in the logs to proactively respond to similar problems and symptoms before they are noticed by end users.

  1. At the beginning of the lab you deployed a standard GKE cluster. Run the following command to ensure that the cluster named gmp-cluster has been created:

gcloud container clusters list

If your cluster status says PROVISIONING, wait a moment and run the command above again. Repeat until the status is RUNNING.

  1. Authenticate the cluster:

gcloud container clusters get-credentials gmp-cluster

You should see the following message:

Fetching cluster endpoint and auth data. kubeconfig entry generated for gmp-cluster.
  1. Create a namespace to work in:

kubectl create ns gmp-test
  1. Now run the following to deploy a simple application that emits metrics at the /metrics endpoint:

kubectl -n gmp-test apply -f https://storage.googleapis.com/spls/gsp091/gmp_flask_deployment.yaml kubectl -n gmp-test apply -f https://storage.googleapis.com/spls/gsp091/gmp_flask_service.yaml
  1. Verify that the namespace is ready and emitting metrics:

kubectl get services -n gmp-test

You should see the following:

NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE hello LoadBalancer 10.0.12.114 34.83.91.157 80:32058/TCP 71s

Click Check my progress to verify the objective. Deploy the simple application that emits metrics

  1. Re-run the command until you see the External-IP address populated.

  2. Check that the Python Flask app is serving metrics with the following command:

curl $(kubectl get services -n gmp-test -o jsonpath='{.items[*].status.loadBalancer.ingress[0].ip}')/metrics

You should see the following:

# HELP flask_exporter_info Multiprocess metric # TYPE flask_exporter_info gauge flask_exporter_info{version="0.18.5"} 1.0

Task 3. Create a log-based metric

  1. Return to Logs Explorer.

  2. Click Create metric link.

  3. On the Create metric page, input the following:

  • Metric type: leave the default setting, Counter

  • Log metric name: hello-app-error

  • Filter selection: update the following into the field:

severity=ERROR resource.labels.container_name="hello-app" textPayload: "ERROR: 404 Error page not found"
  1. Click Create metric.

Click Check my progress to verify the objective. Create the log-based metric

Task 4. Create a metrics-based alert

  1. Under Create a metrics-based alert, click Create Alert.

  2. Under Select a Metric, the metric parameters will automatically fill in.

  • Update the Rolling window to 2 min.
  • Accept the other default settings
  • Click Next.

alerting-policy

  1. You will need to set Notifications. Feel free to re-use the channel you created earlier in the lab.

  2. Name the alert log based metric alert.

  3. Click Create Policy.

Click Check my progress to verify the objective. Create the metrics-based alert

Task 5. Generate some errors

Next you'll generate some errors to match the log-based metric you created and trigger the metric-based alert.

  1. In Cloud Shell, run the following to generate some errors:

timeout 120 bash -c -- 'while true; do curl $(kubectl get services -n gmp-test -o jsonpath='{.items[*].status.loadBalancer.ingress[0].ip}')/error; sleep $((RANDOM % 4)) ; done'
  1. Return to the Logs Explorer page, and go to the Severity section on the lower left side. Click on the Error severity. Now you can search for the 404 Error page not found error. View more information by expanding one of the 404 Error messages.

  2. Return to the Monitoring page, and click on Alerting. You will see the 2 policies you created.

  3. Click on the Alert policies link, and you should see both alerts in the Incidents section. Click on an incident to see details.

monitoring-2-alerts

The log-based metric alert will eventually resolve itself. If you need more time to investigate, run the errors script again and wait for the alert to be triggered again.

Click Check my progress to verify the objective. Generate some errors

Congratulations!

Google Cloud's Operations Suite Quest badge Cloud Logging Quest badge

Finish Your Quest

This self-paced lab is part of the Google Cloud's Operations Suite and Cloud Logging quests. A quest is a series of related labs that form a learning path. Completing a quest earns you the badge above, to recognize your achievement. You can make your badge (or badges) public and link to them in your online resume or social media account. Enroll in either quest and get immediate completion credit if you've taken this lab. See other available quests.

Take Your Next Lab

Continue your quest with Autoscaling an Instance Group with Custom Cloud Monitoring Metrics, or check out these suggestions:

Next steps / Learn more

Google Cloud Training & Certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated May 04, 2022
Lab Last Tested May 04, 2022

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.