微服務觀測工具可讓您檢測應用程式,以便在 Cloud Monitoring、Cloud Logging 和 Cloud Trace 中,收集並呈現部署在 Google Cloud 和其他位置的 gRPC 工作負載遙測資料。微服務可觀測性適用於任何已啟用 Microservices API,並獲准存取 Monitoring、Logging 和 Trace 的部署作業。
在本教學課程中,您將在 Google Cloud 使用 Compute Engine 建構簡單的 gRPC 應用程式,並透過微服務可觀測性功能檢測應用程式,然後在 Monitoring 和 Logging 中即時查看結果,瞭解如何使用微服務可觀測性功能。
目標
大致來說,您需要執行以下操作:
服務開發人員可以:
- 使用您選擇的語言 (C++、Go 或 Java) 建立 gRPC 應用程式。
- 選擇加入應用程式,並控管微服務可觀測性外掛程式。
- 在 Compute Engine VM 上部署應用程式。
身為服務營運商,您可以透過多種方式使用收集到的資料:
- 在 Trace 中查看追蹤記錄。
- 在名為「微服務 (gRPC) 監控」的監控資訊主頁上查看指標。
- 在 Metrics Explorer 中查看指標。
- 在記錄檔探索工具中檢查記錄項目。
費用
在本文件中,您會使用 Google Cloud的下列計費元件:
如要根據預測用量估算費用,請使用 Pricing Calculator。
完成本文所述工作後,您可以刪除已建立的資源,避免繼續計費。詳情請參閱清除所用資源一節。
事前準備
主控台
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Compute Engine, and Microservices API APIs.
-
Create a service account:
-
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.
In the Service account description field, enter a description. For example,
Service account for quickstart
. - Click Create and continue.
-
Grant the following roles to the service account: Logging > Logs Viewer > Logs Writer, Monitoring > Monitoring Editor > Metrics Writer, Trace > Trace Admin > Trace Agent.
To grant a role, find the Select a role list, then select the role.
To grant additional roles, click
Add another role and add each additional role. - Click Continue.
-
In the Service account users role field, enter the identifier for the principal that will attach the service account to other resources, such as Compute Engine instances.
This is typically the email address for a Google Account.
-
Click Done to finish creating the service account.
-
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Compute Engine, and Microservices API APIs.
-
Create a service account:
-
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.
In the Service account description field, enter a description. For example,
Service account for quickstart
. - Click Create and continue.
-
Grant the following roles to the service account: Logging > Logs Viewer > Logs Writer, Monitoring > Monitoring Editor > Metrics Writer, Trace > Trace Admin > Trace Agent.
To grant a role, find the Select a role list, then select the role.
To grant additional roles, click
Add another role and add each additional role. - Click Continue.
-
In the Service account users role field, enter the identifier for the principal that will attach the service account to other resources, such as Compute Engine instances.
This is typically the email address for a Google Account.
-
Click Done to finish creating the service account.
-
- 請參閱微服務可觀測性總覽。
- 請參閱這兩個支援的環境變數,決定要使用哪一個,並判斷環境變數所需的值。
cli
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Compute Engine, and Microservices API APIs:
gcloud services enable compute.googleapis.com
microservices.googleapis.com -
Set up authentication:
-
Create the service account:
gcloud iam service-accounts create SERVICE_ACCOUNT_NAME
Replace
SERVICE_ACCOUNT_NAME
with a name for the service account. -
Grant roles to the service account. Run the following command once for each of the following IAM roles:
roles/logging.logWriter, roles/monitoring.metricWriter, roles/cloudtrace.agent
:gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=ROLE
Replace the following:
SERVICE_ACCOUNT_NAME
: the name of the service accountPROJECT_ID
: the project ID where you created the service accountROLE
: the role to grant
-
Grant the required role to the principal that will attach the service account to other resources.
gcloud iam service-accounts add-iam-policy-binding SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com --member="user:USER_EMAIL" --role=roles/iam.serviceAccountUser
Replace the following:
SERVICE_ACCOUNT_NAME
: the name of the service accountPROJECT_ID
: the project ID where you created the service accountUSER_EMAIL
: the email address for a Google Account
-
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Compute Engine, and Microservices API APIs:
gcloud services enable compute.googleapis.com
microservices.googleapis.com -
Set up authentication:
-
Create the service account:
gcloud iam service-accounts create SERVICE_ACCOUNT_NAME
Replace
SERVICE_ACCOUNT_NAME
with a name for the service account. -
Grant roles to the service account. Run the following command once for each of the following IAM roles:
roles/logging.logWriter, roles/monitoring.metricWriter, roles/cloudtrace.agent
:gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=ROLE
Replace the following:
SERVICE_ACCOUNT_NAME
: the name of the service accountPROJECT_ID
: the project ID where you created the service accountROLE
: the role to grant
-
Grant the required role to the principal that will attach the service account to other resources.
gcloud iam service-accounts add-iam-policy-binding SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com --member="user:USER_EMAIL" --role=roles/iam.serviceAccountUser
Replace the following:
SERVICE_ACCOUNT_NAME
: the name of the service accountPROJECT_ID
: the project ID where you created the service accountUSER_EMAIL
: the email address for a Google Account
-
- 請參閱微服務可觀測性總覽。
- 請參閱這兩個支援的環境變數,決定要使用哪一個,並判斷環境變數所需的值。
建立及連線至 Compute Engine VM
請按照這些操作說明建立並連線至 Compute Engine VM 執行個體。在 VM 上部署應用程式,然後使用微服務可觀測性檢測應用程式。
建立 VM 執行個體:
gcloud compute instances create grpc-observability-vm \ --image-family=debian-11 \ --image-project=debian-cloud \ --service-account=SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com
連線至 VM 執行個體:
gcloud compute ssh --project=$PROJECT_ID grpc-observability-vm
將應用程式部署至 Compute Engine VM
您可以選擇將應用程式部署至上一步建立的 Compute Engine VM,然後略過這個步驟,也可以使用範例,繼續以偏好語言查看操作說明。
C++
連線至 VM 執行個體後,請執行下列指令。
sudo apt-get update -y sudo apt-get install -y git build-essential clang git clone -b v1.54.0 https://github.com/grpc/grpc.git --depth=1
Go
確認您已安裝 Go。
sudo apt-get install -y git sudo apt install wget wget https://go.dev/dl/go1.20.2.linux-amd64.tar.gz sudo rm -rf /usr/local/go && sudo tar -C /usr/local -xzf \ go1.20.2.linux-amd64.tar.gz export PATH=$PATH:/usr/local/go/bin
複製
gRPC-Go
範例。git clone https://github.com/grpc/grpc-go.git cd grpc-go/ git checkout -b run-observability-example 875c97a94dca8093bf01ff2fef490fbdd576373d
Java
連線至 VM 執行個體後,請確認已安裝 Java 8 以上版本。
sudo apt update sudo apt upgrade sudo apt install git sudo apt-get install -y openjdk-11-jdk-headless
複製
grpc-java
存放區。export EXAMPLES_VERSION=v1.54.1 git clone -b $EXAMPLES_VERSION --single-branch --depth=1 \ https://github.com/grpc/grpc-java.git
建立 gRPC Google Cloud 可觀測性設定檔
您需要個別的 gRPC Google Cloud 可觀測性設定檔,才能為伺服器和用戶端啟用微服務可觀測性。這個檔案的位置會在後續步驟中匯出為 GRPC_GCP_OBSERVABILITY_CONFIG_FILE
。請按照下列說明,在設定檔中設定不同參數。
範例 GRPC_GCP_OBSERVABILITY_CONFIG_FILE
{
"project_id": "your-project-here",
"cloud_logging": {
"client_rpc_events": [
{
"methods": ["google.pubsub.v1.Subscriber/Acknowledge", "google.pubsub.v1.Publisher/CreateTopic"],
"exclude": true,
},
{
"methods": ["google.pubsub.v1.Subscriber/*", "google.pubsub.v1.Publisher/*"],
"max_metadata_bytes": 4096,
"max_message_bytes": 4096,
}],
"server_rpc_events": [{
"methods": ["*"],
"max_metadata_bytes": 4096,
"max_message_bytes": 4096
}],
},
"cloud_monitoring": {},
"cloud_trace": {
"sampling_rate": 0.5,
}
"labels": {
"SOURCE_VERSION": "J2e1Cf",
"SERVICE_NAME": "payment-service-1Cf",
"DATA_CENTER": "us-west1-a"
}
}
以下各節包含在個別元件的設定中啟用資料收集功能的說明。如果您在本教學課程中使用 gRPC 範例,可以照常使用這個設定 (更新 your-project-here
後),或將這個設定做為應用程式的範本。
啟用指標
如要啟用指標,請將 cloud_monitoring
物件新增至設定,並將其值設為 {}
。
如要進一步瞭解指標,請參閱「指標定義」。
啟用追蹤
如要啟用追蹤功能,請按照下列步驟操作:
- 將
cloud_trace
物件新增至設定。 - 將
cloud_trace.sampling_rate
設為0.5
,隨機追蹤 50% 的 RPC。
如果您打算跨服務啟用追蹤功能,請確保服務支援將從上游 (或自行啟動) 收到的追蹤內容傳播至下游。
如要進一步瞭解追蹤功能,請參閱「追蹤定義」。
啟用記錄功能
如要啟用記錄功能,請按照下列步驟操作:
- 將
cloud_logging
物件新增至設定。 - 在
client_rpc_events
和server_rpc_events
中新增模式,指定要產生傳輸層級事件記錄的服務或方法集,以及要記錄的標頭和訊息位元組數。
如要進一步瞭解記錄功能,請參閱「記錄定義」。
為可觀測性外掛程式檢測應用程式
如要檢測應用程式,以便使用微服務可觀測性外掛程式,請按照您偏好語言的下列操作說明操作。
C++
從 gRPC C++ v1.54 開始,您可以使用 C++ 搭配微服務可觀測性。範例存放區位於 GitHub。
觀測功能僅支援 Bazel 建構系統。將目標
grpcpp_gcp_observability
新增為依附元件。如要啟用微服務可觀測性,需要額外的依附元件 (可觀測性模組),以及對現有 gRPC 用戶端、伺服器或兩者進行下列程式碼變更:
#include <grpcpp/ext/gcp_observability.h> int main(int argc, char** argv) { auto observability = grpc::GcpObservability::Init(); assert(observability.ok()); … // Observability data flushed when object goes out of scope }
在執行任何 gRPC 作業 (包括建立管道、伺服器或憑證) 之前,請先叫用下列項目:
grpc::GcpObservability::Init();
這會傳回
absl::StatusOr<GcpObservability>
,請儲存該值。狀態有助於判斷可觀測性是否已成功初始化。隨附的GcpObservability
物件會控管可觀測性的生命週期,並在超出範圍時自動關閉及清除可觀測性資料。
Go
- gRPC Go
v1.54.0
以上版本支援微服務可觀測性外掛程式。範例存放區位於 GitHub。
使用 Go 模組時,如要啟用微服務可觀測性,需要可觀測性模組和下列程式碼:
import "google.golang.org/grpc/gcp/observability"
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := observability.Start(ctx); err != nil {
log.Warning("Unable to start gRPC observability:", err)
}
defer observability.End()
…
}
observability.Start
呼叫會剖析環境變數中的設定、建立相應的匯出工具,並將收集邏輯注入呼叫後建立的用戶端連線和伺服器。延遲的 observability.End
呼叫會清除資源,並確保緩衝資料在應用程式關閉前排清。
更新應用程式碼後,請執行下列指令來更新 go.mod
檔案。
go mod tidy
Java
如要將微服務觀測功能與 Java 應用程式搭配使用,請修改建構作業,加入 grpc-gcp-observability
構件。使用 gRPC 1.54.1 以上版本。
在 Gradle 和 Maven 建構工具區段的建構程式碼片段中,grpcVersion
的值設為 1.54.1。
範例存放區位於 GitHub。
- 如要順利檢測 Java 應用程式,以取得微服務可觀測性,請將下列程式碼新增至
main()
。
...
import io.grpc.gcp.observability.GcpObservability;
...
// Main application class
...
public static void main(String[] args) {
...
// call GcpObservability.grpcInit() to initialize & get observability
GcpObservability observability = GcpObservability.grpcInit();
...
// call close() on the observability instance to shutdown observability
observability.close();
...
}
請注意,您必須先呼叫 GcpObservability.grpcInit()
,才能建立任何 gRPC 管道或伺服器。GcpObservability.grpcInit()
函式會讀取微服務可觀測性設定,並使用該設定建立每個管道和伺服器中記錄、指標和追蹤功能所需的全域攔截器和追蹤器。GcpObservability.grpcInit()
是執行緒安全,且必須只呼叫一次。這個方法會傳回 GcpObservability
的例項,您必須儲存這個例項,才能在稍後呼叫 close()
。
GcpObservability.close()
會取消分配資源。之後建立的任何頻道或伺服器都不會執行記錄作業。
GcpObservability
會實作 java.lang.AutoCloseable
,如果您使用 try-with-resource
,系統會自動關閉 java.lang.AutoCloseable
,如下所示:
...
import io.grpc.gcp.observability.GcpObservability;
...
// Main application class
...
public static void main(String[] args) {
...
// call GcpObservability.grpcInit() to initialize & get observability
try (GcpObservability observability = GcpObservability.grpcInit()) {
...
} // observability.close() called implicitly
...
}
使用 Gradle 建構工具
如果您使用 Gradle 建構工具,請加入下列項目:
def grpcVersion = '1.54.1'
...
dependencies {
...
implementation "io.grpc:grpc-gcp-observability:${grpcVersion}"
...
}
使用 Maven 建構工具 (pom.xml)
如果您使用 Maven 建構工具,請加入下列項目:
<properties>
...
<grpc.version>1.54.1</grpc.version>
...
</properties>
...
<dependencies>
...
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-gcp-observability</artifactId>
<version>${grpc.version}</version>
</dependency>
...
</dependencies>
執行應用程式
只有在教學課程中使用 gRPC 範例時,才需要按照本節的操作說明進行。您可以修改 run
指令,指定應用程式二進位檔。
執行伺服器
C++
- 建立 VM 的 SSH 工作階段。
匯出環境變數。按照上述步驟建立
server_config.json
。export GOOGLE_CLOUD_PROJECT=$PROJECT_ID export GRPC_GCP_OBSERVABILITY_CONFIG_FILE="$(pwd)/examples/cpp/gcp_observability/helloworld/server_config.json"
執行伺服器應用程式
shell cd grpc tools/bazel run examples/cpp/gcp_observability/helloworld:greeter_server
Go
- 建立 VM 的 SSH 工作階段。
匯出環境變數。按照上述步驟建立
server_config.json
。export GRPC_GCP_OBSERVABILITY_CONFIG_FILE=./server/serverConfig.json
執行伺服器應用程式
shell go run ./server/main.go
Java
- 在 examples 目錄中開啟 README 檔案,然後按照檔案中的操作說明操作。
- 當指示要求您開啟另一個終端機視窗時,請發出下列指令:
shell gcloud compute ssh --project=$PROJECT_ID grpc-observability-vm
執行用戶端
C++
- 建立另一個連往 VM 的 SSH 工作階段。
匯出環境變數。按照上述步驟建立
client_config.json
檔案。export GOOGLE_CLOUD_PROJECT=$PROJECT_ID export GRPC_GCP_OBSERVABILITY_CONFIG_FILE="$(pwd)/examples/cpp/gcp_observability/helloworld/client_config.json"
執行用戶端應用程式
cd grpc tools/bazel run examples/cpp/gcp_observability/helloworld:greeter_client
Go
- 建立另一個連往 VM 的 SSH 工作階段。
- 匯出環境變數。使用上述步驟建立
client_config.json
檔案。shell export GRPC_GCP_OBSERVABILITY_CONFIG_FILE=./client/clientConfig.json
執行用戶端應用程式
cd grpc-go/examples/features/observability go run ./client/main.go
Java
- 在範例目錄中開啟 README 檔案,然後按照檔案中的操作說明操作。
- 當操作說明要求您開啟另一個終端機視窗時,請發出下列指令:
shell gcloud compute ssh --project=$PROJECT_ID grpc-observability-vm
清除所用資源
如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。
刪除專案
Delete a Google Cloud project:
gcloud projects delete PROJECT_ID
刪除個別資源
-
刪除執行個體:
gcloud compute instances delete INSTANCE_NAME
後續步驟
- 如要進一步瞭解設定資料、追蹤定義、指標定義和記錄定義,請參閱微服務可觀測性參考資料。
- 如要瞭解如何查看記錄、追蹤記錄和指標,請參閱「查看追蹤記錄、指標和記錄項目」