miniprogram-logger
Version:
It is used to log and gather statistics of users' behavior.
70 lines (69 loc) • 2.1 kB
JavaScript
import { Reporter, logTransformFunction } from "../common/reporter";
export class ReportAnalytics extends Reporter {
constructor(tableName, fields, context) {
super(tableName, fields || ["action", "duration"], context);
this.Id = 0;
this.Stopwatch = new Map();
this.TransformFunction = logTransformFunction;
}
log() {
//@ts-ignore
this.report.apply(this, arguments);
}
/**
*
* @param label - 唯一标签,结束时使用同样标签,
* @param context - 记录上下文信息,如果未设置action则使用label作为action
*/
time(label, context) {
this.Stopwatch.set(label, [Date.now(), Object.assign({ [this.Fields[0]]: arguments[0] }, context)]);
}
/**
*
* @param label - 唯一标签,与开始对应
* @param context - 记录上下文信息,如果未设置action则使用label作为action
*/
timeEnd(label, context) {
if (!this.end(label, context)) {
//@ts-ignore
console.error("timer label not found", label);
}
}
start() {
if (arguments.length === 1 && typeof arguments[0] === "object") {
//对象参数
this.Stopwatch.set(this.Id, [Date.now(), arguments[0]]);
}
else {
//多参数
this.Stopwatch.set(this.Id, [
Date.now(),
Object.assign(arguments[1] || {}, { [this.Fields[0]]: arguments[0] }),
]);
}
return this.Id++;
}
/**
* 完成计时,并清除计时ID
* @param id
* @param context
*/
end(id, context) {
const info = this.Stopwatch.get(id);
if (!info) {
return false;
}
const [start, data] = info;
Object.assign(data, context, { [this.Fields[1]]: Date.now() - start });
this.report(data);
return this.remove(id);
}
/**
* 清除计时
* @param id
* @returns 不存在返回false
*/
remove(id) {
return this.Stopwatch.delete(id);
}
}