@crimson-education/browser-logger 2.0.2 → 3.0.0

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 (71) hide show
  1. package/README.md +212 -67
  2. package/lib/index.d.ts +6 -76
  3. package/lib/index.d.ts.map +1 -1
  4. package/lib/index.js +42 -186
  5. package/lib/index.js.map +1 -1
  6. package/lib/logger/consoleTransport.d.ts +37 -0
  7. package/lib/logger/consoleTransport.d.ts.map +1 -0
  8. package/lib/logger/consoleTransport.js +81 -0
  9. package/lib/logger/consoleTransport.js.map +1 -0
  10. package/lib/logger/datadogTransport.d.ts +8 -0
  11. package/lib/logger/datadogTransport.d.ts.map +1 -0
  12. package/lib/logger/datadogTransport.js +21 -0
  13. package/lib/logger/datadogTransport.js.map +1 -0
  14. package/lib/logger/index.d.ts +16 -0
  15. package/lib/logger/index.d.ts.map +1 -0
  16. package/lib/logger/index.js +148 -0
  17. package/lib/logger/index.js.map +1 -0
  18. package/lib/logger/index.test.d.ts +2 -0
  19. package/lib/logger/index.test.d.ts.map +1 -0
  20. package/lib/logger/index.test.js +60 -0
  21. package/lib/logger/index.test.js.map +1 -0
  22. package/lib/logger/utils.d.ts +15 -0
  23. package/lib/logger/utils.d.ts.map +1 -0
  24. package/lib/logger/utils.js +32 -0
  25. package/lib/logger/utils.js.map +1 -0
  26. package/lib/reporters/amplifyReporter.d.ts +2 -2
  27. package/lib/reporters/amplifyReporter.d.ts.map +1 -1
  28. package/lib/reporters/amplifyReporter.js +13 -14
  29. package/lib/reporters/amplifyReporter.js.map +1 -1
  30. package/lib/reporters/datadogReporter.d.ts +7 -5
  31. package/lib/reporters/datadogReporter.d.ts.map +1 -1
  32. package/lib/reporters/datadogReporter.js +37 -100
  33. package/lib/reporters/datadogReporter.js.map +1 -1
  34. package/lib/reporters/gtmReporter.d.ts.map +1 -1
  35. package/lib/reporters/gtmReporter.js +2 -7
  36. package/lib/reporters/gtmReporter.js.map +1 -1
  37. package/lib/reporters/index.d.ts +66 -3
  38. package/lib/reporters/index.d.ts.map +1 -1
  39. package/lib/reporters/index.js +210 -17
  40. package/lib/reporters/index.js.map +1 -1
  41. package/lib/reporters/logReporter.d.ts +35 -0
  42. package/lib/reporters/logReporter.d.ts.map +1 -0
  43. package/lib/reporters/logReporter.js +62 -0
  44. package/lib/reporters/logReporter.js.map +1 -0
  45. package/lib/types/logger.d.ts +43 -2
  46. package/lib/types/logger.d.ts.map +1 -1
  47. package/lib/types/logger.js.map +1 -1
  48. package/lib/types/reporter.d.ts +58 -6
  49. package/lib/types/reporter.d.ts.map +1 -1
  50. package/lib/utils.d.ts +9 -8
  51. package/lib/utils.d.ts.map +1 -1
  52. package/lib/utils.js +28 -48
  53. package/lib/utils.js.map +1 -1
  54. package/lib/utils.test.js +18 -5
  55. package/lib/utils.test.js.map +1 -1
  56. package/package.json +1 -1
  57. package/src/index.ts +38 -208
  58. package/src/logger/consoleTransport.ts +101 -0
  59. package/src/logger/datadogTransport.ts +20 -0
  60. package/src/logger/index.test.ts +68 -0
  61. package/src/logger/index.ts +139 -0
  62. package/src/logger/utils.ts +28 -0
  63. package/src/reporters/amplifyReporter.ts +15 -16
  64. package/src/reporters/datadogReporter.ts +48 -116
  65. package/src/reporters/gtmReporter.ts +2 -7
  66. package/src/reporters/index.ts +216 -3
  67. package/src/reporters/logReporter.ts +86 -0
  68. package/src/types/logger.ts +49 -4
  69. package/src/types/reporter.ts +66 -6
  70. package/src/utils.test.ts +20 -6
  71. package/src/utils.ts +37 -62
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Crimson Education Browser Logger
2
2
 
3
- An abstract logger and reporting utility for browser environments.
3
+ A structured logger and analytics reporting utility for browser environments.
4
4
 
5
5
  This library contains a number of reporters that is will send analytics to.
6
6
 
@@ -34,30 +34,39 @@ Logger.init({
34
34
  application: 'test',
35
35
  },
36
36
 
37
- datadog: {
38
- applicationId: config.datadogApplicationId,
39
- clientToken: config.datadogClientToken,
40
- site: config.datadogSite,
41
- proxyUrl: config.datadogTunnelProxyUrl,
42
- version: config.datadogVersion,
43
-
44
- sampleRate: config.environment === 'production' ? 50 : 0,
45
- replaySampleRate: config.environment === 'production' ? 50 : 0,
46
-
47
- forwardConsoleLogs: true,
48
- trackInteractions: true,
49
- trackFrustrations: true,
50
- allowedTracingOrigins: ['https://my.api.domain']
51
- },
52
-
53
- amplify: {
54
- region: config.awsRegion,
55
- identityPoolId: config.pinpointIdentityPoolId,
56
- analyticsAppId: config.pinpointAnalyticsAppId,
57
-
58
- autoTrackEvents: true,
59
- autoTrackPageViews: true,
60
- autoTrackSessions: true,
37
+ reporters: {
38
+ log: true,
39
+
40
+ gtm: true,
41
+
42
+ datadog: {
43
+ applicationId: config.datadogApplicationId,
44
+ clientToken: config.datadogClientToken,
45
+ site: config.datadogSite,
46
+ proxyUrl: config.datadogTunnelProxyUrl,
47
+ version: config.datadogVersion,
48
+
49
+ sampleRate: config.environment === 'production' ? 50 : 0,
50
+ replaySampleRate: config.environment === 'production' ? 50 : 0,
51
+
52
+ forwardConsoleLogs: true,
53
+ logTransport: {
54
+ level: Logger.LogLevel.Info,
55
+ },
56
+ trackInteractions: true,
57
+ trackFrustrations: true,
58
+ allowedTracingOrigins: ['https://my.api.domain']
59
+ },
60
+
61
+ amplify: {
62
+ region: config.awsRegion,
63
+ identityPoolId: config.pinpointIdentityPoolId,
64
+ analyticsAppId: config.pinpointAnalyticsAppId,
65
+
66
+ autoTrackEvents: true,
67
+ autoTrackPageViews: true,
68
+ autoTrackSessions: true,
69
+ }
61
70
  }
62
71
  });
63
72
 
@@ -77,8 +86,7 @@ Logger.trackEvent({
77
86
  },
78
87
  });
79
88
 
80
- // Must init before you can create a logger.
81
- const logger = Logger.createLogger('app');
89
+ export const logger = Logger.createLogger();
82
90
 
83
91
  // Attributed logging.
84
92
  logger.info('WOW!', {
@@ -86,7 +94,133 @@ logger.info('WOW!', {
86
94
  });
87
95
  ```
88
96
 
89
- ### Reporters
97
+ ### Structured Logging
98
+
99
+ Structured logging in this library is loosely based on Winston, and follows roughly the same interface as `@crimson-education/node-logger`.
100
+
101
+ Call `Logger.createLogger()` to create a logger instance, it is recommended to re-use this as a global logger everywhere, and then call `.child()` to reuse metadata.
102
+
103
+ Global metadata about the service will be added for transport usage after calling `Logger.init()`.
104
+
105
+ You can add more Global Metadata at any time by calling `addMetadata()`.
106
+
107
+
108
+ ```ts
109
+ export const logger = Logger.createLogger();
110
+
111
+ const log = logger.child({
112
+ from: 'childLog',
113
+ });
114
+
115
+ log.info('My Log', { jobCount: jobs.length });
116
+
117
+ const timer = log.startTimer();
118
+
119
+ const result = await job(jobs);
120
+
121
+ timer.done({ message: 'Job Completed', metadata: { id: result.id } });
122
+ ```
123
+
124
+ ### Reporting
125
+
126
+ #### Opting out of events
127
+
128
+ You can opt out of sending events to reporters on a global, or per call basis using the endpoints config.
129
+
130
+ E.g. On calls
131
+
132
+ ```ts
133
+ Logger.trackEvent({
134
+ message: 'my-event',
135
+ toReporters: ['log', 'datadog'],
136
+ excludeReporters: ['datadog']
137
+ });
138
+ ```
139
+
140
+ E.g. Globally
141
+
142
+ ```ts
143
+ Logger.init({
144
+ reporters: {
145
+ log: true,
146
+ datadog: {
147
+ ...
148
+ endpoints: {
149
+ trackEvent: false,
150
+ }
151
+ }
152
+ }
153
+ });
154
+ ```
155
+
156
+ These will only send to the log reporter, it is recommended to use `toReporters` or `excludeReporters` separately as they overlap.
157
+
158
+ #### Filtering out metadata
159
+
160
+ You can filter what metadata gets sent to each reporter in the reporter config.
161
+ This accepts a string for exact match metadata keys, or a RegExp.
162
+ You can use `.` to traverse metadata.
163
+
164
+ ```ts
165
+ Logger.init({
166
+ reporters: {
167
+ log: {
168
+ ignoreMetadataPatterns: [
169
+ 'internalError',
170
+ 'user.email',
171
+ /error\.stack.*/g
172
+ ]
173
+ }
174
+ }
175
+ });
176
+ ```
177
+
178
+ ### Filtering out Breadcrumb categories
179
+
180
+ You can filter what breadcrumbs get sent to reports in the reporter config.
181
+
182
+ ```ts
183
+ Logger.init({
184
+ reporters: {
185
+ log: {
186
+ ignoreBreadcrumbCategories: [
187
+ 'fetch'
188
+ ]
189
+ }
190
+ }
191
+ });
192
+
193
+ // Not sent to the log reporter.
194
+ Logger.addBreadcrumb({
195
+ ...
196
+ category: 'fetch',
197
+ });
198
+ ```
199
+
200
+ ### Configure Reporters
201
+
202
+ #### Log
203
+
204
+ By default, the log reporter is enabled. This adds all reporter functions to logs. Set `reporters.log` to `false` to disable reporter logging.
205
+
206
+ ```ts
207
+ import { config } from '../configuration';
208
+ import * as Logger from '@crimson-education/browser-logger';
209
+
210
+ Logger.init({
211
+ reporters: {
212
+ log: {
213
+ trackEventLevel: Logger.LogInfo.Debug,
214
+ endpoints: {
215
+ recordSession: false,
216
+ recordSessionStop: false,
217
+ }
218
+ }
219
+ }
220
+ });
221
+ ```
222
+
223
+ Check out the [`DatadogReporterConfig`](https://github.com/crimson-education/browser-logger/blob/main/src/reporters/datadogReporter.ts) for all of the configuration you can apply to Datadog reporting.
90
224
 
91
225
  #### Datadog
92
226
 
@@ -97,26 +231,32 @@ import { config } from '../configuration';
97
231
  import * as Logger from '@crimson-education/browser-logger';
98
232
 
99
233
  Logger.init({
100
- ...
101
- datadog: {
102
- applicationId: config.datadogApplicationId,
103
- clientToken: config.datadogClientToken,
104
- site: config.datadogSite,
105
- proxyUrl: config.datadogTunnelProxyUrl,
106
- version: config.datadogVersion,
107
-
108
- sampleRate: config.environment === 'production' ? 50 : 0,
109
- replaySampleRate: config.environment === 'production' ? 50 : 0,
110
-
111
- forwardConsoleLogs: true,
112
- trackInteractions: true,
113
- allowedTracingOrigins: ['https://my.api.domain']
234
+ reporters: {
235
+ datadog: {
236
+ applicationId: config.datadogApplicationId,
237
+ clientToken: config.datadogClientToken,
238
+ site: config.datadogSite,
239
+ proxyUrl: config.datadogTunnelProxyUrl,
240
+ version: config.datadogVersion,
241
+
242
+ sampleRate: config.environment === 'production' ? 50 : 0,
243
+ replaySampleRate: config.environment === 'production' ? 50 : 0,
244
+
245
+ forwardConsoleLogs: true,
246
+ logTransport: {
247
+ level: Logger.LogLevel.Info,
248
+ },
249
+ trackInteractions: true,
250
+ allowedTracingOrigins: ['https://my.api.domain']
251
+ }
114
252
  }
115
253
  });
116
254
  ```
117
255
 
118
256
  Check out the [`DatadogReporterConfig`](https://github.com/crimson-education/browser-logger/blob/main/src/reporters/datadogReporter.ts) for all of the configuration you can apply to Datadog reporting.
119
257
 
258
+ This automatically adds a Datadog Log Transport that transmits Log data to Datadog, this can be customized in `DatadogReporterConfig` with `logTransport`, or disabled by setting `logTransport` to `false`.
259
+
120
260
  #### Amplify/Pinpoint
121
261
 
122
262
  To configure Amplify, this requires at least `region`, `identityPoolId` and `analyticsAppId`.
@@ -131,15 +271,16 @@ import { config } from '../configuration';
131
271
  import * as Logger from '@crimson-education/browser-logger';
132
272
 
133
273
  Logger.init({
134
- ...
135
- amplify: {
136
- region: config.amplifyAwsRegion,
137
- analyticsAppId: config.pinpointAnalyticsAppId,
138
- identityPoolId: config.amplifyIdentityPoolId,
139
-
140
- autoTrackEvents: true,
141
- autoTrackPageViews: true,
142
- autoTrackSessions: true,
274
+ reporters: {
275
+ amplify: {
276
+ region: config.amplifyAwsRegion,
277
+ analyticsAppId: config.pinpointAnalyticsAppId,
278
+ identityPoolId: config.amplifyIdentityPoolId,
279
+
280
+ autoTrackEvents: true,
281
+ autoTrackPageViews: true,
282
+ autoTrackSessions: true,
283
+ }
143
284
  }
144
285
  });
145
286
  ```
@@ -158,15 +299,16 @@ Auth.configure({
158
299
  });
159
300
 
160
301
  Logger.init({
161
- ...
162
- amplify: {
163
- region: config.amplifyAwsRegion,
164
- analyticsAppId: config.pinpointAnalyticsAppId,
165
- identityPoolId: false,
166
-
167
- autoTrackEvents: true,
168
- autoTrackPageViews: true,
169
- autoTrackSessions: true,
302
+ reporters: {
303
+ amplify: {
304
+ region: config.amplifyAwsRegion,
305
+ analyticsAppId: config.pinpointAnalyticsAppId,
306
+ identityPoolId: false,
307
+
308
+ autoTrackEvents: true,
309
+ autoTrackPageViews: true,
310
+ autoTrackSessions: true,
311
+ }
170
312
  }
171
313
  });
172
314
  ```
@@ -184,16 +326,18 @@ import * as Logger from '@crimson-education/browser-logger';
184
326
 
185
327
  // No configuration
186
328
  Logger.init({
187
- ...
188
- gtm: true,
329
+ reporters: {
330
+ gtm: true,
331
+ }
189
332
  });
190
333
 
191
334
  // With configuration
192
335
  Logger.init({
193
- ...
194
- gtm: {
195
- ignoreBreadcrumbCategories: ['fetch']
196
- },
336
+ reporters: {
337
+ gtm: {
338
+ ignoreBreadcrumbCategories: ['fetch']
339
+ }
340
+ }
197
341
  });
198
342
  ```
199
343
 
@@ -201,7 +345,8 @@ Check out the [`GTMReporterConfig`](https://github.com/crimson-education/browser
201
345
 
202
346
  ### Functions
203
347
 
204
- See the [src/index.ts](./src/index.ts) file for all exported functions of the Logger.
348
+ See the [src/logger/index.ts](./src/logger/index.ts) file for all exported functions of the Logger.
349
+ See the [src/reporter/index.ts](./src/reporter/index.ts) file for all exported functions of the Reporter.
205
350
 
206
351
  ### Improve Session Tracking with Component names
207
352
 
package/lib/index.d.ts CHANGED
@@ -1,83 +1,13 @@
1
- import { ILogger, Metadata, ReporterBreadcrumb, ReporterEvent, ReporterFilters, ReportError, ReportUser, ServiceInfo, TrackedReporterEvent } from './types';
2
- import { DatadogReporterConfig, GTMReporterConfig, AmplifyReporterConfig } from './reporters';
1
+ import { ReporterConfigurations, ServiceInfo } from './types';
3
2
  export * from './types';
4
- export declare let logger: ILogger | null;
5
- export declare type ReporterType = 'datadog' | 'gtm' | 'amplify';
6
- export declare type ReporterConfig = ServiceInfo & {
7
- datadog?: DatadogReporterConfig;
8
- amplify?: AmplifyReporterConfig;
9
- gtm?: true | GTMReporterConfig;
3
+ export * from './reporters';
4
+ export * from './logger';
5
+ export declare type LoggerConfig = ServiceInfo & {
6
+ reporters?: ReporterConfigurations;
10
7
  };
11
8
  /**
12
9
  * Initializes the logger and reporters.
13
10
  * @param config Reporter config options.
14
11
  */
15
- export declare function init(config: ReporterConfig): void;
16
- /**
17
- * Tracks an Analytics event.
18
- */
19
- export declare function trackEvent(event: ReporterEvent): void;
20
- /**
21
- * Tracks an Analytics event, recording the time since the last event, if available.
22
- */
23
- export declare function trackEventSinceLastAction(event: ReporterEvent): void;
24
- /**
25
- * Gets the last tracked event, if available.
26
- */
27
- export declare function getLastTrackedEvent(): TrackedReporterEvent | null;
28
- /**
29
- * Breadcrumbs to create a trail of events that happened prior to an issue.
30
- * These events are very similar to traditional logs, but can record more rich structured data.
31
- */
32
- export declare function addBreadcrumb(breadcrumb: ReporterBreadcrumb): void;
33
- /**
34
- * Adds global metadata to all events.
35
- * @param metadata Metadata to add.
36
- * @param filters Optional filters to specify which reporters to add metadata to.
37
- */
38
- export declare function addMetadata(metadata: Metadata, filters?: ReporterFilters): void;
39
- /**
40
- * Sets the user information in Analytics.
41
- * @param user User information, or null to clear.
42
- * @param filters Optional filters to specify which reporters to set the user for.
43
- */
44
- export declare function setUser(user: ReportUser | null, filters?: ReporterFilters): void;
45
- /**
46
- * Sets the route name in Analytics.
47
- * Some Analytics services use this differentiate SPA Route vs Page changes.
48
- * @param routeName Name of the Route.
49
- * @param filters Optional filters to specify which reporters to set the route name for.
50
- */
51
- export declare function setRouteName(routeName: string, filters?: ReporterFilters): void;
52
- /**
53
- * Sets the page name in Analytics.
54
- * @param pageName Name of the Page.
55
- * @param filters Optional filters to specify which reporters to set the page name for.
56
- */
57
- export declare function setPageName(pageName: string, filters?: ReporterFilters): void;
58
- /**
59
- * Reports an Error in Reporters that support error tracking.
60
- * @param error Error data.
61
- * @param metadata Metadata to add to the error.
62
- * @param filters Optional filters to specify which reporters to report the error to.
63
- */
64
- export declare function reportError(error: ReportError, metadata?: Metadata, filters?: ReporterFilters): void;
65
- /**
66
- * Starts a session recording in Analytics, e.g. RUM Session Replay
67
- * @param filters Optional filters to specify which reporters to start a session recording for.
68
- */
69
- export declare function recordSession(filters?: ReporterFilters): void;
70
- /**
71
- * Stops a session recording in Analytics, e.g. RUM Session Replay
72
- * @param filters Optional filters to specify which reporters to stop a session recording for.
73
- */
74
- export declare function recordSessionStop(filters?: ReporterFilters): void;
75
- /**
76
- * Creates a Logger instance.
77
- * @param name Name of the Logger.
78
- * @param options Logger configuration options.
79
- */
80
- export declare function createLogger(name?: string, options?: {
81
- metadata?: Metadata;
82
- }): ILogger;
12
+ export declare function init(config: LoggerConfig): void;
83
13
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EAEP,QAAQ,EACR,kBAAkB,EAClB,aAAa,EACb,eAAe,EACf,WAAW,EACX,UAAU,EACV,WAAW,EACX,oBAAoB,EACrB,MAAM,SAAS,CAAC;AAEjB,OAAO,EAGL,qBAAqB,EAErB,iBAAiB,EAEjB,qBAAqB,EACtB,MAAM,aAAa,CAAC;AAErB,cAAc,SAAS,CAAC;AAExB,eAAO,IAAI,MAAM,EAAE,OAAO,GAAG,IAAW,CAAC;AAEzC,oBAAY,YAAY,GAAG,SAAS,GAAG,KAAK,GAAG,SAAS,CAAC;AAEzD,oBAAY,cAAc,GAAG,WAAW,GAAG;IAEzC,OAAO,CAAC,EAAE,qBAAqB,CAAC;IAGhC,OAAO,CAAC,EAAE,qBAAqB,CAAC;IAGhC,GAAG,CAAC,EAAE,IAAI,GAAG,iBAAiB,CAAC;CAChC,CAAC;AAMF;;;GAGG;AACH,wBAAgB,IAAI,CAAC,MAAM,EAAE,cAAc,QAuB1C;AAkBD;;GAEG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI,CAIrD;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI,CAgBpE;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,oBAAoB,GAAG,IAAI,CAOjE;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,UAAU,EAAE,kBAAkB,GAAG,IAAI,CAIlE;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAI/E;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,UAAU,GAAG,IAAI,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAIhF;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAI/E;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAI7E;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAIpG;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAI7D;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAIjE;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;CAAE,GAAG,OAAO,CAUtF"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAQ9D,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC;AAEzB,oBAAY,YAAY,GAAG,WAAW,GAAG;IAAE,SAAS,CAAC,EAAE,sBAAsB,CAAA;CAAE,CAAC;AAIhF;;;GAGG;AACH,wBAAgB,IAAI,CAAC,MAAM,EAAE,YAAY,QA2CxC"}
package/lib/index.js CHANGED
@@ -14,201 +14,57 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.createLogger = exports.recordSessionStop = exports.recordSession = exports.reportError = exports.setPageName = exports.setRouteName = exports.setUser = exports.addMetadata = exports.addBreadcrumb = exports.getLastTrackedEvent = exports.trackEventSinceLastAction = exports.trackEvent = exports.init = exports.logger = void 0;
18
- const utils_1 = require("./utils");
17
+ exports.init = void 0;
18
+ const logger_1 = require("./logger");
19
19
  const reporters_1 = require("./reporters");
20
+ const gtmReporter_1 = require("./reporters/gtmReporter");
21
+ const amplifyReporter_1 = require("./reporters/amplifyReporter");
22
+ const datadogReporter_1 = require("./reporters/datadogReporter");
23
+ const logReporter_1 = require("./reporters/logReporter");
20
24
  __exportStar(require("./types"), exports);
21
- exports.logger = null;
22
- const reporters = {};
25
+ __exportStar(require("./reporters"), exports);
26
+ __exportStar(require("./logger"), exports);
23
27
  let initialized = false;
24
- let ddInitialized = false;
25
28
  /**
26
29
  * Initializes the logger and reporters.
27
30
  * @param config Reporter config options.
28
31
  */
29
32
  function init(config) {
30
- initialized = true;
31
- if (config.datadog) {
32
- reporters['datadog'] = (0, reporters_1.datadogReporter)(config, config.datadog);
33
- ddInitialized = true;
34
- }
35
- if (config.amplify) {
36
- reporters['amplify'] = (0, reporters_1.amplifyReporter)(config, config.amplify);
37
- }
38
- if (config.gtm) {
39
- reporters['gtm'] = (0, reporters_1.gtmReporter)(config, typeof config.gtm === 'boolean' ? {} : config.gtm);
40
- }
41
- if (config.defaultMetadata) {
42
- for (const reporter of Object.values(reporters)) {
43
- reporter.addMetadata(config.defaultMetadata);
44
- }
33
+ var _a, _b, _c, _d, _e, _f;
34
+ // Some reporters don't like being initialized multiple times.
35
+ if (initialized) {
36
+ return;
45
37
  }
46
- exports.logger = createLogger('Reporter');
38
+ initialized = true;
39
+ // Log Reporter enabled by default.
40
+ const logReporterConfig = (_b = (_a = config.reporters) === null || _a === void 0 ? void 0 : _a.log) !== null && _b !== void 0 ? _b : true;
41
+ if (logReporterConfig !== false) {
42
+ reporters_1.reporters['log'] = (0, logReporter_1.logReporter)(config, typeof logReporterConfig === 'boolean' ? {} : logReporterConfig);
43
+ }
44
+ if ((_c = config.reporters) === null || _c === void 0 ? void 0 : _c.datadog) {
45
+ reporters_1.reporters['datadog'] = (0, datadogReporter_1.datadogReporter)(config, config.reporters.datadog);
46
+ }
47
+ if ((_d = config.reporters) === null || _d === void 0 ? void 0 : _d.amplify) {
48
+ reporters_1.reporters['amplify'] = (0, amplifyReporter_1.amplifyReporter)(config, config.reporters.amplify);
49
+ }
50
+ if ((_e = config.reporters) === null || _e === void 0 ? void 0 : _e.gtm) {
51
+ reporters_1.reporters['gtm'] = (0, gtmReporter_1.gtmReporter)(config, typeof config.reporters.gtm === 'boolean' ? {} : config.reporters.gtm);
52
+ }
53
+ const defaultMetadata = {
54
+ ...((_f = config.defaultMetadata) !== null && _f !== void 0 ? _f : {}),
55
+ service: config.service,
56
+ environment: config.environment,
57
+ version: config.version,
58
+ };
59
+ // Sets the global log level, if specified.
60
+ if (config.logLevel) {
61
+ (0, logger_1.setLogLevel)(config.logLevel);
62
+ }
63
+ // Sets the global event level, if specified.
64
+ if (config.eventLevel) {
65
+ (0, reporters_1.setEventLevel)(config.eventLevel);
66
+ }
67
+ (0, reporters_1.addMetadata)(defaultMetadata);
47
68
  }
48
69
  exports.init = init;
49
- /**
50
- * Gets reporters, optionally with filters.
51
- * @param filters Filters to remove or specify specific reporters.
52
- * @returns Selected reporters, or all registered reporters.
53
- */
54
- function getReporters(filters) {
55
- let result = Object.entries(reporters);
56
- if (filters === null || filters === void 0 ? void 0 : filters.excludeReporters) {
57
- result = result.filter(([key]) => { var _a; return !((_a = filters === null || filters === void 0 ? void 0 : filters.excludeReporters) === null || _a === void 0 ? void 0 : _a.includes(key)); });
58
- }
59
- if (filters === null || filters === void 0 ? void 0 : filters.toReporters) {
60
- result = result.filter(([key]) => { var _a; return (_a = filters === null || filters === void 0 ? void 0 : filters.toReporters) === null || _a === void 0 ? void 0 : _a.includes(key); });
61
- }
62
- return result.map(([, reporter]) => reporter);
63
- }
64
- /**
65
- * Tracks an Analytics event.
66
- */
67
- function trackEvent(event) {
68
- for (const reporter of getReporters(event)) {
69
- reporter.trackEvent(event);
70
- }
71
- }
72
- exports.trackEvent = trackEvent;
73
- /**
74
- * Tracks an Analytics event, recording the time since the last event, if available.
75
- */
76
- function trackEventSinceLastAction(event) {
77
- const lastEvent = getLastTrackedEvent();
78
- if (lastEvent) {
79
- const duration = new Date().getTime() - lastEvent.occurred.getTime();
80
- trackEvent({
81
- ...event,
82
- metadata: {
83
- ...event.metadata,
84
- lastEventName: lastEvent.message,
85
- timeSinceLastEvent: duration,
86
- },
87
- });
88
- }
89
- else {
90
- trackEvent(event);
91
- }
92
- sessionStorage.setItem('loggerLastEvent', JSON.stringify({ ...event, occurred: new Date() }));
93
- }
94
- exports.trackEventSinceLastAction = trackEventSinceLastAction;
95
- /**
96
- * Gets the last tracked event, if available.
97
- */
98
- function getLastTrackedEvent() {
99
- const eventStr = sessionStorage.getItem('loggerLastEvent');
100
- if (!eventStr)
101
- return null;
102
- const event = JSON.parse(eventStr);
103
- event.occurred = new Date(event.occurred);
104
- return event;
105
- }
106
- exports.getLastTrackedEvent = getLastTrackedEvent;
107
- /**
108
- * Breadcrumbs to create a trail of events that happened prior to an issue.
109
- * These events are very similar to traditional logs, but can record more rich structured data.
110
- */
111
- function addBreadcrumb(breadcrumb) {
112
- for (const reporter of getReporters(breadcrumb)) {
113
- reporter.addBreadcrumb(breadcrumb);
114
- }
115
- }
116
- exports.addBreadcrumb = addBreadcrumb;
117
- /**
118
- * Adds global metadata to all events.
119
- * @param metadata Metadata to add.
120
- * @param filters Optional filters to specify which reporters to add metadata to.
121
- */
122
- function addMetadata(metadata, filters) {
123
- for (const reporter of getReporters(filters)) {
124
- reporter.addMetadata(metadata);
125
- }
126
- }
127
- exports.addMetadata = addMetadata;
128
- /**
129
- * Sets the user information in Analytics.
130
- * @param user User information, or null to clear.
131
- * @param filters Optional filters to specify which reporters to set the user for.
132
- */
133
- function setUser(user, filters) {
134
- for (const reporter of getReporters(filters)) {
135
- reporter.setUser(user);
136
- }
137
- }
138
- exports.setUser = setUser;
139
- /**
140
- * Sets the route name in Analytics.
141
- * Some Analytics services use this differentiate SPA Route vs Page changes.
142
- * @param routeName Name of the Route.
143
- * @param filters Optional filters to specify which reporters to set the route name for.
144
- */
145
- function setRouteName(routeName, filters) {
146
- for (const reporter of getReporters(filters)) {
147
- reporter.setRouteName(routeName);
148
- }
149
- }
150
- exports.setRouteName = setRouteName;
151
- /**
152
- * Sets the page name in Analytics.
153
- * @param pageName Name of the Page.
154
- * @param filters Optional filters to specify which reporters to set the page name for.
155
- */
156
- function setPageName(pageName, filters) {
157
- for (const reporter of getReporters(filters)) {
158
- reporter.setPageName(pageName);
159
- }
160
- }
161
- exports.setPageName = setPageName;
162
- /**
163
- * Reports an Error in Reporters that support error tracking.
164
- * @param error Error data.
165
- * @param metadata Metadata to add to the error.
166
- * @param filters Optional filters to specify which reporters to report the error to.
167
- */
168
- function reportError(error, metadata, filters) {
169
- var _a;
170
- for (const reporter of getReporters(filters)) {
171
- (_a = reporter.reportError) === null || _a === void 0 ? void 0 : _a.call(reporter, error, metadata);
172
- }
173
- }
174
- exports.reportError = reportError;
175
- /**
176
- * Starts a session recording in Analytics, e.g. RUM Session Replay
177
- * @param filters Optional filters to specify which reporters to start a session recording for.
178
- */
179
- function recordSession(filters) {
180
- var _a;
181
- for (const reporter of getReporters(filters)) {
182
- (_a = reporter.recordSession) === null || _a === void 0 ? void 0 : _a.call(reporter);
183
- }
184
- }
185
- exports.recordSession = recordSession;
186
- /**
187
- * Stops a session recording in Analytics, e.g. RUM Session Replay
188
- * @param filters Optional filters to specify which reporters to stop a session recording for.
189
- */
190
- function recordSessionStop(filters) {
191
- var _a;
192
- for (const reporter of getReporters(filters)) {
193
- (_a = reporter.recordSessionStop) === null || _a === void 0 ? void 0 : _a.call(reporter);
194
- }
195
- }
196
- exports.recordSessionStop = recordSessionStop;
197
- /**
198
- * Creates a Logger instance.
199
- * @param name Name of the Logger.
200
- * @param options Logger configuration options.
201
- */
202
- function createLogger(name, options) {
203
- if (!initialized) {
204
- throw new Error('You must call init on BrowserLogger before creating a logger');
205
- }
206
- if (ddInitialized) {
207
- return (0, reporters_1.datadogLogger)(name, options);
208
- }
209
- else {
210
- return (0, utils_1.consoleLogger)(name, options);
211
- }
212
- }
213
- exports.createLogger = createLogger;
214
70
  //# sourceMappingURL=index.js.map