如何在 GKE 上通过 stackdriver 查看容器日志

How to view container logs via stackdriver on GKE

我读到默认情况下,GKE 上的集群将所有日志写入 stackdriver。在 GKE UI 上,我可以看到所有部署的容器日志,但我希望以编程方式从 API 获取这些日志。

我试过 gcloud logging read "resource.labels.pod_id="<pod-id>"" 但没有返回任何内容。

我是否需要做一些特殊的事情才能在集群上启用日志记录?如果没有,我如何访问特定 deployment/pod/container 的日志?

此外,这些日志是否持久化?比如,当部署结束时,我还能访问这些日志吗?

您可以通过多种方式从 Stackdriver 读取 GKE pods 日志。其中一些是:

Reading logs

To read log entries in Logging, you can do any of the following:

  • Use the Logs Viewer in the Google Cloud Console.
  • Call the Logging API through the Client Libraries for your programming language.
  • Call the Logging API REST endpoints directly. See the Logging API reference documentation.
  • Use the Cloud SDK. For more information, see the gcloud logging command-line interface.

    Cloud.google.com: Logging: Setup

至于:

Do I need to do something special in order to enable logging on the cluster? And if not, how do I access logs for a specific deployment/pod/container?

请参考:Cloud.google.com: Logging: Access control

回答如下:

Further, are these logs persistent? As in, when the deployment dies, can I still access these logs?

是的,即使部署已删除,您仍然可以访问此日志。即使您删除了集群,您仍然可以访问日志。存储在 Stackdriver 中的日志具有 保留 策略,这些策略将在设定的时间内存储日志。 请参考:


请查看下面的示例,其中显示了如何使用 gcloud 命令访问日志:

步骤:

  • 创建一个 Deployment 将日志发送到 Stackdriver
  • 检查日志是否存储在 Stackdriver 中
  • 使用 gcloud
  • 从 Stackdriver 获取日志

创建部署

请按照 Google 云平台指南生成一个 Deployment,它将向 Stackdriver 发送数据:

检查日志是否在 Stackdriver 中。

通过上述部署导出的日志将存储在 Stackdriver 中。它的示例应如下所示:

{
 insertId: "REDACTED"  
 labels: {
  k8s-pod/pod-template-hash: "545464fb5"   
  k8s-pod/run: "custom-metric-sd"   
 }
 logName: "projects/REDACTED/logs/stderr"  
 receiveTimestamp: "2020-05-26T10:17:16.161949129Z"  
 resource: {
  labels: {
   cluster_name: "gke-logs"    
   container_name: "sd-dummy-exporter"    
   location: "ZONE"    
   namespace_name: "default"    
   pod_name: "custom-metric-sd-545464fb5-2rdvx"    
   project_id: "REDACTED"    
  }
  type: "k8s_container"   
 }
 severity: "ERROR"  
 textPayload: "2020/05/26 10:17:10 Finished writing time series with value: 0xc420015290
"  
 timestamp: "2020-05-26T10:17:10.356684667Z"  
}

以上日志条目将有助于创建 gcloud 命令以仅从 Stackdriver 获取指定的日志。

使用 gcloud

从 Stackdriver 获取日志

如您所指:

I've tried to do something like gcloud logging read "resource.labels.pod_id=""" but nothing is returned.

没有返回任何内容很可能与您使用的命令未找到请求的资源有关。

要从 Stackdriver 获取此日志,请调用以下命令:

$ gcloud logging read "resource.type=k8s_container AND resource.labels.container_name=sd-dummy-exporter" 

在较小的部分上划分上述命令:

  • resource.type=k8s_container - 它将获取类型为 k8s_container
  • 的日志
  • resource.labels.container_name=XYZ - 它将获取具有指定 container_name 的日志。

这部分与前面提到的示例单数日志条目直接相关。

提示:

resources.labels.container_name can be used to collect logs from multiple pods as the specific pod can be referenced with pod_name.