我正在构建一个工具来下载 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-logging
的 LogEntry
类的函数包来做到这一点:
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/