[英]Google Cloud Functions Python Logging issue
我不知道该怎么说,但我觉得谷歌在我不知道的情况下改变了引擎盖下的某些东西。 我曾经在日志仪表板的 Google Cloud Console 中从我的 python Cloud Functions 获取日志。 而现在,它刚刚停止工作。
于是又去调查了半天,刚刚做了一个log hello world python Cloud Function:
import logging
def cf_endpoint(req):
logging.debug('log debug')
logging.info('log info')
logging.warning('log warning')
logging.error('log error')
logging.critical('log critical')
return 'ok'
所以这是我的 main.py,我将其部署为带有 http 触发器的云函数。
由于我有一个包含所有“调试”级别日志的日志摄取排除过滤器,因此我在日志仪表板中看不到任何内容。 但是当我删除它时,我发现了这个:
因此,似乎将 python 内置日志记录解析为 stackdriver 的东西停止了解析日志严重性参数! 如果我看起来很愚蠢,我很抱歉,但这是我唯一能想到的:/
你们对此有任何解释或解决方案吗? 我做错了吗?
预先感谢您的帮助。
2022/01 年更新:
输出现在看起来像这样:
[INFO]: Connecting to DB ...
严重性的下拉菜单如下所示:
使用“默认”作为显示 Python 日志记录所需的过滤器,这意味着只显示任何可用的日志,并且所有 Python 日志都在“默认”下,严重性仍然被删除。
使用 Python 原生日志记录模块时,不再支持 Stackdriver Logging 严重性过滤器。
但是,您仍然可以使用Stackdriver Logging Client Libraries创建具有特定严重性的日志。 检查此文档以参考 Python 库,并查看此文档以获取一些用例示例。
请注意,为了让日志位于正确的资源下,您必须手动配置它们,请参阅此列表以了解支持的资源类型。 同样,每种资源类型都有一些必需的标签,这些标签需要出现在日志结构中。
例如,以下代码会将日志写入 Stackdriver Logging 中的 Cloud Function 资源,严重性为ERROR
:
from google.cloud import logging
from google.cloud.logging.resource import Resource
log_client = logging.Client()
# This is the resource type of the log
log_name = 'cloudfunctions.googleapis.com%2Fcloud-functions'
# Inside the resource, nest the required labels specific to the resource type
res = Resource(type="cloud_function",
labels={
"function_name": "YOUR-CLOUD-FUNCTION-NAME",
"region": "YOUR-FUNCTION-LOCATION"
},
)
logger = log_client.logger(log_name.format("YOUR-PROJECT-ID"))
logger.log_struct(
{"message": "message string to log"}, resource=res, severity='ERROR')
return 'Wrote logs to {}.'.format(logger.name) # Return cloud function response
请注意, YOUR-CLOUD-FUNCTION-NAME
、 YOUR-FUNCTION-LOCATION
和YOUR-PROJECT-ID
中的字符串需要特定于您的项目/资源。
我遇到了同样的问题。
在@joan Grau 分享的链接中,我还看到有一种方法可以将云记录器与 Python 日志记录模块集成,这样您就可以像往常一样使用 Python 根记录器,并且所有日志都将发送到 StackDriver Logging。
...
我试过了,它有效。 简而言之,你可以通过两种方式做到这一点
将云记录器绑定到根日志记录的一种简单方法
from google.cloud import logging as cloudlogging
import logging
lg_client = cloudlogging.Client()
lg_client.setup_logging(log_level=logging.INFO) # to attach the handler to the root Python logger, so that for example a plain logging.warn call would be sent to Stackdriver Logging, as well as any other loggers created.
或者,您可以使用更细粒度的控制设置记录器
from google.cloud import logging as cloudlogging
import logging
lg_client = cloudlogging.Client()
lg_handler = lg_client.get_default_handler()
cloud_logger = logging.getLogger("cloudLogger")
cloud_logger.setLevel(logging.INFO)
cloud_logger.addHandler(lg_handler)
cloud_logger.info("test out logger carrying normal news")
cloud_logger.error("test out logger carrying bad news")
不想处理云日志库,我创建了一个自定义格式化程序,它发出带有正确字段的结构化日志,正如云日志所期望的那样。
class CloudLoggingFormatter(logging.Formatter):
"""Produces messages compatible with google cloud logging"""
def format(self, record: logging.LogRecord) -> str:
s = super().format(record)
return json.dumps(
{
"message": s,
"severity": record.levelname,
"timestamp": {"seconds": int(record.created), "nanos": 0},
}
)
将此处理程序附加到记录器会导致日志被解析并在日志控制台中正确显示。 在云功能中,我会将根记录器配置为发送到标准输出并将格式化程序附加到它。
# setup logging
root = logging.getLogger()
handler = logging.StreamHandler(sys.stdout)
formatter = CloudLoggingFormatter(fmt="[%(name)s] %(message)s")
handler.setFormatter(formatter)
root.addHandler(handler)
root.setLevel(logging.DEBUG)
从 Python 3.8 开始,您可以简单地print
带有severity
和message
属性的 JSON 结构。 例如:
print(
json.dumps(
dict(
severity="ERROR",
message="This is an error message",
custom_property="I will appear inside the log's jsonPayload field",
)
)
)
官方文档: https ://cloud.google.com/functions/docs/monitoring/logging#writing_structured_logs
我使用一个非常简单的自定义日志记录功能来记录到 Cloud Logging:
import json
def cloud_logging(severity, message):
print(json.dumps({"severity": severity, "message": message}))
cloud_logging(severity="INFO", message="Your logging message")
要在 GCP 上使用标准 python 日志记录模块(在 python 3.9 上测试),您可以执行以下操作:
import google.cloud.logging
logging_client = google.cloud.logging.Client()
logging_client.setup_logging()
import logging
logging.warning("A warning")
另请参阅: https ://cloud.google.com/logging/docs/setup/python
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.