首页 > 解决方案 > Python Cloud Functions 添加日志以查看发生了什么

问题描述

我正在使用 Python 处理存储在 Firestore 中的数据。我在本地机器上创建了一个函数来更新我在 firestore 中的数据,但现在我想添加一个云函数,以便每天使用 Pub/sub 和云调度程序自动更新。

这是我正在使用的功能:

from google.cloud import firestore
from datetime import datetime, timedelta

db = firestore.Client.from_service_account_json('credentials/gc.json')

def update_collection__persons():   
    persons = db.collection(u'collection__persons')
    #person_docs = persons.stream()
    person_docs = [snapshot for snapshot in persons.stream()]

    for person_doc in person_docs:
        person_dict = person_doc.to_dict()
        #last_updated = person_dict['last_updated']
        #last_processed = person_dict['last_processed']
        #dt_last_updated = datetime(1, 1, 1) + timedelta(microseconds=last_updated/10)
        #dt_last_processed = datetime(1, 1, 1) + timedelta(microseconds=last_processed/10)

        #if dt_last_processed < dt_last_updated:
        orders = db.collection(u'collection__orders').where(u'email', u'==', person_dict['email'])
        orders_docs = [snapshot for snapshot in orders.stream()]

        sum_price = 0
        count = 0
        date_add_list = []

        for order_doc in orders_docs:
            order_dict = order_doc.to_dict() 
            sum_price += order_dict['total_price']
            count +=1
            date_add_list.append(order_dict['dateAdded'])
        if count > 0:
            data = {'metrics': {'LTV': sum_price,
                                'AOV': sum_price/count,
                                'Quantity_orders': count,
                                'first_order_date': min(date_add_list),
                                'last_order_date': max(date_add_list)},
                     'last_processed': int((datetime.utcnow() - datetime(1, 1, 1)).total_seconds() * 10000000),
                      'delta_last_updated_last_processed': 0}

            db.collection(u'collection__persons').document(person_dict['email']).set(data, merge = True)     

我想把它放在谷歌函数中,我这里有两个问题:

  1. 我收到一个错误,因为当函数被触发时 - 看起来它向它传递了一些东西并且它导致了一个错误,因为 def 只是()。

我已经读到我必须将这两个变量放在我的函数中:https ://cloud.google.com/functions/docs/calling/pubsub?hl=en

def My_function (event, context):

我不明白我与这些变量有什么关系,我必须在我的函数中更改哪些内容才能使用这些变量?

  1. 我想在运行该函数后编写日志,以了解该函数是否启动良好以及何时完成,如果出现问题,我也知道如何编写,我读到我可以使用 google.cloud.logging 来完成:Google Cloud Functions Python 日志记录问题

但是我不知道如何在我的函数中实现这个日志,我没有太多的经验

标签: pythongoogle-cloud-firestoregoogle-cloud-functions

解决方案


调用的 pubsub 云函数update_blanklabelcom__persons()如下所示:

from google.cloud import firestore
from datetime import datetime, timedelta

# Service account provided by Cloud Function environment
db = firestore.Client()

def update_blanklabelcom__persons():   
    persons = db.collection(u'collection__persons')
    person_docs = [snapshot for snapshot in persons.stream()]

    for person_doc in person_docs:
        person_dict = person_doc.to_dict()
        orders = db.collection(u'collection__orders').where(u'email', u'==', person_dict['email'])
        orders_docs = [snapshot for snapshot in orders.stream()]

        sum_price = 0
        count = 0
        date_add_list = []

        for order_doc in orders_docs:
            order_dict = order_doc.to_dict() 
            sum_price += order_dict['total_price']
            count +=1
            date_add_list.append(order_dict['dateAdded'])
        if count > 0:
            data = {'metrics': {'LTV': sum_price,
                                'AOV': sum_price/count,
                                'Quantity_orders': count,
                                'first_order_date': min(date_add_list),
                                'last_order_date': max(date_add_list)},
                     'last_processed': int((datetime.utcnow() - datetime(1, 1, 1)).total_seconds() * 10000000),
                      'delta_last_updated_last_processed': 0}

            db.collection(u'collection__persons').document(person_dict['email']).set(data, merge = True) 


def persons_pubsub(event, context):

    print("update blanklabel started")
    update_blanklabelcom__persons()
    print("update blanklabel done")

您不需要使用eventandcontext变量。它们提供有关调用该函数的 pubsub 事件的额外信息。要写入日志,您可以使用print语句。您打印的任何内容都将显示在 Cloud Function 日志中,并带有时间戳:

在此处输入图像描述

我从控制台部署了这个云函数,如此处所述。这是requirements.txt

google-cloud-firestore>=1.4.0

推荐阅读