作者 | 刘宇
策划 | 田晓旭
Serverless 白皮书中曾描述过 Serverless 的一些缺点,例如难以调试、冷启动严重等等。其中难以调试是表现在多个方面的,有一个方面是日志输出。
当我们把 Serverless 架构应用于实际项目,就会发现调试成为了效率的重要影响因素。以日志输出为例,某个函数被触发之后未得到预期结果,大家第一想法就是查看日志,但这时输出的日志可能并未是我们想要的,而且云厂商输出日志的延时也非常高。
日志输出现状
以腾讯云云函数为例,我们可以看一下其日志输出情况:
通过这个测试
功能,可以很快获取到函数的结果,并查看日志信息。
通过网关触发一个函数:
通过函数日志查看何时会刷出这个日志:
这个过程大概有 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)
输出结果:
1584108001.141546 ee7243dd-6532-11ea-8bce-5254000c8aa4
1584108005.2496068
这次输出结果是 4S,再做一个多次调用的时间对比图:
import json
import time
import numpy
import matplotlib.pyplot as plt
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)
timeList = []
for i in range(0, 100):
req = models.InvokeRequest()
params = '{"FunctionName":"test"}'
req.from_json_string(params)
resp = client.Invoke(req)
functionRequestId = json.loads(resp.to_json_string())["Result"]["FunctionRequestId"]
startTime = int(time.time())
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
endTime = int(time.time())
timeList.append(endTime - startTime)
print("最大时间", int(max(timeList)))
print("最小时间", int(min(timeList)))
print("平均时间", int(numpy.mean(timeList)))
plt.figure()
plt.subplot(2, 1, 1)
x_data = range(0, len(timeList))
plt.plot(x_data, timeList)
plt.subplot(2, 1, 2)
plt.hist(timeList, bins=20)
plt.show()
except TencentCloudSDKException as err:
print(err)
这是比较差的一段代码,耗时很久,可以考虑加入队列,一方面多进程在队列面加入执行的 RequestId,一方面消费 RequestId,进入到获取 Logs 的对象中,速度可以大大提升。但是无论如何,运行结果如下:
最大时间 31
最小时间 0
平均时间 17
通过这个结果,我们发现日志输出有两个问题:
就目前的腾讯云 Serverless 架构而言,如果要在本地开发一个项目,并在本地进行了初步的调试,就算一切正常,也并不能保证在线上完全可用,尤其在复杂的触发器环境下以及复杂的对象复用、内网资源使用的前提下,本地调试的难度非常大,很难完整模拟出线上的环境。
以 API 网关触发器为例,当本地写完代码,调试完成部署线上,通过 API 网关触发一次,发现函数代码不能正常运行,这个时候的第一想法是什么?查看日志,看一下打印的日志有哪些问题,是不是通过日志可以判断出问题。很遗憾的告诉你,你可能要等几秒钟,十几秒钟,甚至二十几秒,三十秒。
自建日志输出功能
通过刚才的分析,我们可以知道,在线上触发函数的时候,日志入库的速度非常缓慢,而且极其不稳定,一定条件下会严重影响开发进度以及问题定位的进度。为了解决这个问题,我们可以通过 Serverless 架构,封装一套实时日志功能:
在这个操作过程中,主要使用一个 API 网关作为 Websocket 与客户端建立链接,三个函数(注册函数,上报函数,清理函数)与 API 搭配使用,存储桶作为部分资源的临时存储。
整个流程大概可以描述为:
由于腾讯云的 API 网关限制,所以该功能每次最长只能执行 900s,900s 之后需要重新执行该程序。
API 网关涉及到的三个函数:
业务函数上报数据的逻辑,实际上就是修改常见组件的日志方法,以 Python 为例,例如重写print()
方法以及logging
组件:
重写print()
:
# -*- coding: utf8 -*-
import os
import sys
import json
import urllib.parse
import urllib.request
def print(*args):
url = os.environ.get("real_time_log_url")
cid = os.environ.get("real_time_log_id")
if url and cid and os.environ.get("real_time_log_id", None):
try:
retmsg = {
"coid": cid,
"data": " ".join([str(eveObject) for eveObject in args])
}
urllib.request.urlopen(
urllib.request.Request(
url=url,
data=json.dumps(retmsg).encode("utf-8")
)
)
except Exception as e:
sys.stdout.write("Debug Error:" + str(e))
sys.stdout.write("aaa"+ " ".join([str(eveObject) for eveObject in args]) + "\n")
对logging
进行额外的处理,将文件中的log
/info
... 等接口增加上报逻辑,例如:
def warning(msg, *args, **kwargs):
"""
Log a message with severity 'WARNING' on the root logger. If the logger has
no handlers, call basicConfig() to add a console handler with a pre-defined
format.
"""
realTimeLogs("WARNING %s %s"%(str(msg), " ".join([str(eveObject) for eveObject in args])))
if len(root.handlers) == 0:
basicConfig()
root.warning(msg, *args, **kwargs)
上报逻辑:
def realTimeLogs(data):
url = os.environ.get("real_time_log_url")
cid = os.environ.get("real_time_log_id")
if url and cid and os.environ.get("real_time_log_id", None):
try:
retmsg = {
"coid": cid,
"data": data
}
urllib.request.urlopen(
urllib.request.Request(
url=url,
data=json.dumps(retmsg).encode("utf-8")
)
)
except Exception as e:
sys.stdout.write("Debug Error:" + str(e))
封装成工具
封装成工具后的整体使用流程:
组件的安装与配置
安装scflog
:
npm install scflog
部署实时日志组件,新建项目,并且建立serverless.yaml
,内容:
PythonLogs:
component: '@gosls/tencent-pythonlogs'
inputs:
region: ap-guangzhou
通过sls --debug
部署:
DEBUG ─ Setting tags for function PythonRealTimeLogs_Cleanup
DEBUG ─ Creating trigger for function PythonRealTimeLogs_Cleanup
DEBUG ─ Deployed function PythonRealTimeLogs_Cleanup successful
PythonLogs:
websocket: ws://service-laabz6zm-1256773370.gz.apigw.tencentcs.com/test/python_real_time_logs
26s › PythonLogs › done
配置组件:
scflog set -w ws://service-laabz6zm-1256773370.gz.apigw.tencentcs.com/test/python_real_time_logs
配置成功输出:
DFOUNDERLIU-MB0:~ dfounderliu$ scflog set -w ws://service-laabz6zm-1256773370.gz.apigw.tencentcs.com/test/python_real_time_logs
设置成功
websocket: ws://service-laabz6zm-1256773370.gz.apigw.tencentcs.com/test/python_real_time_logs
region: ap-guangzhou
namespace: default
函数的初始化与部署
在项目中使用该组件的方法很简单。
mkdir scflogs && cd scflogs
scflog init -l python
index.py
文件以及serverless.yaml
文件:vim index.py
内容是:
from logs import *
import time
import logging
def main_handler(event, context):
print("event is: ", event)
time.sleep(1)
logging.debug("this is debug_msg")
time.sleep(1)
logging.info("this is info_msg")
time.sleep(1)
logging.warning("this is warning_msg")
time.sleep(1)
logging.error("this is error_msg")
time.sleep(1)
logging.critical("this is critical_msg")
time.sleep(1)
print("context is: ", event)
return "hello world"
vim serverless.yaml
内容是:
Hello_World:
component: "@serverless/tencent-scf"
inputs:
name: Hello_World
codeUri: ./
handler: index.main_handler
runtime: Python3.6
region: ap-guangzhou
description: My Serverless Function
memorySize: 64
timeout: 20
exclude:
- .gitignore
- .git/**
- node_modules/**
- .serverless
- .env
events:
- apigw:
name: serverless
parameters:
protocols:
- http
serviceName: serverless
description: the serverless service
environment: release
endpoints:
- path: /test
method: ANY
通过sls --debug
部署:
DEBUG ─ Deployed function Hello_World successful
Hello_World:
Name: Hello_World
Runtime: Python3.6
Handler: index.main_handler
MemorySize: 64
Timeout: 20
Region: ap-guangzhou
Namespace: default
Description: My Serverless Function
APIGateway:
- serverless - http://service-89bjzrye-1256773370.gz.apigw.tencentcs.com/release
30s › Hello_World › done
实时日志功能的测试
配置 APIGW 的触发器,地址是上面输出的地址 + endpoints 中的 path:
http://service-89bjzrye-1256773370.gz.apigw.tencentcs.com/release/test
打开实时日志:
scflog logs -n Hello_World -r ap-guangzhou
提醒实时日志开启成功:
DFOUNDERLIU-MB0:~ dfounderliu$ scflog logs -n Hello_World -r ap-guangzhou
实时日志开启 ...
用浏览器通过刚才函数部署完成返回的地址触发函数:
实时日志开启 ...
[2020-03-04 16:36:08] : ......}
[2020-03-04 16:36:09] : DEBUG debug_msg
[2020-03-04 16:36:10] : INFO info_msg
[2020-03-04 16:36:11] : WARNING warning_msg
[2020-03-04 16:36:14] : ERROR error_msg
[2020-03-04 16:36:14] : CRITICAL critical_msg
[2020-03-04 16:36:16] : context is: .......}
.......
至此,实现实时日志功能。
总 结
Serverless 架构虽然拥有很多优势,但是同时也有劣势,没有什么事情是完美的,Serverless 架构也是如此。在 Serverless 架构下,日志的实时性确实是一个问题,这个问题不仅仅是我们可能要等十几秒才能看到日志,而且会影响开发效率、维护效率以及问题定位效率,但是我们可以通过自身来实现这样的功能,通过 API 网关的 Websocket 能力,通过云函数的与 API 网关的结合,构建一个实时日志的系统。