send-sls-logger 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.ts +76 -0
  2. package/package.json +18 -0
package/index.ts ADDED
@@ -0,0 +1,76 @@
1
+ import SlsTracker, {
2
+ WebTrackerBrowserOptions,
3
+ } from "@aliyun-sls/web-track-browser";
4
+
5
+ interface StringObject {
6
+ [name: string]: string;
7
+ }
8
+
9
+ const opts: WebTrackerBrowserOptions = {
10
+ host: "", // 所在地域的服务入口。例如cn-hangzhou.log.aliyuncs.com
11
+ project: "", // Project名称。
12
+ logstore: "", // Logstore名称。
13
+ time: 5, // 发送日志的时间间隔,默认是10秒。
14
+ count: 10, // 发送日志的数量大小,默认是10条。
15
+ };
16
+ const defaultLogData: StringObject = {};
17
+ const exclude: string[] = [];
18
+ const tracker = new SlsTracker(opts);
19
+
20
+ const formatLogData = (data: string | StringObject, type = "log") => {
21
+ const result = {
22
+ type,
23
+ ...defaultLogData,
24
+ };
25
+ if (typeof data === "string") {
26
+ return { ...result, data };
27
+ } else if (typeof data === "object") {
28
+ return { ...result, ...data };
29
+ }
30
+ return result;
31
+ };
32
+
33
+ const send = (type) => {
34
+ return function (err) {
35
+ if (!opts.host || !opts.project || !opts.logstore) {
36
+ return console.error("日志初始化需要配置options");
37
+ }
38
+ let data: StringObject = {};
39
+ if (typeof err === "string") {
40
+ data.msg = err;
41
+ } else if (typeof err === "object") {
42
+ data = { ...err };
43
+ }
44
+ const isExcludeMsg = Object.keys(data).find((key) => {
45
+ return exclude.find((i) => new RegExp(i, "g").test(data[key]));
46
+ });
47
+ if (isExcludeMsg) {
48
+ console.log(data);
49
+ return;
50
+ }
51
+ const result = formatLogData(data, type);
52
+ tracker.send(result);
53
+ };
54
+ };
55
+
56
+ const error = send("error");
57
+ const warn = send("warn");
58
+ const log = send("log");
59
+
60
+ interface initConfig {
61
+ defaultData?: StringObject;
62
+ defaultExclude?: string[];
63
+ options?: WebTrackerBrowserOptions;
64
+ }
65
+
66
+ export default {
67
+ error,
68
+ warn,
69
+ log,
70
+ init: (config: initConfig = {} as initConfig) => {
71
+ const { defaultData = {}, defaultExclude = [], options = {} } = config;
72
+ Object.assign(defaultLogData, defaultData);
73
+ Object.assign(opts, options);
74
+ exclude.push(...defaultExclude);
75
+ },
76
+ };
package/package.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "send-sls-logger",
3
+ "version": "0.0.2",
4
+ "description": "阿里云sls的logger发送",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [
10
+ "logger",
11
+ "sls"
12
+ ],
13
+ "author": "liukai",
14
+ "license": "ISC",
15
+ "dependencies": {
16
+ "@aliyun-sls/web-track-browser": "^0.0.3"
17
+ }
18
+ }