简体   繁体   English

使用 Google Cloud Logging Python 库发送带有标签的 JSON 有效负载

[英]Send a JSON Payload with labels using Google Cloud Logging Python library

I'm using the google-cloud-logging Python client library with Cloud Functions.我正在使用带有 Cloud Functions 的google-cloud-logging Python 客户端库 I'm following recommendations and using the standard Python logging library.我遵循建议并使用标准 Python 日志库。 v3+ of this library supports logging JSON payloads and setting custom metadata .此库的 v3+ 支持记录 JSON 有效负载设置自定义元数据

I wish to both set a custom label and log a JSON payload.我希望既设置自定义 label 并记录 JSON 有效负载。 The docs mention that sending a custom JSON payload can be achieved using the json_fields extra argument.文档提到可以使用json_fields extra参数来发送自定义 JSON 有效负载。 Example:例子:

import logging

data_dict = {"hello": "world"}
logging.info("message field", extra={"json_fields": data_dict})

With regard to sending a label the docs once again point to the extra argument.关于发送 label 文档再次指向extra参数。 Example:例子:

my_labels = {"foo": "bar"}
my_http = {"requestUrl": "localhost"}
my_trace = "01234"

logging.info(
    "hello", extra={"labels": my_labels, "http_request": my_http, "trace": my_trace}
)

Following the guidance above I'm under the impression that this should work in achieving both:按照上面的指导,我的印象是这应该可以同时实现:

image_metrics = {
    'total_images_sourced': 10,
    'total_images': 8
}

# Write custom metrics to Cloud Logging
logging.info("image_metrics", extra={
    "labels": {"type": "image"},
    "json_fields": image_metrics  
})

However, the resulting logs only output a text payload.但是,生成的日志只有 output 一个文本有效负载。 Neither the JSON payload nor the label is set. JSON 有效载荷和 label 均未设置。

在此处输入图像描述

How can I send both the JSON payload as well as the label?如何同时发送 JSON 有效负载以及 label?

Update 1 : This seems to work correctly when testing locally via the Functions Framework but when I deploy the exact same codebase to update the Cloud Function and run again, it result in the text payload and no label.更新 1 :当通过 Functions Framework 进行本地测试时,这似乎可以正常工作,但是当我部署完全相同的代码库以更新 Cloud Function 并再次运行时,它会导致文本有效负载并且没有 label。

This turned out to be an issue with my logging setup.这原来是我的日志记录设置的问题。 I was attaching two logging handlers to my root logger;我将两个日志记录处理程序附加到我的根记录器; the Cloud Logging handler for integration with GCP and the Streaming handler for outputting to the console.用于与 GCP 集成的 Cloud Logging 处理程序和用于输出到控制台的 Streaming 处理程序。

import logging

import google.cloud.logging
from google.cloud.logging.handlers import CloudLoggingHandler

log_name = 'my_log_name'

# Root logger
logger = logging.getLogger(log_name)
logger.setLevel(logging.DEBUG)

# Stream handler to log messages in the console.
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)

# Cloud Logging handler to log messages in GCP.
gcloud_logging_client = google.cloud.logging.Client()
gcloud_logging_handler = CloudLoggingHandler(
    gcloud_logging_client, name=log_name
)

# Add handlers
logger.addHandler(gcloud_logging_handler)
logger.addHandler(stream_handler)

This saw my log messages printed to the console and also sent in the correct format to Cloud Logging when developing locally .这看到我的日志消息打印到控制台,并在本地开发时以正确的格式发送到 Cloud Logging。 However, the StreamHandler only displays unformatted log messages (not JSON payloads) and the Cloud Logging Handler is unreliable on serverless workloads.但是,StreamHandler 仅显示未格式化的日志消息(不是 JSON 有效负载),并且 Cloud Logging Handler 在无服务器工作负载上不可靠。 This meant that my JSON payloads were being displayed as plain text messages.这意味着我的 JSON 有效负载显示为纯文本消息。

It turns out that the Google python logging library provides an easier way to send logs to Google Cloud using:事实证明,谷歌 python 日志库提供了一种更简单的方法来将日志发送到谷歌云,使用:

client = google.cloud.logging.Client()
client.setup_logging()

When using setup_logging() it chooses the right handler based on where your code is running meaning you don't need to manage the handlers yourself.使用setup_logging()时,它会根据代码运行的位置选择正确的处理程序,这意味着您不需要自己管理处理程序。 Using this instead sees my log messages sent and interpreted correctly in Cloud Logging both from local development and when deployed as a Cloud Function.使用它可以看到我的日志消息在本地开发和部署为 Cloud Function 时在 Cloud Logging 中正确发送和解释。

The one thing that was missing was a way to see log messages in the console when developing locally.缺少的一件事是在本地开发时在控制台中查看日志消息的方法。 I therefore modified my code to this:因此,我将代码修改为:

import logging

client = google.cloud.logging.Client()
client.setup_logging()

log = logging.getLogger()

if __name__ == '__main__':
    # Add a stream handler to log messages to the console.
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.INFO)
    log.addHandler(stream_handler)

It uses the recommended setup_logging() method whilst also including the stream handler for local development.它使用推荐的setup_logging()方法,同时还包括用于本地开发的 stream 处理程序。 Since if __name__ == '__main__': is never true in a Cloud Function environment it makes for a safe place to put things that only apply to local development.因为if __name__ == '__main__':在云 Function 环境中永远不会成立,所以它为放置仅适用于本地开发的东西提供了一个安全的地方。 This sees my log messages outputting to the console as well.这也可以看到我的日志消息也输出到控制台。

One thing to note is that the stream handler doesn't support structured JSON log messages so it will only output the message part (plain text) of a structured log message.需要注意的一点是 stream 处理程序不支持结构化的 JSON 日志消息,因此它只会 output 结构化日志消息的消息部分(纯文本)。 For my case this isn't an issue however.就我而言,这不是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 谷歌云日志python脚本权限错误 - Google cloud logging python script permission error 使用谷歌云发送自动 outlook 邮件 - Send automated outlook mail using Google cloud 谷歌云中的日志记录信息/调试消息 apache 光束 python sdk - logging info/debug messages in google cloud apache beam python sdk json 格式的 python 谷歌云列表 vm - python google cloud list vm in json format 需要使用Python 2.7版本中的“Google-cloud-ndb”库 - Need to use the "Google-cloud-ndb" library in Python 2.7 version 如何使用Python的Google Cloud Client Library配置gcloud项目 - How to use Google Cloud Client Library for Python to configure the gcloud project Python 中的双向 TLS 使用 Google Cloud KMS - Mutual TLS in Python using Google Cloud KMS 用于上传到谷歌云存储的子进程 CALL 或 python 库? - Subprocess CALL or python library for uploading to Google Cloud Storage? Google Cloud Logging 不解析来自 Container Optimized OS 的 JSON 消息 - Google Cloud Logging doesn't parse JSON message from Container Optimized OS 将使用 google-api-python-client 库的 Python 脚本部署为 Google Cloud Function - Deploying Python script that use google-api-python-client library as Google Cloud Function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM