微服務觀測工具可讓您檢測應用程式,以便從部署在 Google Cloud 和其他位置的 gRPC 工作負載中,收集並在 Cloud Monitoring、Cloud Logging 和 Cloud Trace 中呈現遙測資料。微服務觀測功能可搭配任何已啟用 Microservices API 的部署作業,取得存取監控、記錄和追蹤記錄的權限。
在本教學課程中,您將瞭解如何使用微服務觀測功能,方法是使用 Compute Engine 建構簡單的 gRPC 應用程式,並為應用程式加入微服務觀測功能,然後在監控和記錄中查看這些功能。 Google Cloud
目標
整體來說,您需要執行以下操作:
服務開發人員可以:
- 使用您選擇的語言 (C++、Go 或 Java) 建立 gRPC 應用程式。
- 選擇加入應用程式,並控管微服務可觀察性外掛程式。
- 在 Compute Engine VM 上部署應用程式。
服務營運商可透過各種方式使用收集到的資料:
- 在 Trace 中查看追蹤記錄。
- 在名為「Microservices (gRPC) Monitoring」的監控資訊主頁上查看指標。
- 在 Metrics Explorer 中查看指標。
- 在 Logs Explorer 中檢查記錄項目。
費用
In this document, you use the following billable components of Google Cloud:
To generate a cost estimate based on your projected usage,
use the pricing calculator.
When you finish the tasks that are described in this document, you can avoid continued billing by deleting the resources that you created. For more information, see Clean up.
事前準備
主控台
- 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<wbr> 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<wbr> 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++ 1.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
- 在範例目錄中開啟 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
刪除個別資源
-
Delete the instance:
gcloud compute instances delete INSTANCE_NAME
後續步驟
- 如要進一步瞭解設定資料、追蹤定義、指標定義和記錄定義,請參閱微服務可觀察性參考資料。
- 如要瞭解如何查看記錄、追蹤記錄和指標,請參閱「查看追蹤記錄、指標和記錄項目」一文。