InfoQServerless 架构下如何实现日志的实时输出?

作者 | 刘宇策划 | 田晓旭Serverless 白皮书中曾描述过 Serverless 的一些缺点 , 例如难以调试、冷启动严重等等 。 其中难以调试是表现在多个方面的 , 有一个方面是日志输出 。
当我们把 Serverless 架构应用于实际项目 , 就会发现调试成为了效率的重要影响因素 。 以日志输出为例 , 某个函数被触发之后未得到预期结果 , 大家第一想法就是查看日志 , 但这时输出的日志可能并未是我们想要的 , 而且云厂商输出日志的延时也非常高 。
日志输出现状以腾讯云云函数为例 , 我们可以看一下其日志输出情况:
InfoQServerless 架构下如何实现日志的实时输出?
本文插图
通过这个测试功能 , 可以很快获取到函数的结果 , 并查看日志信息 。

  • 通过 API 网关、COS 等触发云函数 , 此处以 API 网关为例:
通过网关触发一个函数:
InfoQServerless 架构下如何实现日志的实时输出?
本文插图
通过函数日志查看何时会刷出这个日志:
InfoQServerless 架构下如何实现日志的实时输出?
本文插图
这个过程大概有 11S , 通过代码来进行更加详细的测试:
importjson,timefrom tencentcloud.commonimportcredentialfrom tencentcloud.common.profile.client_profileimportClientProfilefrom tencentcloud.common.profile.http_profileimportHttpProfilefrom tencentcloud.common.exception.tencent_cloud_sdk_exceptionimportTencentCloudSDKExceptionfrom tencentcloud.scf.v20180416importscf_client, modelstry:cred = credential.Credential("","")httpProfile =HttpProfilehttpProfile.endpoint ="scf.tencentcloudapi.com"clientProfile =ClientProfileclientProfile.httpProfile = httpProfileclient = scf_client.ScfClient(cred,"ap-guangzhou", clientProfile)req = models.InvokeRequestparams = '{"FunctionName":"test"}'req.from_json_string(params)resp = client.Invoke(req)functionRequestId = json.loads(resp.to_json_string)["Result"]["FunctionRequestId"]print(time.time, functionRequestId)whileTrue:time.sleep(0.2)req = models.GetFunctionLogsRequestresp = client.GetFunctionLogs(req)iffunctionRequestIdinstr(resp.to_json_string):breakprint(time.time)1584108001.141546ee7243dd-6532-11ea-8bce-5254000c8aa41584108005.2496068这次输出结果是 4S , 再做一个多次调用的时间对比图:
importjsonimporttimeimportnumpyimportmatplotlib.pyplot as plttry:timeList = foriinrange(0,100):startTime = int(time.time)whileTrue:breakendTime = int(time.time)timeList.append(endTime - startTime)print("最大时间", int(max(timeList)))print("最小时间", int(min(timeList)))print("平均时间", int(numpy.mean(timeList)))plt.figure


推荐阅读