@edgeone/ef-cls-sdk
v1.0.4
Published
Edgefunctions CLS SDK
Downloads
35
Maintainers
Readme
@edgeone/ef-cls-sdk
基于 tencentcloud-cls-sdk-js 进行开发,适配 EdgeFunctions Runtime API,用于在 EdgeOne 边缘函数中进行 CLS 日志上报。
安装
npm i @edgeone/ef-cls-sdk
使用
import { AsyncClient, Content, LogGroup, LogItem, PutLogsRequest } from '@edgeone/ef-cls-sdk';
/** CONFIG START */
const TENCENT_SECRET_ID = 'xxxxx';
const TENCENT_SECRET_KEY = 'xxxxx';
const CLS_END_POINT = 'ap-xxxxx.cls.tencentcs.com';
const CLS_TOPIC_ID = 'xxxxx';
/** CONFIG END */
const clsAsyncClient = new AsyncClient({
endpoint: CLS_END_POINT,
secretId: TENCENT_SECRET_ID,
secretKey: TENCENT_SECRET_KEY,
sourceIp: 'edge',
retry_times: 1,
});
async function clsUpload(data: string) {
const logGroup = new LogGroup();
const logItem = new LogItem();
const logTime = Math.floor(Date.now() / 1000);
const logContent = new Content('__CONTENT__', JSON.stringify(data));
logItem.setTime(logTime);
logItem.pushBack(logContent);
logGroup.addLogs(logItem);
const clsRequest = new PutLogsRequest(CLS_TOPIC_ID, logGroup);
return await clsAsyncClient.PutLogs(clsRequest);
}
async function doClsUpload(request: Request) {
try {
const data = await request.clone().text();
await clsUpload(data);
} catch (err) {
console.error(`cls upload error: ${err}`);
}
}
async function handleRequest(event: FetchEvent) {
const { request } = event;
const contentType = request.headers.get('content-type') || '';
if (contentType.includes('application/json') || contentType.includes('text/plain')) {
// 用于通知边缘函数等待 Promise 完成,可延长事件处理的生命周期,不阻塞 fetch(request) 的返回。
event.waitUntil(doClsUpload(request));
}
return;
}
addEventListener('fetch', handleRequest);