Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/gitpod-protocol/src/util/analytics.ts
2500 views
1
/**
2
* Copyright (c) 2021 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
import Analytics = require("analytics-node");
8
import { IAnalyticsWriter, IdentifyMessage, TrackMessage, PageMessage } from "../analytics";
9
import { log } from "./logging";
10
11
export function newAnalyticsWriterFromEnv(): IAnalyticsWriter {
12
switch (process.env.GITPOD_ANALYTICS_WRITER) {
13
case "segment":
14
return new SegmentAnalyticsWriter(
15
process.env.GITPOD_ANALYTICS_SEGMENT_KEY || "",
16
process.env.GITPOD_ANALYTICS_SEGMENT_ENDPOINT || "",
17
);
18
case "log":
19
return new LogAnalyticsWriter();
20
default:
21
return new NoAnalyticsWriter();
22
}
23
}
24
25
class SegmentAnalyticsWriter implements IAnalyticsWriter {
26
protected readonly analytics: Analytics;
27
28
constructor(writeKey: string, endpoint: string) {
29
this.analytics = new Analytics(writeKey, {
30
host: endpoint,
31
});
32
}
33
34
identify(msg: IdentifyMessage) {
35
try {
36
this.analytics.identify(
37
{
38
...msg,
39
integrations: {
40
All: true,
41
Mixpanel: !!msg.userId,
42
},
43
},
44
(err: Error) => {
45
if (err) {
46
log.warn("analytics.identify failed", err);
47
}
48
},
49
);
50
} catch (err) {
51
log.warn("analytics.identify failed", err);
52
}
53
}
54
55
track(msg: TrackMessage) {
56
try {
57
this.analytics.track(
58
{
59
...msg,
60
integrations: {
61
All: true,
62
Mixpanel: !!msg.userId,
63
},
64
},
65
(err: Error) => {
66
if (err) {
67
log.warn("analytics.track failed", err);
68
}
69
},
70
);
71
} catch (err) {
72
log.warn("analytics.track failed", err);
73
}
74
}
75
76
page(msg: PageMessage) {
77
try {
78
this.analytics.page(
79
{
80
...msg,
81
integrations: {
82
All: true,
83
Mixpanel: !!msg.userId,
84
},
85
},
86
(err: Error) => {
87
if (err) {
88
log.warn("analytics.page failed", err);
89
}
90
},
91
);
92
} catch (err) {
93
log.warn("analytics.page failed", err);
94
}
95
}
96
}
97
98
class LogAnalyticsWriter implements IAnalyticsWriter {
99
identify(msg: IdentifyMessage): void {
100
log.debug("analytics identify", msg);
101
}
102
track(msg: TrackMessage): void {
103
log.debug("analytics track", msg);
104
}
105
page(msg: PageMessage): void {
106
log.debug("analytics page", msg);
107
}
108
}
109
110
class NoAnalyticsWriter implements IAnalyticsWriter {
111
identify(msg: IdentifyMessage): void {}
112
track(msg: TrackMessage): void {}
113
page(msg: PageMessage): void {}
114
}
115
116