Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Browser-side analytics services: use core logger #184520

Merged
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import { trackPerformanceMeasureEntries } from './track_performance_measure_entr
import { trackClicks } from './track_clicks';

import { getSessionId } from './get_session_id';
import { createLogger } from './logger';
import { trackViewportSize } from './track_viewport_size';

/** @internal */
Expand All @@ -32,7 +31,7 @@ export class AnalyticsService {
constructor(core: CoreContext) {
this.analyticsClient = createAnalytics({
isDev: core.env.mode.dev,
logger: createLogger(core.env.mode.dev),
logger: core.logger.get('analytics'),
// TODO: We need to be able to edit sendTo once we resolve the telemetry config.
// For now, we are relying on whether it's a distributable or running from source.
sendTo: core.env.packageInfo.dist ? 'production' : 'staging',
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@
},
"include": ["**/*.ts"],
"kbn_references": [
"@kbn/logging",
"@kbn/analytics-client",
"@kbn/ebt-tools",
"@kbn/core-base-browser-internal",
"@kbn/core-injected-metadata-browser-internal",
"@kbn/core-analytics-browser",
"@kbn/core-base-browser-mocks",
"@kbn/core-injected-metadata-browser-mocks",
"@kbn/security-hardening"
],
"exclude": ["target/**/*"]
}
6 changes: 6 additions & 0 deletions packages/core/analytics/core-analytics-browser/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
# @kbn/core-analytics-browser

This package contains the public types for Core's browser-side analytics service.

## Enabling debug logging

Most events-related messages are logged under the `debug` level, which is silenced by default.

Until per-context logging configuration is available, use `logging.browser.root.level: DEBUG` to enable debug logging.
30 changes: 13 additions & 17 deletions packages/kbn-analytics/src/reporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@
* Side Public License, v 1.
*/

import type { Logger } from '@kbn/logging';
import { wrapArray } from './util';
import { Metric, createUiCounterMetric, trackUsageAgent, ApplicationUsageMetric } from './metrics';

import { Storage, ReportStorageManager } from './storage';
import { Report, ReportManager } from './report';

export interface ReporterConfig {
http: ReportHTTP;
logger: Logger;
storage?: Storage;
checkInterval?: number;
debug?: boolean;
storageKey?: string;
}

Expand All @@ -26,20 +26,21 @@ export class Reporter {
checkInterval: number;
private interval?: NodeJS.Timer;
private http: ReportHTTP;
private logger: Logger;
private reportManager: ReportManager;
private storageManager: ReportStorageManager;
private debug: boolean;
private retryCount = 0;
private readonly maxRetries = 3;

constructor(config: ReporterConfig) {
const { http, storage, debug, checkInterval = 90000, storageKey = 'analytics' } = config;
const { http, logger, storage, checkInterval = 90000, storageKey = 'analytics' } = config;

this.http = http;
this.logger = logger;
this.checkInterval = checkInterval;
this.storageManager = new ReportStorageManager(storageKey, storage);
const storedReport = this.storageManager.get();
this.reportManager = new ReportManager(storedReport);
this.debug = !!debug;
}

private saveToReport(newMetrics: Metric[]) {
Expand All @@ -62,36 +63,31 @@ export class Reporter {
}
};

private log(message: unknown) {
if (this.debug) {
// eslint-disable-next-line no-console
console.debug(message);
}
}

public reportUiCounter = (
appName: string,
type: string,
eventNames: string | string[],
count?: number
) => {
const metrics = wrapArray(eventNames).map((eventName) => {
this.log(`${type} Metric -> (${appName}:${eventName}):`);
this.logger.debug(`${type} Metric -> (${appName}:${eventName}):`);
const report = createUiCounterMetric({ type, appName, eventName, count });
this.log(report);
this.logger.debug(JSON.stringify(report));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT we can wrap this one under isLevelEnabled, to avoid JSON.stringify() cost when not needed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call 👍

return report;
});
this.saveToReport(metrics);
};

public reportUserAgent = (appName: string) => {
this.log(`Reporting user-agent.`);
this.logger.debug(`Reporting user-agent.`);
const report = trackUsageAgent(appName);
this.saveToReport([report]);
};

public reportApplicationUsage(appUsageReport: ApplicationUsageMetric) {
this.log(`Reporting application usage for ${appUsageReport.appId}, ${appUsageReport.viewId}`);
this.logger.debug(
`Reporting application usage for ${appUsageReport.appId}, ${appUsageReport.viewId}`
);
this.saveToReport([appUsageReport]);
}

Expand All @@ -101,7 +97,7 @@ export class Reporter {
await this.http(this.reportManager.report);
this.flushReport();
} catch (err) {
this.log(`Error Sending Metrics Report ${err}`);
this.logger.warn(`Error Sending Metrics Report ${err}`);
this.retryCount = this.retryCount + 1;
const versionMismatch =
this.reportManager.report.reportVersion !== ReportManager.REPORT_VERSION;
Expand Down
3 changes: 3 additions & 0 deletions packages/kbn-analytics/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,8 @@
],
"exclude": [
"target/**/*",
],
"kbn_references": [
"@kbn/logging",
]
}
7 changes: 3 additions & 4 deletions src/plugins/usage_collection/public/plugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,16 @@ export class UsageCollectionPlugin
private subscriptions: Subscription[] = [];
private reporter?: Reporter;
private config: PublicConfigType;
constructor(initializerContext: PluginInitializerContext) {
this.config = initializerContext.config.get<PublicConfigType>();
constructor(private readonly initContext: PluginInitializerContext) {
this.config = initContext.config.get<PublicConfigType>();
}

public setup({ http }: CoreSetup): UsageCollectionSetup {
const localStorage = new Storage(window.localStorage);
const debug = this.config.uiCounters.debug;

this.reporter = createReporter({
localStorage,
debug,
logger: this.initContext.logger.get('reporter'),
fetch: http,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,22 @@
* Side Public License, v 1.
*/

import type { Logger } from '@kbn/logging';
import { Reporter, Storage } from '@kbn/analytics';
import { HttpSetup } from '@kbn/core/public';
import { UiCounters } from '../../common/types';

interface AnalyicsReporterConfig {
interface AnalyticsReporterConfig {
localStorage: Storage;
debug: boolean;
logger: Logger;
fetch: HttpSetup;
}

export function createReporter(config: AnalyicsReporterConfig): Reporter {
const { localStorage, debug, fetch } = config;
export function createReporter(config: AnalyticsReporterConfig): Reporter {
const { localStorage, logger, fetch } = config;

return new Reporter({
debug,
logger,
storage: localStorage,
async http(report) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down
1 change: 1 addition & 0 deletions src/plugins/usage_collection/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"@kbn/i18n",
"@kbn/core-http-server-mocks",
"@kbn/analytics-collection-utils",
"@kbn/logging",
],
"exclude": [
"target/**/*",
Expand Down