【问题标题】:How do I query GCP log viewer and obtain json results in Python 3.x (like gcloud logging read)如何在 Python 3.x 中查询 GCP 日志查看器并获取 json 结果(如 gcloud 日志读取)
【发布时间】:2019-12-12 16:13:52
【问题描述】:

我正在构建一个工具来下载 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)

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

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

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

【问题讨论】:

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


    【解决方案1】:

    您可以在 google-cloud-logging 包中的 LogEntry 类上使用 to_api_repr 函数来执行此操作:

    from google.cloud import logging
    
    client = logging.Client()
    logger = client.logger('log_name')
    
    for entry in logger.list_entries():
        print(entry.to_api_repr())
    

    【讨论】:

    • 感谢达斯汀的快速回复。不幸的是,我现在得到一个不同的错误:TypeError: Can not find message descriptor by type_url: type.googleapis.com/google.cloud.audit.AuditLog 我正在尝试查询:logger = client.logger('cloudaudit.googleapis.com%2Factivity') 另外,我可以像在 gcloud 中一样查询所有日志名称吗?
    • logger 的参数应该是您要解析的日志的名称,我认为'cloudaudit.googleapis.com%2Factivity' 在这里有效。
    • 在 json 字段中(通过 Log Viewer 和 gcloud 查看)字段为 "logName": "projects/windy-star-244817/logs/cloudaudit.googleapis.com%2Factivity"。如果我输入此名称的任何其他组合,我会收到一个错误,它期待 Expected the form projects/[PROJECT_ID]/logs/[ID]
    • 您最近的错误似乎是库问题。 google.cloud.audit.AuditLog 不在常用的原型中,因此不返回任何内容。 here 有一个问题,他们正在努力解决这种问题。
    猜你喜欢
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多