TypeError 将结构化日志从云函数写入谷歌云日志

如何解决TypeError 将结构化日志从云函数写入谷歌云日志

我正在尝试将云函数中的日志写入云日志记录,但在执行此操作时遇到问题。我的代码如下,其中消息是这样的日志:“20210319-11:39:58-CET - INFO - 这是一条信息消息”,属性只是字符串。

import base64
import json
import os
import pytz
from datetime import datetime
from google.cloud import logging
from google.cloud.logging_v2.resource import Resource

RESOURCE_TYPE = "cloudiot_devices"
PROJECT = os.environ.get("GCP_PROJECT")
DEVICE_REGISTRY = REGISTRY_ID
LOCATION = LOCATION
DATEFORMAT = "%Y%m%d-%H:%M:%S"

def iot_logger(event,context):
    """Triggered from a message on a Cloud Pub/Sub topic.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for the event.
    """
    log = base64.b64decode(event['data']).decode('utf-8')
    attributes = event['attributes']

    print(log)
    print(json.dumps(attributes))

    print("preparing timestamp")
    # Extract elements from log
    date_str,severity,message = log.split(" - ")

    # This is the main content for the log
    log_content = {"message":message}

    # turn log timestamp str to an aware datetime object for our timestamp
    tzname = date_str.split("-")[-1]
    # remove time zone to avoid tripping up the datetime module
    date_str = date_str[:-4]
    date_unaware = datetime.strptime(date_str,DATEFORMAT)
    date_aware = date_unaware.astimezone(pytz.timezone(tzname))

    print(f"done preparing timestamp: {date_aware}")

    # extract attributes
    logger_name = attributes["logger_name"]
    device_num_id = attributes["device_num_id"]

    print("creating resource")
    # create resource 
    resource_labels = {
        'project_id':PROJECT,'device_num_id':device_num_id,'device_registry_id':DEVICE_REGISTRY,'location':LOCATION
    }
    log_resource = Resource(type=RESOURCE_TYPE,labels=resource_labels)

    print("initiating client")
    # initiate logging client
    log_client = logging.Client()

    logger = log_client.logger(logger_name)

    print("creating structured log")
    logger.log_struct(log_content,severity=severity,resource=log_resource,timestamp=date_aware)

但是,我一直面临 log_struct 命令的问题,我一直无法弄清楚问题出在哪里。最初我将一个字符串传递给时间戳,但它不起作用,所以现在我传递了一个日期对象。但现在错误不同了: 编辑:不止一个:

Traceback (most recent call last):
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/protobuf/json_format.py",line 589,in _ConvertFieldValuePair
    self.ConvertMessage(value,sub_message)
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/protobuf/json_format.py",line 485,in ConvertMessage
    self._ConvertFieldValuePair(value,message)
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/protobuf/json_format.py",line 603,in _ConvertFieldValuePair
    raise ParseError('Failed to parse {0} field: {1}.'.format(name,e))
google.protobuf.json_format.ParseError: Failed to parse labels field: expected string or bytes-like object. 
Traceback (most recent call last):
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/protobuf/json_format.py",e))
google.protobuf.json_format.ParseError: Failed to parse labels field: expected string or bytes-like object. 
"Traceback (most recent call last):
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py",line 2447,in wsgi_app
    response = self.full_dispatch_request()
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py",line 1952,in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py",line 1821,in handle_user_exception
    reraise(exc_type,exc_value,tb)
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/_compat.py",line 39,in reraise
    raise value
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py",line 1950,in full_dispatch_request
    rv = self.dispatch_request()
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py",line 1936,in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/functions_framework/__init__.py",line 149,in view_func
    function(data,context)
  File "/workspace/main.py",line 64,in iot_logger
    logger.log_struct(log_content,timestamp=date_aware)
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/logging_v2/logger.py",line 180,in log_struct
    self._do_log(client,StructEntry,info,**kw)
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/logging_v2/logger.py",line 133,in _do_log
    client.logging_api.write_entries([api_repr])
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/logging_v2/_gapic.py",line 140,in write_entries
    log_entry_pbs = [_log_entry_mapping_to_pb(entry) for entry in entries]
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/logging_v2/_gapic.py",in <listcomp>
    log_entry_pbs = [_log_entry_mapping_to_pb(entry) for entry in entries]
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/cloud/logging_v2/_gapic.py",line 507,in _log_entry_mapping_to_pb
    ParseDict(mapping,entry_pb)
  File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/protobuf/json_format.py",line 454,in ParseDict
    parser.ConvertMessage(js_dict,line 597,e))
google.protobuf.json_format.ParseError: Failed to parse resource field: Failed to parse labels field: expected string or bytes-like object.."

它说它需要一个字符串或类似字节的对象,但我不确定在哪里。我想它与日期无关,因为当它是一个字符串时它给了我一个错误。此外,我认为应该可以使用的资源,我正在查看有关此 stackoverflow 问题的一个非常相似的示例,但它对我不起作用:

Google Cloud Functions Python Logging issue

我做错了什么?

解决方法

我在@jabbson 的帮助下解决了这个问题。我遇到了一些问题,但主要是我在没有意识到的情况下给了它一些错误的东西。

我正在使用这里指出的环境变量:https://cloud.google.com/functions/docs/env-var#nodejs_8_python_37_and_go_111 但由于某种原因,我的项目 ID 为 null。我的 resource_type 也有错别字。

最后,我不得不玩弄时间戳,直到它真正像我想要的那样工作。 LogEntry 文档说它是一个字符串,但在这种情况下,我必须向它传递一个 datetime 对象并将本地时间转换为 UTC,这样我才能在云日志中找到它。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-