【问题标题】:module 'google.cloud.logging_v2' has no attribute 'Client'模块“google.cloud.logging_v2”没有属性“客户端”
【发布时间】:2021-11-06 07:27:04
【问题描述】:

我正在尝试使用云功能以编程方式创建基于日志的指标。我真的没有找到任何代码示例,所以我有点迷茫。这是我到目前为止的代码

from google.cloud import logging_v2

    metric = {"name":"test","filter":"stuff_here"}
    client = logging_v2.Client()
    client.create(metric) 

我有以下错误module 'google.cloud.logging_v2' has no attribute 'Client'

#编辑

我在文档中找到了一些代码示例:

metric = client.metric(metric_name, filter_=filter, description=description)
assert not metric.exists()  # API call
metric.create()  # API call
assert metric.exists()  # API call 

但仍然遇到同样的错误

【问题讨论】:

    标签: python google-cloud-platform google-cloud-functions google-cloud-logging


    【解决方案1】:

    确实没有,见Client

    但是,Client 有一个 metric 方法“创建一个绑定到当前客户端的指标”。

    还有一个Metrics

    import os
    
    from google.cloud import logging_v2
    
    
    client = logging_v2.Client(project=os.getenv("PROJECT"))
    
    # You need to provide a filter
    # This one counts the Service Accounts created in my project
    filter=(
      "resource.type=\"service_account\" "
      "protoPayload.methodName=\"google.iam.admin.v1.CreateServiceAccountKey\" "
      "severity=\"NOTICE\""
    
    )
    
    metric_name=os.getenv("METRIC")
    

    或者使用client.metric:

    metric = client.metric(
      metric_name,
      filter_=filter,
      description="test")
    

    或者使用logging_v2.Metric(...).create():

    metric = logging_v2.Metric(
      metric_name,
      filter_=filter,
      client=client).create()
    

    还有:

    print(metric)
    

    还有:

    export PROJECT=[[YOUR-PROJECT]]
    export GOOGLE_APPLICATION_CREDENTIALS=/path/to/you/key.json
    export METRIC="test"
    
    # Before
    gcloud logging metrics list \
    --project=${PROJECT} \
    --filter="name=${METRIC}"
    Listed 0 items.
    
    python3 python/main.py
    
    # After
    gcloud logging metrics list \
    --project=${PROJECT} \
    --filter="name=${METRIC}" \
    --format="yaml(name,filter)"
    

    产量:

    filter: resource.type="service_account" protoPayload.methodName="google.iam.admin.v1.CreateServiceAccountKey" severity="NOTICE"
    name: test
    

    【讨论】:

    • 我有点理解你的意思,但我的代码到底意味着什么?
    • 添加回答
    【解决方案2】:

    客户端应该这样调用client = logging_v2.client.Client()

    例如:

    client = logging_v2.client.Client()
    metric = client.metric(metric_name, filter_=filter, description=description)
    assert not metric.exists()  # API call
    metric.create()  # API call
    assert metric.exists()  # API call 
    

    【讨论】:

      猜你喜欢
      • 2022-11-18
      • 2019-04-28
      • 2017-03-10
      • 2023-03-08
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      相关资源
      最近更新 更多