Serverless架構下如何實現日誌的實時輸出?

Serverless白皮書中曾描述過Serverless的一些缺點,例如難以調試、冷啓動嚴重等等。其中難以調試是表現在多個方面的,有一個方面是日誌輸出。

當我們把Serverless架構應用於實際項目,就會發現調試成爲了效率的重要影響因素。以日誌輸出爲例,某個函數被觸發之後未得到預期結果,大家第一想法就是查看日誌,但這時輸出的日誌可能並未是我們想要的,而且雲廠商輸出日誌的延時也非常高。

日誌輸出現狀

以騰訊云云函數爲例,我們可以看一下其日誌輸出情況:

  • 通過控制檯或者是雲API的Invoke接口觸發雲函數:

通過這個測試功能,可以很快獲取到函數的結果,並查看日誌信息。

  • 通過API網關、COS等觸發雲函數,此處以API網關爲例:

通過網關觸發一個函數:

通過函數日誌查看何時會刷出這個日誌:

這個過程大概有11S,通過代碼來進行更加詳細的測試:

import json,time
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.scf.v20180416 import scf_client, models
try:
    cred = credential.Credential("", "")
    httpProfile = HttpProfile()
    httpProfile.endpoint = "scf.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = scf_client.ScfClient(cred, "ap-guangzhou", clientProfile)

    req = models.InvokeRequest()
    params = '{"FunctionName":"test"}'
    req.from_json_string(params)

    resp = client.Invoke(req)
    functionRequestId = json.loads(resp.to_json_string())["Result"][ "FunctionRequestId"]

    print(time.time(), functionRequestId)

    while True:
        time.sleep(0.2)
        req = models.GetFunctionLogsRequest()
        params = '{"FunctionName":"test"}'
        req.from_json_string(params)

        resp = client.GetFunctionLogs(req)
        if functionRequestId in str(resp.to_json_string()):
            break

    print(time.time())


except TencentCloudSDKException as err:
    print(err)

原文鏈接:【https://www.infoq.cn/article/6gcWzU4jkeW5dLrU4j2H】。未經作者許可,禁止轉載。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章