python - Google StackDriver 将日志与父请求关联起来 python 3

标签 python stackdriver google-cloud-stackdriver google-cloud-logging structured-logging

在 python 2.7 中,应用程序引擎 sdk 在后台执行工作,将所有日志与父请求嵌套在一起,以便在 Google StackDriver 中建立关联。

从过渡到 python 3 开始,它是通过使用谷歌云日志记录或结构化日志记录,并且从我能找到的所有不同引用资料来看,在堆栈的“子”日志中具有相同的跟踪 ID 非常重要驱动程序与“请求”日志进行匹配。

正如您在下面看到的,它仍然显示为不同的日志。

对于上下文,我什至在部署在应用程序引擎上的空 django 项目上尝试过此操作。

即使按照文档中的示例,也得到相同的结果: https://cloud.google.com/run/docs/logging#writing_structured_logs

Log StackDriver

尝试登录到标准输出会得到相同的结果。

Log StackDriver 2

编辑:

在使用标准输出时,在初始请求之后,所有其他请求都将嵌套在初始请求下。

但是,“父”日志不会获取“子”日志的最高严重性,因此过滤器不会获取实际日志。见下文:

enter image description here

最佳答案

感谢您的提问!

看起来您正在正确记录跟踪,但您的 logName 表明您没有使用 stdout 或 stderr。如果您将其中之一用于日志,它们将正确关联,如下所示:

StackDriver Logs Screenshot

您可以看到 logName 以 stdout 结尾。标准输出或标准错误将相互关联。您可以按照教程中所示进行创建:

# Build structured log messages as an object.
global_log_fields = {}

# Add log correlation to nest all log messages
# beneath request log in Log Viewer.
trace_header = request.headers.get('X-Cloud-Trace-Context')

if trace_header and PROJECT:
    trace = trace_header.split('/')
    global_log_fields['logging.googleapis.com/trace'] = (
        f"projects/{PROJECT}/traces/{trace[0]}")

# Complete a structured log entry.
entry = dict(severity='NOTICE',
             message='This is the default display field.',
             # Log viewer accesses 'component' as jsonPayload.component'.
             component='arbitrary-property',
             **global_log_fields)

print(json.dumps(entry))

编辑:

要过滤掉标准输出并仅在 stackdriver UI 中查看请求日志,您可以从过滤器中取消选择标准输出。 Logs Filter

有关使用 python 客户端 API 的示例,请参阅本文和随附的示例 Flask 应用程序。 Combining correlated Log Lines in Google Stackdriver

关于python - Google StackDriver 将日志与父请求关联起来 python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58846168/

相关文章:

python - Pandas :保存数据框以打开工作簿

python - 无需下载即可获取pdf的大小

python - 重定向 python 版本输出

python-3.x - 如何查询 GCP 日志查看器并在 Python 3.x 中获取 json 结果(如 gcloud logging read)

kubernetes - GKE 是在 Anthos 解决方案中默认构建的吗?获取 Anthos 指标

google-cloud-platform - 如何获取 GKE 节点池中的节点数作为堆栈驱动程序指标?

python - 如何用Python抓取网页渲染完成后的HTML内容

java - 使用 GAE 上的 java 客户端使用来自 Google Stackdriver 错误报告的数据

monitoring - 监控 GKE 节点中 CPU 和内存的百分比

google-cloud-platform - Stackdriver 中的 Google Cloud IoT Core 状态数据