python-3.x - 如何手动设置 Google App Engine 请求日志的严重性?

标签 python-3.x google-app-engine logging google-cloud-platform stackdriver

我在 Google App Engine Python 3 标准环境中有一个应用程序。我将其设置为根据他们的请求对日志条目进行分组,如 Writing Application Logs 中所述。 (在“查看相关请求日志条目”部分)。

该页注释:

The highest severity from the "child" log entries does not automatically apply to the top-level entry. If that behavior is desired, manually set the highest severity in the top-level entry.

有问题的顶级条目是 App Engine 自动创建的请求日志。它始终处于日志级别“任何”。我没有看到如何更改其日志级别/严重性。

这是我现在拥有的代码(的一个分支):

import os
from flask import request
from google.cloud import logging as gcp_logging
from google.cloud.logging.resource import Resource

client = gcp_logging.Client()
logger = client.logger('my_custom_log_type')
trace_id = (f"projects/{os.environ['GOOGLE_CLOUD_PROJECT']}/traces/"
            f"{request.headers['X-Cloud-Trace-Context'].split('/')[0]}")
res = Resource(type='gae_app',
               labels={'project_id': os.environ['GOOGLE_CLOUD_PROJECT'],
                       'module_id': os.environ['GAE_SERVICE'],
                       'version_id': os.environ['GAE_VERSION']})
logger.log_text('Sample log text', resource=res, trace=trace_id, severity='INFO')

将日志与他们的请求分组非常有效,但是父(请求)日志,例如,

> * 2019-11-19 15:54:56.613 EST  GET  200  1.21 KiB  390ms  Chrome 78  /

正在显示“任何”日志级别。我希望它是适当的“信息”或“错误”。我怎样才能做到这一点?

最佳答案

我还没有找到修改自动生成日志的方法。

我仍然有兴趣听听是否有更好的方法,所以我不会将此答案标记为已接受。

但我找到了一种非常符合我需求的解决方法,即添加我自己的请求日志并忽略自动生成的请求日志。

对于每个子日志,我使用与问题代码中相同的想法,但更新了 flask 的 g 对象上的一个新属性,以跟踪到目前为止请求中最严重的日志级别。

from flask import g

LOG_LEVELS = ('DEFAULT', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')

previous_level = g.get('log_level', 0)
g.log_level = max(previous_level, new_level)

(其中 new_level 是 LOG_LEVELS 中级别的整数索引)

然后,为了生成新的请求日志,我使用了 this solution 的缩小版本:

def log_request(response):
    logger = client.logger('my_request_logger')
    severity = LOG_LEVELS[g.get('log_level', 0)]
    request_info = {
        'requestMethod': request.method,
        'requestUrl': request.url,
        'status': response.status_code,
        'userAgent': request.headers.get('USER-AGENT'),
        'responseSize': response.content_length,
        'latency': g.request_duration(),
        'remoteIp': request.remote_addr
    }
    if request.method == 'POST':
        payload = request.get_json() or json.loads(request.data.decode())
    else:
        payload = {}
    logger.log_struct(payload,
                      trace=trace_id,
                      http_request=request_info,
                      severity=severity)

以上内容在 my_logging 模块中。然后,只需向 main.py 中添加一些内容即可完成这项工作:

import time
from flask import g
import my_logging

@app.before_request
def setup_timing():
    g.request_start_time = time.time()
    g.request_duration = lambda: f'{(time.time() - g.request_start_time):.5f}s'

@app.after_request
def log_request(response):
    my_logging.log_request(response)
    return response

这工作得相当好 - 我很想听听任何让它变得更好的想法。

关于python-3.x - 如何手动设置 Google App Engine 请求日志的严重性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58943157/

相关文章:

用于部署为应用程序服务的 Node.js 的 Azure 应用程序日志记录(blob)

ios - 无法模拟发送给我的 iOS 崩溃报告

python - 修复 QTreeWidget 上的选定项目荧光笔

node.js - 如何使用 google 数据存储(在 javascript 中)创建模式?

python - Homebrew - `python@3` 和 `python3` 之间有什么区别?

google-app-engine - GAE Datastore 与 Google Cloud SQL 定价

java - 谷歌云端点中的 apiKeyRequired 未得到解决

java - 询问Apache公共(public)日志中的基本配置

django - 错误: client intended to send too large body

python-3.x - 在Docker中从源代码构建numpy