python-3.x - 如何查询 GCP 日志查看器并在 Python 3.x 中获取 json 结果(如 gcloud logging read)

标签 python-3.x google-cloud-platform gcloud stackdriver google-cloud-stackdriver

我正在构建一个工具来下载 GCP 日志,将日志作为单行 json 条目保存到磁盘,然后对这些日志执行处理。该程序需要支持导出到云存储的日志和当前在 stackdriver 中的日志(以部分支持尚未预先配置导出到云存储的环境)。云存储部分已完成,但我无法从 stackdriver 下载日志。

我想在 Python 中实现与 gcloud 函数“gcloud logging read”类似的功能。是的,我可以使用 gcloud,但我想将所有内容构建到一个工具中。

我目前有这个示例代码来打印命中结果,但是我无法获得 JSON 格式的完整日志条目:

def downloadStackdriver():
    client = logging.Client()
    FILTER = "resource.type=project"
    for entry in client.list_entries(filter_=FILTER):
        a = (entry.payload.value)
        print(a)

如何获取匹配日志的完整 JSON 输出,就像使用 gcloud logging read 一样?

基于其他 stackoverflow 页面,我尝试使用 MessageToDict 和 MessageToJson,但是我收到错误

"AttributeError: 'ProtobufEntry' object has no attribute 'DESCRIPTOR'"

最佳答案

您可以使用 to_api_repr来自 google-cloud-loggingLogEntry 类的函数包来做到这一点:

from google.cloud import logging

client = logging.Client()
logger = client.logger('log_name')

for entry in logger.list_entries():
    print(entry.to_api_repr())

关于python-3.x - 如何查询 GCP 日志查看器并在 Python 3.x 中获取 json 结果(如 gcloud logging read),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57353495/

相关文章:

python - 如何在Python列表中查找特定字符串,如果找到则打印位置,否则打印0

python - 如何在索引中应用 value_counts 并创建新的数据帧?

python - numpy : Grouping/binning values based on associations

python - Google Cloud Datastore 模拟器不使用默认凭据

kubernetes - 区分多个Kubernetes集群的方法

python - 来自 Dataframe 的条形图

android - 在 Big Query 的表中插入数据时出现 IO 异常

python - 在 Google Cloud Platform 中读取存储桶中 Keras ML 训练的批量数据的理想方法是什么?

gcloud - 为什么 gcloud app deploy 上传 0 个文件到谷歌云存储?

java - 在 App Engine Standard (Java 8) 中使用 Spring Boot Web 应用程序时出现空白页面